from datetime import datetime
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from app.extensions import db, csrf
from app.models.features import InvestorContact

investor_crm_bp = Blueprint("investor_crm", __name__, url_prefix="/investor-crm")


@investor_crm_bp.route("/")
@login_required
def index():
    stage = request.args.get("stage", "").strip()
    query = InvestorContact.query.filter_by(user_id=current_user.id)
    if stage:
        query = query.filter_by(stage=stage)
    contacts = query.order_by(InvestorContact.created_at.desc()).all()
    stages = ["identified", "contacted", "meeting_scheduled", "negotiating", "committed", "declined"]
    return render_template("investor_crm/index.html", contacts=contacts, stages=stages, current_stage=stage)


@investor_crm_bp.route("/add", methods=["POST"])
@login_required
def add():
    contact = InvestorContact(
        user_id=current_user.id,
        report_id=request.form.get("report_id", type=int),
        name=request.form.get("name", "").strip(),
        company=request.form.get("company", "").strip(),
        email=request.form.get("email", "").strip(),
        phone=request.form.get("phone", "").strip(),
        stage=request.form.get("stage", "identified"),
        notes=request.form.get("notes", "").strip(),
    )
    db.session.add(contact)
    db.session.commit()
    flash("Investor contact added.", "success")
    return redirect(url_for("investor_crm.index"))


@investor_crm_bp.route("/update/<int:cid>", methods=["POST"])
@login_required
def update(cid):
    contact = InvestorContact.query.get_or_404(cid)
    if contact.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("investor_crm.index"))
    contact.stage = request.form.get("stage", contact.stage)
    contact.notes = request.form.get("notes", contact.notes)
    contact.last_contact = datetime.utcnow()
    next_days = request.form.get("followup_days", type=int)
    if next_days:
        from datetime import timedelta
        contact.next_followup = datetime.utcnow() + timedelta(days=next_days)
    db.session.commit()
    flash("Contact updated.", "success")
    return redirect(url_for("investor_crm.index"))


@investor_crm_bp.route("/delete/<int:cid>", methods=["POST"])
@login_required
def delete(cid):
    contact = InvestorContact.query.get_or_404(cid)
    if contact.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("investor_crm.index"))
    db.session.delete(contact)
    db.session.commit()
    flash("Contact deleted.", "success")
    return redirect(url_for("investor_crm.index"))


# ─── AI Suggest Investor ─────────────────────────────────
@investor_crm_bp.route("/api/ai-suggest", methods=["POST"])
@login_required
@csrf.exempt
def api_ai_suggest():
    import json as _json
    from app.ai.diamond import call_ai, run_sync
    from app.models.report import Report
    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": "غير مصرح"}), 403

    synthesis = report.synthesis_result or {}
    prompt = f"""بناءً على بيانات دراسة الجدوى التالية، اقترح مستثمراً مناسباً (حقيقي أو نموذجي).

اسم المشروع: {report.project_name}
الوصف: {report.project_description}
الملخص: {synthesis.get('executive_summary', '')[:400]}

أرجع JSON فقط:
{{
  "investor_name": "اسم المستثمر",
  "firm": "اسم الشركة أو الصندوق",
  "email": "example@fund.com",
  "phone": "+966500000000",
  "stage": "identified",
  "notes": "ملاحظات عن سبب مناسبة هذا المستثمر للمشروع"
}}
اقترح مستثمراً واقعياً من السوق السعودي أو الخليجي."""

    try:
        messages = [
            {"role": "system", "content": "أنت خبير استثمار. أرجع JSON فقط."},
            {"role": "user", "content": prompt},
        ]
        result = run_sync(call_ai(messages, model_type="fast"))
        result_clean = result.strip()
        if result_clean.startswith("```"):
            result_clean = result_clean.split("\n", 1)[-1].rsplit("```", 1)[0].strip()
        return jsonify(_json.loads(result_clean))
    except Exception as e:
        return jsonify({"error": str(e)}), 500
