"""
Contexte Django pour le template HTML du Business Plan (templates/bp/index.html).
Remplit les variables avec les données du modèle BP + données financières calculées.
"""
from datetime import datetime
from decimal import Decimal


def _txt(val):
    return (val or "").strip() or "—"


def _num(x):
    if x is None:
        return "0"
    try:
        return f"{float(x):,.0f}".replace(",", " ")
    except (TypeError, ValueError):
        return "0"


def _date_fr(d):
    if not d:
        return "—"
    if hasattr(d, "strftime"):
        return d.strftime("%d/%m/%Y")
    return str(d)[:10]


def _month_year(month, year):
    if not month or not year:
        return "—"
    mois = ("", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin",
            "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre")
    m = int(month) if month else 0
    if 1 <= m <= 12:
        return f"{mois[m]} {year}"
    return str(year)


def get_bp_template_context(bp, financial_data=None):
    """
    Construit le contexte pour templates/bp/index.html.
    financial_data peut être None (sections financières vides) ou le dict
    retourné par FinancialEngine (global_costs, loan_schedule, amortization, pnl_normal).
    """
    user = getattr(bp, "entrepreneur", None)
    promoter_name = _txt(getattr(bp, "promoter_name", None))
    if not promoter_name and user:
        promoter_name = f"{getattr(user, 'first_name', '') or ''} {getattr(user, 'last_name', '') or ''}".strip()
    if not promoter_name and user:
        promoter_name = getattr(user, "email", "—")

    elaboration_str = _month_year(
        getattr(bp, "elaboration_month", None),
        getattr(bp, "elaboration_year", None),
    )
    if elaboration_str == "—":
        elaboration_str = datetime.now().strftime("%B %Y")

    marketing_activities = []
    for m in getattr(bp, "marketing_activities", []).all():
        marketing_activities.append({
            "activity_name": _txt(getattr(m, "activity_name", None)),
            "description": _txt(getattr(m, "description", None)),
        })
    if not marketing_activities:
        marketing_activities = [{"activity_name": "—", "description": "—"}]

    investments_incorporel = []
    investments_corporel = []
    sum_incorporel = Decimal("0")
    sum_corporel = Decimal("0")
    inv_qs = getattr(bp, "investments", None)
    inv_list = list(inv_qs.all()) if inv_qs and hasattr(inv_qs, "all") else []
    for inv in inv_list:
        total_cost = getattr(inv, "total_cost", None) or Decimal("0")
        try:
            total_cost = Decimal(str(total_cost))
        except Exception:
            total_cost = Decimal("0")
        row = {
            "name": _txt(getattr(inv, "name", None)),
            "quantity": getattr(inv, "quantity", 1),
            "unit_price": _num(getattr(inv, "unit_price", 0)),
            "total": _num(total_cost),
            "description": _txt(getattr(inv, "description", None)),
            "duration_years": getattr(inv, "duration_years", 0),
        }
        if getattr(inv, "invest_type", "") == "INCORPOREL":
            investments_incorporel.append(row)
            sum_incorporel += total_cost
        else:
            investments_corporel.append(row)
            sum_corporel += total_cost

    human_resources = []
    for hr in getattr(bp, "human_resources", []).all():
        human_resources.append({
            "position": _txt(getattr(hr, "position", None)),
            "count": getattr(hr, "count", 1),
            "description": _txt(getattr(hr, "description", None)),
        })

    context = {
        "project_title": _txt(getattr(bp, "project_title", None)) or _txt(getattr(bp, "company_name", None)),
        "company_name": _txt(getattr(bp, "company_name", None)),
        "elaboration_date": elaboration_str,
        "promoter_name": promoter_name,
        "legal_status": _txt(getattr(bp, "legal_status", None)),
        "creation_date": _date_fr(getattr(bp, "creation_date", None)),
        "rc_number": _txt(getattr(bp, "rc_number", None)),
        "ninea": _txt(getattr(bp, "ninea", None)),
        "address": _txt(getattr(bp, "address", None)),
        "contact_name": _txt(getattr(bp, "contact_name", None)),
        "contact_phone": _txt(getattr(bp, "contact_phone", None)),
        "contact_email": _txt(getattr(bp, "contact_email", None)),
        "capacity_reasons": _txt(getattr(bp, "capacity_reasons", None)),
        "experience_text": _txt(getattr(bp, "experience_text", None)),
        "training_text": _txt(getattr(bp, "training_text", None)),
        "skills_text": _txt(getattr(bp, "skills_text", None)),
        "project_object": _txt(getattr(bp, "project_object", None)),
        "project_objectives": _txt(getattr(bp, "project_objectives", None)),
        "location_reason": _txt(getattr(bp, "location_reason", None)),
        "product_description": _txt(getattr(bp, "product_description", None)),
        "competition_analysis": _txt(getattr(bp, "competition_analysis", None)),
        "customer_analysis": _txt(getattr(bp, "customer_analysis", None)),
        "marketing_strategy_note": _txt(getattr(bp, "marketing_strategy", None)),
        "marketing_activities": marketing_activities,
        "process_description": _txt(getattr(bp, "process_description", None)),
        "investments_incorporel": investments_incorporel or [{"name": "—", "total": "0", "description": "—"}],
        "investments_corporel": investments_corporel or [{"name": "—", "quantity": 0, "unit_price": "0", "total": "0", "description": "—"}],
        "human_resources": human_resources or [{"position": "—", "count": 0, "description": "—"}],
    }
    startup_costs_labor = []
    startup_costs_material = []
    startup_costs_fixed = []
    startup_costs_qs = getattr(bp, "startup_costs", None)
    startup_list = list(startup_costs_qs.all()) if startup_costs_qs and hasattr(startup_costs_qs, "all") else []
    for c in startup_list:
        row = {
            "designation": _txt(getattr(c, "designation", None)),
            "monthly_amount": _num(getattr(c, "monthly_amount", 0)),
            "months_needed": getattr(c, "months_needed", 0),
            "total": _num(getattr(c, "total_bfr", 0)),
        }
        cat = getattr(c, "category", "")
        if cat == "LABOR":
            startup_costs_labor.append(row)
        elif cat == "MATERIAL":
            startup_costs_material.append(row)
        else:
            startup_costs_fixed.append(row)
    context["startup_costs_labor"] = startup_costs_labor
    context["startup_costs_material"] = startup_costs_material
    context["startup_costs_fixed"] = startup_costs_fixed

    if financial_data:
        gc = financial_data.get("global_costs") or {}
        loan_schedule = financial_data.get("loan_schedule") or []
        amort = financial_data.get("amortization") or {}
        pnl = financial_data.get("pnl_normal") or {}

        context["total_incorporel"] = _num(gc.get("incorporel"))
        context["total_corporel"] = _num(gc.get("corporel"))
        context["total_bfr"] = _num(gc.get("bfr"))
        context["total_project_cost"] = _num(gc.get("total_project"))
        context["personal_contribution"] = _num(getattr(bp, "personal_contribution", 0))
        context["other_funding"] = _num(getattr(bp, "other_funding", 0))
        context["loan_amount"] = _num(gc.get("loan_amount"))
        context["loan_interest_rate"] = _num(getattr(bp, "loan_interest_rate", 0))
        context["loan_duration_months"] = getattr(bp, "loan_duration_months", 0)
        context["loan_deferral_months"] = getattr(bp, "loan_deferral_months", 0)

        context["amortization_rows"] = []
        for row in loan_schedule:
            context["amortization_rows"].append({
                "year": row.get("year", "—"),
                "capital_start": _num(row.get("capital_start")),
                "interest": _num(row.get("interest")),
                "amortization": _num(row.get("amortization")),
                "annuity": _num(row.get("annuity")),
            })

        context["pnl_rows"] = []
        pnl_list = pnl if isinstance(pnl, list) else pnl.get("years", []) if isinstance(pnl, dict) else []
        for year_data in pnl_list:
            y = year_data.get("year", "—")
            if isinstance(y, int):
                y = f"Année {y}"
            context["pnl_rows"].append({
                "year": y,
                "revenues": _num(year_data.get("revenues")),
                "expenses": _num(year_data.get("expenses")),
                "rbe": _num(year_data.get("rbe")),
                "amortization": _num(year_data.get("amortization")),
                "interest": _num(year_data.get("interest")),
                "rai": _num(year_data.get("rai")),
                "impot": _num(year_data.get("impot")),
                "net_result": _num(year_data.get("net_result")),
                "cash_flow": _num(year_data.get("cash_flow")),
            })

        context["has_financial_data"] = True
    else:
        context["has_financial_data"] = False
        context["total_incorporel"] = _num(sum_incorporel)
        context["total_corporel"] = _num(sum_corporel)
        context["total_bfr"] = "0"
        context["total_project_cost"] = context["personal_contribution"] = context["other_funding"] = context["loan_amount"] = "0"
        context["loan_interest_rate"] = context["loan_duration_months"] = context["loan_deferral_months"] = "—"
        context["amortization_rows"] = []
        context["pnl_rows"] = []

    return context
