import json
import requests
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, current_app
from flask_login import login_required, current_user
from app.extensions import db, csrf
from app.models.report import Report
from app.models.services import GammaPresentationRequest

gamma_bp = Blueprint("gamma", __name__, url_prefix="/gamma")


@gamma_bp.route("/create/<int:report_id>", methods=["GET", "POST"])
@login_required
def create(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return redirect(url_for("dashboard.index"))

    if request.method == "POST":
        format_type = request.form.get("format_type", "presentation")
        theme = request.form.get("theme", "")

        synthesis = report.synthesis_result or {}
        content_text = _build_gamma_content(report, synthesis)

        gamma_req = GammaPresentationRequest(
            user_id=current_user.id,
            report_id=report.id,
            format_type=format_type,
            theme=theme,
            status="generating",
        )
        db.session.add(gamma_req)
        db.session.commit()

        api_key = current_app.config.get("GAMMA_API_KEY", "")
        if api_key:
            try:
                result = _call_gamma_api(api_key, content_text, format_type, theme)
                gamma_req.gamma_id = result.get("id", "")
                gamma_req.gamma_url = result.get("url", "")
                gamma_req.status = "completed"
            except Exception as e:
                gamma_req.status = "error"
                gamma_req.error_message = str(e)
        else:
            gamma_req.status = "error"
            gamma_req.error_message = "Gamma API key not configured"

        db.session.commit()

        if gamma_req.status == "completed" and gamma_req.gamma_url:
            return redirect(gamma_req.gamma_url)

        flash("تم إنشاء طلب العرض التقديمي. " + (gamma_req.error_message or ""), "info")
        return redirect(url_for("study.view", report_id=report.id))

    presentations = GammaPresentationRequest.query.filter_by(
        report_id=report_id, user_id=current_user.id
    ).order_by(GammaPresentationRequest.created_at.desc()).all()

    return render_template("gamma/create.html", report=report, presentations=presentations)


@gamma_bp.route("/api/generate", methods=["POST"])
@login_required
@csrf.exempt
def api_generate():
    data = request.get_json() or {}
    report_id = data.get("report_id")
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    format_type = data.get("format_type", "presentation")
    theme = data.get("theme", "")

    synthesis = report.synthesis_result or {}
    content_text = _build_gamma_content(report, synthesis)

    api_key = current_app.config.get("GAMMA_API_KEY", "")
    if not api_key:
        return jsonify({"error": "Gamma API key not configured", "fallback": "pptx"}), 400

    try:
        result = _call_gamma_api(api_key, content_text, format_type, theme)
        gamma_req = GammaPresentationRequest(
            user_id=current_user.id,
            report_id=report.id,
            format_type=format_type,
            theme=theme,
            gamma_id=result.get("id", ""),
            gamma_url=result.get("url", ""),
            status="completed",
        )
        db.session.add(gamma_req)
        db.session.commit()
        return jsonify({"url": result.get("url", ""), "id": result.get("id", "")})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


def _build_gamma_content(report, synthesis):
    sections = []
    sections.append(f"# {report.project_name}")
    sections.append(f"\n{report.project_description}")

    if synthesis.get("executive_summary"):
        sections.append(f"\n## Executive Summary\n{synthesis['executive_summary']}")
    if synthesis.get("market_opportunity"):
        sections.append(f"\n## Market Opportunity\n{synthesis['market_opportunity']}")
    if synthesis.get("swot"):
        swot = synthesis["swot"]
        sections.append("\n## SWOT Analysis")
        for key in ["strengths", "weaknesses", "opportunities", "threats"]:
            if swot.get(key):
                items = swot[key] if isinstance(swot[key], list) else [swot[key]]
                sections.append(f"\n### {key.title()}")
                for item in items:
                    sections.append(f"- {item}")
    if synthesis.get("financial_summary"):
        sections.append(f"\n## Financial Summary\n{synthesis['financial_summary']}")
    if synthesis.get("verdict"):
        sections.append(f"\n## Verdict: {synthesis['verdict']}")

    return "\n".join(sections)


def _call_gamma_api(api_key, content, format_type, theme):
    url = "https://api.gamma.app/v1/generate"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    payload = {
        "inputText": content,
        "format": format_type,
    }
    if theme:
        payload["theme"] = theme

    resp = requests.post(url, json=payload, headers=headers, timeout=120)
    resp.raise_for_status()
    return resp.json()
