import json
from flask import Blueprint, render_template, request, redirect, url_for, 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 AdvisorChat

advisor_bp = Blueprint("advisor", __name__, url_prefix="/advisor")


@advisor_bp.route("/<int:report_id>")
@login_required
def index(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return redirect(url_for("dashboard.index"))

    messages = AdvisorChat.query.filter_by(
        report_id=report_id, user_id=current_user.id
    ).order_by(AdvisorChat.created_at.asc()).all()

    return render_template("advisor/index.html", report=report, messages=messages)


@advisor_bp.route("/api/message/<int:report_id>", methods=["POST"])
@csrf.exempt
@login_required
def send_message(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    data = request.get_json(silent=True) or {}
    user_msg = data.get("message", "").strip()
    if not user_msg:
        return jsonify({"error": "Empty message"}), 400

    # Save user message
    user_chat = AdvisorChat(
        report_id=report_id, user_id=current_user.id,
        role="user", content=user_msg
    )
    db.session.add(user_chat)
    db.session.commit()

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

        lang = "Arabic" if report.language == "ar" else "English"

        # Build context from report
        project_context = f"Project: {report.project_name}\nDescription: {report.project_description}\n"
        if report.synthesis_result:
            synthesis = json.dumps(report.synthesis_result, ensure_ascii=False)[:2000]
            project_context += f"Feasibility Study Summary:\n{synthesis}\n"
        if report.verdict:
            project_context += f"Verdict: {report.verdict}\n"

        # Get recent chat history (last 20 messages for context)
        recent = AdvisorChat.query.filter_by(
            report_id=report_id, user_id=current_user.id
        ).order_by(AdvisorChat.created_at.desc()).limit(20).all()
        recent.reverse()

        ai_messages = [
            {"role": "system", "content": (
                f"You are an AI Co-Founder and business advisor for this specific project. "
                f"You have deep knowledge of the project from the feasibility study.\n\n"
                f"{project_context}\n\n"
                f"Your role:\n"
                f"- Answer business questions specific to this project\n"
                f"- Give strategic advice on pricing, marketing, operations, hiring\n"
                f"- Help solve problems and make decisions\n"
                f"- Provide market insights and competitive strategies\n"
                f"- Be proactive: suggest next steps and warn about risks\n"
                f"- Remember the conversation history\n"
                f"- Be concise but thorough. Use bullet points when helpful.\n"
                f"Language: {lang}"
            )}
        ]

        for msg in recent:
            ai_messages.append({"role": msg.role, "content": msg.content})

        reply = run_sync(call_ai(ai_messages, model_type="fast"))

    except Exception as e:
        current_app.logger.error(f"Advisor chat failed: {e}")
        reply = "عذراً، حدث خطأ. حاول مرة أخرى." if report.language == "ar" else "Sorry, an error occurred. Please try again."

    # Save assistant reply
    bot_chat = AdvisorChat(
        report_id=report_id, user_id=current_user.id,
        role="assistant", content=reply
    )
    db.session.add(bot_chat)
    db.session.commit()

    return jsonify({"reply": reply})


@advisor_bp.route("/api/clear/<int:report_id>", methods=["POST"])
@csrf.exempt
@login_required
def clear_chat(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    AdvisorChat.query.filter_by(report_id=report_id, user_id=current_user.id).delete()
    db.session.commit()
    return jsonify({"status": "ok"})
