import json
from datetime import datetime
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.features import ProjectKPI, KPIEntry
from app.helpers.access import has_report_access

kpis_bp = Blueprint("kpis", __name__, url_prefix="/kpis")


@kpis_bp.route("/<int:report_id>")
@login_required
def index(report_id):
    report = Report.query.get_or_404(report_id)
    if not has_report_access(current_user, report):
        return redirect(url_for("dashboard.index"))

    kpis = ProjectKPI.query.filter_by(
        report_id=report_id, user_id=current_user.id
    ).order_by(ProjectKPI.category, ProjectKPI.id).all()

    current_month = datetime.utcnow().strftime("%Y-%m")

    return render_template("kpis/index.html",
        report=report, kpis=kpis, current_month=current_month)


@kpis_bp.route("/generate/<int:report_id>", methods=["POST"])
@csrf.exempt
@login_required
def generate(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403
    if not report.synthesis_result:
        return jsonify({"error": "Report not complete"}), 400

    existing = ProjectKPI.query.filter_by(report_id=report_id, user_id=current_user.id).first()
    if existing:
        return jsonify({"error": "KPIs already exist", "redirect": url_for("kpis.index", report_id=report_id)})

    try:
        from app.ai.diamond import call_ai, run_sync, _parse_json

        lang = "Arabic" if report.language == "ar" else "English"
        synthesis = json.dumps(report.synthesis_result, ensure_ascii=False)[:3000]

        messages = [
            {"role": "system", "content": (
                f"You are a business KPI expert. Based on the feasibility study below, "
                f"define 8-12 key performance indicators the entrepreneur should track monthly.\n"
                f"Return JSON: {{\"kpis\": [{{\"name\": \"...\", \"unit\": \"SAR|%|عدد|...\", "
                f"\"target_value\": 1000, \"category\": \"financial|customers|operations|growth\"}}]}}\n"
                f"Include: revenue, expenses, profit margin, customer count, customer acquisition cost, "
                f"conversion rate, retention rate, and project-specific KPIs.\n"
                f"target_value should be the monthly target from the feasibility study projections.\n"
                f"Language: {lang}"
            )},
            {"role": "user", "content": f"Project: {report.project_name}\n\nFeasibility Study:\n{synthesis}"}
        ]

        response = run_sync(call_ai(messages, model_type="fast"))
        data = _parse_json(response)

        if not data or "kpis" not in data:
            return jsonify({"error": "AI response invalid"}), 500

        for kpi_data in data["kpis"]:
            kpi = ProjectKPI(
                report_id=report_id,
                user_id=current_user.id,
                name=kpi_data.get("name", ""),
                unit=kpi_data.get("unit", ""),
                target_value=kpi_data.get("target_value"),
                category=kpi_data.get("category", "financial"),
            )
            db.session.add(kpi)

        db.session.commit()
        return jsonify({"status": "ok", "redirect": url_for("kpis.index", report_id=report_id)})

    except Exception as e:
        current_app.logger.error(f"KPI generation failed: {e}")
        return jsonify({"error": str(e)}), 500


@kpis_bp.route("/entry/<int:kpi_id>", methods=["POST"])
@csrf.exempt
@login_required
def add_entry(kpi_id):
    kpi = ProjectKPI.query.get_or_404(kpi_id)
    if kpi.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    data = request.get_json(silent=True) or {}
    month = data.get("month", datetime.utcnow().strftime("%Y-%m"))
    actual_value = data.get("actual_value")
    notes = data.get("notes", "")

    if actual_value is None:
        return jsonify({"error": "actual_value required"}), 400

    try:
        actual_value = float(actual_value)
    except (ValueError, TypeError):
        return jsonify({"error": "Invalid value"}), 400

    existing = KPIEntry.query.filter_by(kpi_id=kpi_id, month=month).first()
    if existing:
        existing.actual_value = actual_value
        existing.notes = notes
    else:
        entry = KPIEntry(kpi_id=kpi_id, month=month, actual_value=actual_value, notes=notes)
        db.session.add(entry)

    db.session.commit()
    return jsonify({"status": "ok"})


@kpis_bp.route("/report/<int:report_id>/ai-analysis", methods=["POST"])
@csrf.exempt
@login_required
def ai_analysis(report_id):
    """AI analyzes current KPI performance vs targets and gives recommendations."""
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    kpis = ProjectKPI.query.filter_by(report_id=report_id, user_id=current_user.id).all()
    if not kpis:
        return jsonify({"error": "No KPIs found"}), 400

    kpi_summary = []
    for kpi in kpis:
        latest = KPIEntry.query.filter_by(kpi_id=kpi.id).order_by(KPIEntry.month.desc()).first()
        kpi_summary.append({
            "name": kpi.name,
            "target": kpi.target_value,
            "actual": latest.actual_value if latest else None,
            "unit": kpi.unit,
            "category": kpi.category,
        })

    try:
        from app.ai.diamond import call_ai, run_sync

        lang = "Arabic" if report.language == "ar" else "English"
        messages = [
            {"role": "system", "content": (
                f"You are a business performance analyst. Analyze the KPI data below and provide:\n"
                f"1. Overall performance summary (2-3 sentences)\n"
                f"2. Top 3 areas of concern\n"
                f"3. Top 3 recommendations for improvement\n"
                f"4. What to focus on next month\n"
                f"Be specific and actionable. Language: {lang}"
            )},
            {"role": "user", "content": f"Project: {report.project_name}\n\nKPIs:\n{json.dumps(kpi_summary, ensure_ascii=False)}"}
        ]

        response = run_sync(call_ai(messages, model_type="fast"))
        return jsonify({"status": "ok", "analysis": response})

    except Exception as e:
        return jsonify({"error": str(e)}), 500
