from datetime import datetime
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, 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 ReportVersion, CompetitorMonitor, WhiteLabelConfig

advanced_bp = Blueprint("advanced", __name__, url_prefix="/advanced")

SUPPORTED_LANGUAGES = {
    "ar": "العربية", "en": "English", "fr": "Français",
    "tr": "Türkçe", "ur": "اردو", "es": "Español", "zh": "中文",
}


@advanced_bp.route("/translate/<int:report_id>", methods=["GET", "POST"])
@login_required
def translate(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    if request.method == "POST":
        target_lang = request.form.get("target_lang", "en")
        lang_name = SUPPORTED_LANGUAGES.get(target_lang, target_lang)
        try:
            from app.ai.diamond import call_ai, run_sync
            prompt = f"""Translate the following feasibility study synthesis to {lang_name}.
Keep all section headers, maintain JSON structure, preserve numbers exactly.
Original language: {report.language}

{report.synthesis_result}"""
            messages = [{"role": "system", "content": f"Translate accurately to {lang_name}. Return valid JSON."}, {"role": "user", "content": prompt}]
            result = run_sync(call_ai(messages, model_type="deep"))
            return render_template("advanced/translate_result.html", report=report, translated=result, target_lang=target_lang, lang_name=lang_name)
        except Exception as e:
            flash(f"Translation error: {str(e)}", "error")
    return render_template("advanced/translate.html", report=report, languages=SUPPORTED_LANGUAGES)


@advanced_bp.route("/valuation/<int:report_id>")
@login_required
def valuation(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    try:
        from app.ai.diamond import call_ai, run_sync
        prompt = f"""For the project "{report.project_name}":
{report.project_description}

Synthesis data: {report.synthesis_result}

Calculate startup valuation using 4 methods:
1. DCF (Discounted Cash Flow) — project 5 years of cash flow
2. Comparable Companies — estimate based on industry multiples
3. Scorecard Method — rate vs. typical startup (team, market, product, competition)
4. Berkus Method — assign value to 5 factors (sound idea, prototype, team, strategic relationships, product rollout)

Return JSON: {{"dcf": {{"value": 0, "explanation": "..."}}, "comparable": {{"value": 0, "explanation": "..."}}, "scorecard": {{"value": 0, "explanation": "..."}}, "berkus": {{"value": 0, "explanation": "..."}}, "recommended_range": {{"low": 0, "high": 0}}, "currency": "{current_user.currency or 'SAR'}"}}
Language: {"Arabic" if report.language == "ar" else "English"}"""
        messages = [{"role": "system", "content": "Return only valid JSON."}, {"role": "user", "content": prompt}]
        result = run_sync(call_ai(messages, model_type="deep"))
        import json
        try:
            valuation_data = json.loads(result)
        except Exception:
            valuation_data = {"error": result}
    except Exception as e:
        valuation_data = {"error": str(e)}
    return render_template("advanced/valuation.html", report=report, valuation=valuation_data)


@advanced_bp.route("/pitch-rehearsal/<int:report_id>", methods=["GET", "POST"])
@login_required
def pitch_rehearsal(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    feedback = None
    if request.method == "POST":
        pitch_text = request.form.get("pitch_text", "").strip()
        if pitch_text:
            try:
                from app.ai.diamond import call_ai, run_sync
                prompt = f"""You are a tough but fair venture capital investor evaluating a pitch.
The entrepreneur is pitching: "{report.project_name}"
Actual feasibility data: {report.synthesis_result}

Their pitch: "{pitch_text}"

Evaluate the pitch on these criteria (score each 1-10):
1. Clarity — Is the problem and solution clearly stated?
2. Market understanding — Do they know their TAM/SAM/SOM?
3. Financial credibility — Are the numbers realistic?
4. Competitive awareness — Do they know the competition?
5. Ask clarity — Is the investment ask clear?
6. Confidence & persuasion — Would you invest?

Return JSON: {{"scores": {{"clarity": 8, "market": 7, ...}}, "overall_score": 75, "strengths": ["..."], "weaknesses": ["..."], "tough_questions": ["Q1?", "Q2?", "Q3?"], "improved_pitch": "..."}}
Language: {"Arabic" if report.language == "ar" else "English"}"""
                messages = [{"role": "system", "content": "Return only valid JSON."}, {"role": "user", "content": prompt}]
                result = run_sync(call_ai(messages, model_type="deep"))
                import json
                try:
                    feedback = json.loads(result)
                except Exception:
                    feedback = {"raw": result}
            except Exception as e:
                feedback = {"error": str(e)}
    return render_template("advanced/pitch_rehearsal.html", report=report, feedback=feedback)


@advanced_bp.route("/pitch-simulator/<int:report_id>", methods=["POST"])
@csrf.exempt
@login_required
def pitch_simulator(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Access denied"}), 403
    data = request.get_json(silent=True) or {}
    user_answer = data.get("answer", "").strip()
    history = data.get("history", [])
    try:
        from app.ai.diamond import call_ai, run_sync
        system_msg = f"""You are a tough venture capital investor in a meeting with an entrepreneur pitching "{report.project_name}".
Project data: {report.synthesis_result}
Ask challenging questions about: market size, competition, financials, team, exit strategy.
Be skeptical but professional. Ask ONE question at a time.
If the entrepreneur has answered well, acknowledge it briefly then ask a harder question.
After 5-6 questions, give a final verdict: would you invest or not, and why.
Language: {"Arabic" if report.language == "ar" else "English"}"""
        messages = [{"role": "system", "content": system_msg}] + history
        if user_answer:
            messages.append({"role": "user", "content": user_answer})
        else:
            messages.append({"role": "user", "content": "مرحبا، أنا هنا لأعرض عليك مشروعي." if report.language == "ar" else "Hi, I'm here to pitch my project."})
        result = run_sync(call_ai(messages, model_type="fast"))
        return jsonify({"response": result})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@advanced_bp.route("/export-docx/<int:report_id>")
@login_required
def export_docx(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    try:
        from docx import Document
        from docx.shared import Inches, Pt, RGBColor
        doc = Document()
        style = doc.styles["Title"]
        style.font.size = Pt(24)
        doc.add_heading(f"Feasibility Study: {report.project_name}", 0)
        doc.add_paragraph(f"Generated by Jadwa AI — {datetime.utcnow().strftime('%Y-%m-%d')}")
        doc.add_paragraph("")
        doc.add_heading("Project Description", level=1)
        doc.add_paragraph(report.project_description)
        if report.synthesis_result:
            import json
            try:
                synthesis = json.loads(report.synthesis_result) if isinstance(report.synthesis_result, str) else report.synthesis_result
                for key, value in synthesis.items():
                    doc.add_heading(key.replace("_", " ").title(), level=1)
                    if isinstance(value, dict):
                        for k2, v2 in value.items():
                            doc.add_heading(k2.replace("_", " ").title(), level=2)
                            doc.add_paragraph(str(v2))
                    elif isinstance(value, list):
                        for item in value:
                            doc.add_paragraph(str(item), style="List Bullet")
                    else:
                        doc.add_paragraph(str(value))
            except Exception:
                doc.add_heading("Full Report", level=1)
                doc.add_paragraph(str(report.synthesis_result))
        import io
        buffer = io.BytesIO()
        doc.save(buffer)
        buffer.seek(0)
        return send_file(buffer, as_attachment=True, download_name=f"jadwa_{report.project_name}.docx",
                         mimetype="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
    except ImportError:
        flash("python-docx is required for Word export. Install: pip install python-docx", "error")
        return redirect(url_for("study.view", report_id=report_id))


@advanced_bp.route("/versions/<int:report_id>")
@login_required
def versions(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    versions = ReportVersion.query.filter_by(report_id=report_id).order_by(ReportVersion.version_number.desc()).all()
    return render_template("advanced/versions.html", report=report, versions=versions)


@advanced_bp.route("/versions/<int:report_id>/save", methods=["POST"])
@login_required
def save_version(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    last_version = ReportVersion.query.filter_by(report_id=report_id).order_by(ReportVersion.version_number.desc()).first()
    next_num = (last_version.version_number + 1) if last_version else 1
    version = ReportVersion(report_id=report_id, version_number=next_num,
                            synthesis_snapshot=report.synthesis_result, html_snapshot=report.full_report_html)
    db.session.add(version)
    db.session.commit()
    flash(f"Version {next_num} saved.", "success")
    return redirect(url_for("advanced.versions", report_id=report_id))


@advanced_bp.route("/monitor/<int:report_id>", methods=["GET", "POST"])
@login_required
def competitor_monitor(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    if request.method == "POST":
        url = request.form.get("url", "").strip()
        if url:
            monitor = CompetitorMonitor(user_id=current_user.id, report_id=report_id, competitor_url=url)
            db.session.add(monitor)
            db.session.commit()
            flash("Competitor monitor added.", "success")
    monitors = CompetitorMonitor.query.filter_by(report_id=report_id, user_id=current_user.id).all()
    return render_template("advanced/monitor.html", report=report, monitors=monitors)


@advanced_bp.route("/monitor/delete/<int:mid>", methods=["POST"])
@login_required
def delete_monitor(mid):
    monitor = CompetitorMonitor.query.get_or_404(mid)
    if monitor.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    report_id = monitor.report_id
    db.session.delete(monitor)
    db.session.commit()
    flash("Monitor removed.", "success")
    return redirect(url_for("advanced.competitor_monitor", report_id=report_id))


@advanced_bp.route("/meeting/<int:report_id>")
@login_required
def meeting_scheduler(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    from app.models.features import InvestorContact
    contacts = InvestorContact.query.filter_by(user_id=current_user.id, report_id=report_id).all()
    return render_template("advanced/meeting.html", report=report, contacts=contacts)


@advanced_bp.route("/api/digest", methods=["POST"])
@csrf.exempt
@login_required
def generate_digest():
    try:
        from app.ai.diamond import call_ai, run_sync
        reports = Report.query.filter_by(user_id=current_user.id).order_by(Report.created_at.desc()).limit(5).all()
        reports_summary = "\n".join([f"- {r.project_name}: verdict={r.verdict}, score={r.viability_score}" for r in reports])
        monitors = CompetitorMonitor.query.filter_by(user_id=current_user.id, is_active=True).all()
        monitors_summary = "\n".join([f"- Monitoring: {m.competitor_url} (changes: {m.changes_detected})" for m in monitors])
        prompt = f"""Generate a weekly AI digest email for this entrepreneur:
Recent reports: {reports_summary}
Competitor monitors: {monitors_summary}

Include: 1) Summary of their projects 2) Market trends relevant to their sectors 3) Action items for next week 4) One motivational insight
Language: {"Arabic" if (current_user.language_pref or "ar") == "ar" else "English"}"""
        messages = [{"role": "system", "content": "Generate a professional weekly digest email."}, {"role": "user", "content": prompt}]
        result = run_sync(call_ai(messages, model_type="fast"))
        return jsonify({"digest": result})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@advanced_bp.route("/auto-update/<int:report_id>", methods=["POST"])
@csrf.exempt
@login_required
def auto_update(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Access denied"}), 403
    try:
        from app.models.features import ReportVersion
        last_version = ReportVersion.query.filter_by(report_id=report_id).order_by(ReportVersion.version_number.desc()).first()
        next_num = (last_version.version_number + 1) if last_version else 1
        version = ReportVersion(report_id=report_id, version_number=next_num,
                                synthesis_snapshot=report.synthesis_result, html_snapshot=report.full_report_html)
        db.session.add(version)

        from app.ai.diamond import call_ai, run_sync
        prompt = f"""This is a feasibility study for "{report.project_name}" generated previously:
{report.synthesis_result}

Update this analysis with the latest 2024-2025 market data, trends, and competitive landscape changes.
Keep the same JSON structure. Only update numbers, statistics, and market insights that may have changed.
Language: {"Arabic" if report.language == "ar" else "English"}"""
        messages = [{"role": "system", "content": "Return updated JSON maintaining the exact same structure."}, {"role": "user", "content": prompt}]
        result = run_sync(call_ai(messages, model_type="deep"))
        report.synthesis_result = result
        db.session.commit()

        from app.routes.notifications import notify
        notify(current_user.id, f"تقرير '{report.project_name}' تم تحديثه تلقائياً",
               category="update", link=url_for("study.view", report_id=report_id))

        return jsonify({"status": "updated", "version": next_num})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


CURRENCIES = {
    "SAR": {"name": "ريال سعودي", "symbol": "ر.س", "rate_to_usd": 0.2667},
    "AED": {"name": "درهم إماراتي", "symbol": "د.إ", "rate_to_usd": 0.2723},
    "USD": {"name": "دولار أمريكي", "symbol": "$", "rate_to_usd": 1.0},
    "EUR": {"name": "يورو", "symbol": "€", "rate_to_usd": 1.08},
    "GBP": {"name": "جنيه استرليني", "symbol": "£", "rate_to_usd": 1.27},
    "EGP": {"name": "جنيه مصري", "symbol": "ج.م", "rate_to_usd": 0.0205},
    "KWD": {"name": "دينار كويتي", "symbol": "د.ك", "rate_to_usd": 3.25},
}


@advanced_bp.route("/charts/<int:report_id>")
@login_required
def financial_charts(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    chart_data = {}
    if report.synthesis_result:
        import json
        try:
            synthesis = json.loads(report.synthesis_result) if isinstance(report.synthesis_result, str) else report.synthesis_result
            financial = synthesis.get("financial_analysis") or synthesis.get("financial") or {}
            chart_data = {
                "revenue": financial.get("revenue_projection") or financial.get("revenue") or [],
                "costs": financial.get("cost_projection") or financial.get("costs") or [],
                "cashflow": financial.get("cash_flow") or financial.get("cashflow") or [],
                "profit": financial.get("profit_projection") or financial.get("profit") or [],
                "roi": financial.get("roi") or 0,
                "npv": financial.get("npv") or 0,
                "irr": financial.get("irr") or 0,
                "payback": financial.get("payback_period") or 0,
            }
        except Exception:
            pass
    return render_template("advanced/charts.html", report=report, chart_data=chart_data)


@advanced_bp.route("/currency/<int:report_id>")
@login_required
def currency_converter(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    target = request.args.get("to", "USD")
    source = request.args.get("from", "SAR")
    return render_template("advanced/currency.html", report=report, currencies=CURRENCIES,
                           source=source, target=target)


@advanced_bp.route("/api/convert", methods=["POST"])
@csrf.exempt
@login_required
def convert_currency():
    data = request.get_json(silent=True) or {}
    amount = data.get("amount", 0)
    source = data.get("from", "SAR")
    target = data.get("to", "USD")
    if source in CURRENCIES and target in CURRENCIES:
        usd = float(amount) * CURRENCIES[source]["rate_to_usd"]
        result = usd / CURRENCIES[target]["rate_to_usd"]
        return jsonify({"result": round(result, 2), "from": source, "to": target})
    return jsonify({"error": "Invalid currency"}), 400


@advanced_bp.route("/branded-pdf/<int:report_id>")
@login_required
def branded_pdf(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    return render_template("advanced/branded_pdf.html", report=report)


@advanced_bp.route("/custom-sections/<int:report_id>", methods=["GET", "POST"])
@login_required
def custom_sections(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))
    available_sections = [
        ("executive_summary", "Executive Summary / الملخص التنفيذي"),
        ("swot", "SWOT Analysis"), ("pestel", "PESTEL Analysis"),
        ("porters", "Porter's Five Forces"), ("bmc", "Business Model Canvas"),
        ("lean_canvas", "Lean Canvas"), ("tam_sam_som", "TAM/SAM/SOM Market Sizing"),
        ("gtm", "Go-to-Market Strategy"), ("financial", "Financial Analysis"),
        ("competitors", "Competitor Analysis"), ("vrio", "VRIO Analysis"),
        ("legal", "Legal & Regulatory"), ("risk", "Risk Assessment"),
        ("marketing", "Marketing Strategy"), ("mvp", "MVP Path & Roadmap"),
        ("team", "Team & Hiring Plan"),
    ]
    if request.method == "POST":
        selected = request.form.getlist("sections")
        import json
        report.custom_sections = json.dumps(selected)
        db.session.commit()
        flash("Sections saved. Regenerate to apply.", "success")
        return redirect(url_for("study.view", report_id=report_id))
    current_sections = []
    if hasattr(report, 'custom_sections') and report.custom_sections:
        import json
        try:
            current_sections = json.loads(report.custom_sections)
        except Exception:
            pass
    return render_template("advanced/custom_sections.html", report=report,
                           sections=available_sections, current_sections=current_sections)


@advanced_bp.route("/investor-portfolio")
@login_required
def investor_portfolio():
    from app.models.features import InvestorContact
    contacts = InvestorContact.query.filter_by(user_id=current_user.id).all()
    portfolio = {}
    for c in contacts:
        if c.name not in portfolio:
            portfolio[c.name] = {"contact": c, "reports": []}
        if c.report_id:
            r = Report.query.get(c.report_id)
            if r:
                portfolio[c.name]["reports"].append(r)
    return render_template("advanced/investor_portfolio.html", portfolio=portfolio)
