from flask import Flask, render_template, request
import subprocess

app = Flask(__name__, template_folder='templates')

@app.route('/', methods=["GET"])
def index():
    return render_template("index.html")

@app.route('/run', methods=["POST"])
def run_script():
    try:
        result = subprocess.run(
            ["python3", "/var/www/Python/Finialwitherroremail.py"],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            timeout=120,
            encoding='utf-8',
            errors='replace'
        )
        return render_template("result.html", status="✅ Script Output", output=result.stdout)
    except subprocess.TimeoutExpired:
        return render_template("result.html", status="⏰ Script Timeout", output="The script took too long to complete.")
    except Exception as e:
        return render_template("result.html", status="❌ Error", output=str(e))
