from flask import Flask, request, jsonify, render_template_string
from .manager import TradingTwinsManager

app = Flask(__name__)
manager = TradingTwinsManager()

# Einfaches HTML-Template für Feedback
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <title>Trading Twins Status</title>
    <style>
        body { font-family: sans-serif; text-align: center; padding: 50px; }
        .success { color: green; font-size: 24px; }
        .cancelled { color: red; font-size: 24px; }
        .info { color: gray; margin-top: 20px; }
    </style>
</head>
<body>
    <h1>{title}</h1>
    <p class="{status_class}">{message}</p>
    <p class="info">Job ID: {job_uuid}</p>
</body>
</html>
"""

@app.route('/action/approve/<job_uuid>', methods=['GET'])
def approve_job(job_uuid):
    current_status = manager.get_job_status(job_uuid)
    
    if not current_status:
        return render_template_string(HTML_TEMPLATE, title="Fehler", status_class="cancelled", message="Job nicht gefunden.", job_uuid=job_uuid), 404

    if current_status == 'pending':
        manager.update_job_status(job_uuid, 'approved')
        # TODO: Hier würde der E-Mail-Versand sofort getriggert werden (Phase 3)
        return render_template_string(HTML_TEMPLATE, title="Erfolg", status_class="success", message="✅ E-Mail wird jetzt versendet!", job_uuid=job_uuid)
    elif current_status == 'approved':
        return render_template_string(HTML_TEMPLATE, title="Info", status_class="success", message="⚠️ Job wurde bereits genehmigt.", job_uuid=job_uuid)
    else:
        return render_template_string(HTML_TEMPLATE, title="Info", status_class="cancelled", message=f"Job-Status ist bereits: {current_status}", job_uuid=job_uuid)

@app.route('/action/cancel/<job_uuid>', methods=['GET'])
def cancel_job(job_uuid):
    current_status = manager.get_job_status(job_uuid)
    
    if not current_status:
        return render_template_string(HTML_TEMPLATE, title="Fehler", status_class="cancelled", message="Job nicht gefunden.", job_uuid=job_uuid), 404

    if current_status == 'pending':
        manager.update_job_status(job_uuid, 'cancelled')
        return render_template_string(HTML_TEMPLATE, title="Abbruch", status_class="cancelled", message="❌ E-Mail-Versand gestoppt.", job_uuid=job_uuid)
    else:
        return render_template_string(HTML_TEMPLATE, title="Info", status_class="info", message=f"Job konnte nicht gestoppt werden (Status: {current_status}).", job_uuid=job_uuid)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8004)
