import json
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.ai.diamond import call_ai, run_sync
from app.models.report import Report

tools_bp = Blueprint("tools", __name__, url_prefix="/tools")


# --- Automated Pitch Email ---
@tools_bp.route("/pitch-email/<int:report_id>")
@login_required
def pitch_email(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return redirect(url_for("dashboard.index"))
    return render_template("tools/pitch_email.html", report=report)


@tools_bp.route("/api/generate-pitch-email", methods=["POST"])
@csrf.exempt
@login_required
def api_pitch_email():
    data = request.get_json() or {}
    report_id = data.get("report_id")
    investor_type = data.get("investor_type", "VC")
    tone = data.get("tone", "professional")

    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    synthesis = report.synthesis_result or {}
    prompt = f"""Generate a professional investor pitch email for the following project.

Project: {report.project_name}
Description: {report.project_description}
Investor Type: {investor_type}
Tone: {tone}
Executive Summary: {synthesis.get('executive_summary', '')}
Verdict: {synthesis.get('verdict', '')}
Viability Score: {json.dumps(synthesis.get('viability_score', {}))}
Financial: {json.dumps(synthesis.get('financial_highlights', {}))}

Write in {'Arabic' if report.language == 'ar' else 'English'}.
Include: Subject line, greeting, problem statement, solution, traction/metrics, ask/CTA, signature template.
Return as JSON: {{subject: string, body: string, cta: string}}"""

    try:
        messages = [{"role": "user", "content": prompt}]
        result = run_sync(call_ai(messages, model_type="fast"))
        from app.ai.diamond import _parse_json
        parsed = _parse_json(result)
        return jsonify(parsed if isinstance(parsed, dict) else {"body": result})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# --- Financial Scenario Simulator ---
@tools_bp.route("/scenario/<int:report_id>")
@login_required
def scenario(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return redirect(url_for("dashboard.index"))
    synthesis = report.synthesis_result or {}
    fh = synthesis.get("financial_highlights", {})
    return render_template("tools/scenario.html", report=report, fh=fh)


@tools_bp.route("/api/simulate-scenario", methods=["POST"])
@csrf.exempt
@login_required
def api_simulate():
    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

    changes = data.get("changes", {})
    synthesis = report.synthesis_result or {}
    fh = synthesis.get("financial_highlights", {})

    prompt = f"""You are a financial analyst. Given the original financial projections and the user's "What-If" changes,
recalculate and provide updated financial projections.

Original Financial Highlights: {json.dumps(fh)}

User's What-If Changes: {json.dumps(changes)}

Return JSON with:
- updated_financials: same structure as financial_highlights with new values
- impact_summary: string describing the key impacts
- risk_change: "increased", "decreased", or "neutral"
- new_break_even: string
- recommendations: [string]"""

    try:
        messages = [{"role": "user", "content": prompt}]
        result = run_sync(call_ai(messages, model_type="fast"))
        from app.ai.diamond import _parse_json
        parsed = _parse_json(result)
        return jsonify(parsed if isinstance(parsed, dict) else {"impact_summary": result})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# --- AI Brand Kit Generator ---
@tools_bp.route("/brand-kit/<int:report_id>")
@login_required
def brand_kit(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return redirect(url_for("dashboard.index"))
    return render_template("tools/brand_kit.html", report=report)


@tools_bp.route("/api/generate-brand-kit", methods=["POST"])
@csrf.exempt
@login_required
def api_brand_kit():
    data = request.get_json() or {}
    report_id = data.get("report_id")
    style = data.get("style", "modern")

    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    synthesis = report.synthesis_result or {}

    user_lang = "Arabic" if (current_user.language_pref or "ar") == "ar" else "English"
    prompt = f"""Generate a complete brand kit for this business.
Respond entirely in {user_lang}.

Business: {report.project_name}
Description: {report.project_description}
Industry: {synthesis.get('industry_benchmarks', {}).get('industry', 'General')}
Style: {style}
USP: {synthesis.get('usp', '')}

Return JSON with:
- brand_names: [5 creative brand name suggestions with Arabic and English versions]
- taglines: [3 tagline options]
- color_palette: [{{name: string, hex: string, usage: string}}] (5 colors: primary, secondary, accent, bg, text)
- typography: {{heading_font: string, body_font: string, accent_font: string}}
- brand_voice: string (description of tone and voice)
- logo_description: string (detailed description for a designer)
- brand_values: [3-5 core values]
- social_media_handles: [suggested handle variations]"""

    try:
        messages = [{"role": "user", "content": prompt}]
        result = run_sync(call_ai(messages, model_type="deep"))
        from app.ai.diamond import _parse_json
        parsed = _parse_json(result)
        return jsonify(parsed if isinstance(parsed, dict) else {"brand_names": [], "error": result})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@tools_bp.route("/api/generate-logos", methods=["POST"])
@csrf.exempt
@login_required
def api_generate_logos():
    data = request.get_json() or {}
    report_id = data.get("report_id")
    style = data.get("style", "modern")
    brand_name = data.get("brand_name", "")
    color_hint = data.get("color_hint", "")

    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    synthesis = report.synthesis_result or {}
    industry = synthesis.get("industry_benchmarks", {}).get("industry", "General")

    style_map = {
        "modern": "clean modern minimalist",
        "luxury": "luxury elegant premium gold",
        "playful": "playful colorful creative fun",
        "corporate": "professional corporate formal",
        "minimal": "ultra minimal simple geometric",
    }
    style_desc = style_map.get(style, "modern minimalist")

    name = brand_name or report.project_name
    color_part = f", using colors: {color_hint}" if color_hint else ""

    logo_styles = [
        f"A {style_desc} logo icon for '{name}', a {industry} brand. Simple vector-style icon on white background{color_part}. No text.",
        f"A {style_desc} wordmark logo for '{name}', a {industry} brand. Clean typography-based logo on white background{color_part}.",
        f"A {style_desc} emblem/badge logo for '{name}', a {industry} brand. Circular or shield emblem on white background{color_part}. No text.",
        f"A {style_desc} abstract symbol logo for '{name}', a {industry} brand. Creative abstract mark on white background{color_part}. No text.",
    ]

    try:
        from openai import OpenAI
        client = OpenAI(api_key=current_app.config["OPENAI_API_KEY"])

        logos = []
        for i, prompt in enumerate(logo_styles):
            try:
                resp = client.images.generate(
                    model="dall-e-3",
                    prompt=prompt,
                    size="1024x1024",
                    quality="standard",
                    n=1,
                )
                style_labels_ar = ["أيقونة", "نص", "شعار دائري", "رمز مجرد"]
                style_labels_en = ["Icon", "Wordmark", "Emblem", "Abstract"]
                style_labels = style_labels_ar if (current_user.language_pref or "ar") == "ar" else style_labels_en
                logos.append({
                    "url": resp.data[0].url,
                    "style": style_labels[i],
                    "revised_prompt": resp.data[0].revised_prompt or "",
                })
            except Exception as e:
                current_app.logger.error(f"Logo {i+1} generation failed: {e}")
                style_labels_ar = ["أيقونة", "نص", "شعار دائري", "رمز مجرد"]
                style_labels_en = ["Icon", "Wordmark", "Emblem", "Abstract"]
                style_labels = style_labels_ar if (current_user.language_pref or "ar") == "ar" else style_labels_en
                logos.append({"url": None, "style": style_labels[i], "error": str(e)})

        return jsonify({"status": "done", "logos": logos})
    except Exception as e:
        current_app.logger.error(f"Logo generation failed: {e}")
        return jsonify({"error": str(e)}), 500


# --- Investor Matching ---
@tools_bp.route("/investor-match/<int:report_id>")
@login_required
def investor_match(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return redirect(url_for("dashboard.index"))
    return render_template("tools/investor_match.html", report=report)


@tools_bp.route("/api/match-investors", methods=["POST"])
@csrf.exempt
@login_required
def api_match_investors():
    data = request.get_json() or {}
    report_id = data.get("report_id")
    stage = data.get("stage", "seed")
    region = data.get("region", "MENA")

    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    synthesis = report.synthesis_result or {}

    prompt = f"""Based on this business profile, suggest matching investors and funding sources.

Business: {report.project_name}
Description: {report.project_description}
Stage: {stage}
Region: {region}
Industry: {synthesis.get('industry_benchmarks', {}).get('industry', '')}
Funding Needed: {synthesis.get('financial_highlights', {}).get('estimated_startup_cost', '')}

Return JSON with:
- investors: [{{name: string, type: string, focus: string, typical_check: string, website: string, fit_score: number 0-100, reason: string}}]
  Include real VCs, angel networks, government funds, and accelerators relevant to {region}.
  For MENA include: STV, Wa'ed, Shorooq, 500 Global MENA, Flat6Labs, SVC, Sanabil, Raed Ventures, etc.
- grants: [{{name: string, provider: string, amount: string, eligibility: string}}]
- crowdfunding: [{{platform: string, type: string, url: string}}]
- tips: [string]"""

    try:
        messages = [{"role": "user", "content": prompt}]
        result = run_sync(call_ai(messages, model_type="deep"))
        from app.ai.diamond import _parse_json
        parsed = _parse_json(result)
        return jsonify(parsed if isinstance(parsed, dict) else {"investors": [], "error": result})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# --- Progress Tracker ---
@tools_bp.route("/progress/<int:report_id>")
@login_required
def progress(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return redirect(url_for("dashboard.index"))
    return render_template("tools/progress.html", report=report)


@tools_bp.route("/api/generate-roadmap", methods=["POST"])
@csrf.exempt
@login_required
def api_roadmap():
    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

    synthesis = report.synthesis_result or {}
    mvp = synthesis.get("mvp_definition", {})

    prompt = f"""Create a detailed implementation roadmap for this business:

Business: {report.project_name}
Description: {report.project_description}
MVP: {json.dumps(mvp)}
Startup Cost: {synthesis.get('financial_highlights', {}).get('estimated_startup_cost', '')}

Return JSON with:
- phases: [{{
    name: string,
    duration: string,
    tasks: [{{task: string, category: string, priority: "high"|"medium"|"low"}}],
    milestone: string,
    budget_allocation: string
  }}]
  Include 4-6 phases from "Pre-Launch" to "Scale".
- critical_path: [string] (key dependencies)
- quick_wins: [string] (things to do in first week)"""

    try:
        messages = [{"role": "user", "content": prompt}]
        result = run_sync(call_ai(messages, model_type="deep"))
        from app.ai.diamond import _parse_json
        parsed = _parse_json(result)
        return jsonify(parsed if isinstance(parsed, dict) else {"phases": [], "error": result})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# ── Supply Chain Mapper ──────────────────────────────────────────────

@tools_bp.route("/api/supply-chain-map", methods=["POST"])
@login_required
@csrf.exempt
def api_supply_chain_map():
    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

    synthesis = report.synthesis_result or {}
    prompt = f"""أنت خبير سلاسل إمداد. بناءً على بيانات المشروع التالية، أنشئ خريطة سلسلة إمداد تفصيلية.

اسم المشروع: {report.project_name}
الوصف: {report.project_description}
الملخص التنفيذي: {synthesis.get('executive_summary', '')[:500]}
تعريف MVP: {json.dumps(synthesis.get('mvp_definition', {}), ensure_ascii=False)[:400]}

أرجع JSON:
{{
  "raw_materials": [
    {{"name": "المادة الخام", "source_countries": ["الدولة"], "estimated_cost": "التكلفة", "lead_time": "المدة", "suppliers_count": 3}}
  ],
  "manufacturing_steps": [
    {{"step": "الخطوة", "description": "الوصف", "location_suggestion": "الموقع المقترح", "duration": "المدة", "cost_percentage": 20}}
  ],
  "logistics": {{
    "shipping_method": "طريقة الشحن",
    "estimated_shipping_cost": "تكلفة الشحن",
    "customs_considerations": ["اعتبار جمركي 1"],
    "warehousing": "متطلبات التخزين"
  }},
  "distribution_channels": [
    {{"channel": "القناة", "reach": "الوصول", "cost": "التكلفة", "timeline": "الجدول"}}
  ],
  "risks": [
    {{"risk": "المخاطرة", "probability": "عالية/متوسطة/منخفضة", "impact": "التأثير", "mitigation": "التخفيف"}}
  ],
  "optimization_tips": ["نصيحة 1", "نصيحة 2"],
  "total_supply_chain_cost": "التكلفة الإجمالية التقديرية",
  "recommended_strategy": "الاستراتيجية الموصى بها"
}}"""

    try:
        messages = [
            {"role": "system", "content": "أنت خبير سلاسل إمداد. أرجع JSON فقط."},
            {"role": "user", "content": prompt},
        ]
        result = run_sync(call_ai(messages, model_type="deep"))
        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 json.JSONDecodeError:
        return jsonify({"error": "AI returned invalid format", "raw": result}), 500
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# ── Product Cost Calculator ──────────────────────────────────────────

@tools_bp.route("/api/product-cost-calculator", methods=["POST"])
@login_required
@csrf.exempt
def api_product_cost_calculator():
    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

    quantity = data.get("quantity", 1000)
    target_margin = data.get("target_margin", 30)
    synthesis = report.synthesis_result or {}

    prompt = f"""أنت محاسب تكاليف متخصص. احسب تكلفة المنتج التفصيلية بناءً على:

اسم المشروع: {report.project_name}
الوصف: {report.project_description}
الكمية المستهدفة: {quantity} وحدة
هامش الربح المستهدف: {target_margin}%
الملخص: {synthesis.get('executive_summary', '')[:400]}

أرجع JSON:
{{
  "direct_costs": {{
    "raw_materials": {{"cost_per_unit": 0, "total": 0, "details": []}},
    "labor": {{"cost_per_unit": 0, "total": 0, "hours_per_unit": 0}},
    "packaging": {{"cost_per_unit": 0, "total": 0}}
  }},
  "indirect_costs": {{
    "overhead": {{"cost_per_unit": 0, "total": 0}},
    "utilities": {{"cost_per_unit": 0, "total": 0}},
    "depreciation": {{"cost_per_unit": 0, "total": 0}},
    "quality_control": {{"cost_per_unit": 0, "total": 0}}
  }},
  "distribution_costs": {{
    "shipping": {{"cost_per_unit": 0, "total": 0}},
    "marketing": {{"cost_per_unit": 0, "total": 0}},
    "sales_commission": {{"cost_per_unit": 0, "total": 0}}
  }},
  "summary": {{
    "total_cost_per_unit": 0,
    "total_production_cost": 0,
    "suggested_selling_price": 0,
    "gross_margin_percentage": 0,
    "break_even_units": 0,
    "currency": "SAR"
  }},
  "scaling_analysis": {{
    "economies_of_scale": [
      {{"quantity": 100, "unit_cost": 0}},
      {{"quantity": 1000, "unit_cost": 0}},
      {{"quantity": 10000, "unit_cost": 0}}
    ]
  }},
  "cost_reduction_opportunities": ["فرصة 1", "فرصة 2"]
}}

استخدم أرقام واقعية بالريال السعودي."""

    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 json.JSONDecodeError:
        return jsonify({"error": "AI returned invalid format"}), 500
    except Exception as e:
        return jsonify({"error": str(e)}), 500
