from __future__ import annotations

from datetime import date

from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Sum
from django.utils import timezone

from apps.core.services import audit, format_number, next_sequence
from apps.sync.services import emit

from .models import (Activity, Budget, BudgetLine, Expense, FinancialEvent,
                     FiscalYear, Payment, Revenue, Threshold)


# Définitions uniques, partagées avec le reporting.
ENGAGED_STATUSES = ("APPROVED", "PARTIALLY_PAID", "PAID")
EXECUTED_STATUSES = ("PARTIALLY_PAID", "PAID")


def current_fiscal_year(agency):
    today = timezone.localdate()
    year = FiscalYear.objects.filter(agency=agency, start_date__lte=today, end_date__gte=today).first()
    if year:
        return year
    return FiscalYear.objects.filter(agency=agency).order_by("-year").first()


def ensure_open(year: FiscalYear):
    if year.status != "OPEN":
        raise ValidationError("L'exercice budgétaire est clôturé : aucune opération n'est possible.")


@transaction.atomic
def append_financial_event(*, agency, fiscal_year, event_type, entity_type, entity_id,
                           amount_xaf, actor, payload=None) -> FinancialEvent:
    last = (
        FinancialEvent.objects.filter(agency=agency, fiscal_year=fiscal_year)
        .order_by("-ledger_seq").first()
    )
    seq = (last.ledger_seq + 1) if last else 1
    prev_hash = last.hash if last else ""
    event = FinancialEvent(
        agency=agency, fiscal_year=fiscal_year, event_type=event_type,
        entity_type=entity_type, entity_id=entity_id, amount_xaf=amount_xaf,
        actor=actor, payload=payload or {}, ledger_seq=seq, prev_hash=prev_hash,
    )
    event.hash = event.compute_hash(prev_hash)
    event.save()
    emit(entity=event, op_type="APPEND", actor=actor, agency_id=agency.id,
         entity_type="finance.FinancialEvent", entity_id=event.id,
         payload={"op_id": str(event.op_id), "event_type": event_type,
                  "amount_xaf": amount_xaf, "ledger_seq": seq, "hash": event.hash})
    return event


@transaction.atomic
def create_budget(*, actor, agency, fiscal_year, notes="") -> Budget:
    ensure_open(fiscal_year)
    version = Budget.objects.filter(agency=agency, fiscal_year=fiscal_year).count() + 1
    code = format_number(agency.code, f"BUD{str(fiscal_year.year)[-2:]}", version, width=3)
    budget = Budget.objects.create(
        code=code, agency=agency, fiscal_year=fiscal_year, version_number=version,
        status=Budget.Status.DRAFT, notes=notes, created_by=actor, updated_by=actor,
    )
    audit(action="BUDGET_CREATED", actor=actor, entity=budget, agency_id=agency.id)
    emit(entity=budget, op_type="CREATE", actor=actor, agency_id=agency.id)
    return budget


@transaction.atomic
def add_budget_line(*, actor, budget: Budget, data: dict) -> BudgetLine:
    if budget.status not in {Budget.Status.DRAFT, Budget.Status.REVISED}:
        raise ValidationError("Seul un budget en brouillon peut être modifié.")
    line = BudgetLine.objects.create(
        budget=budget, category=data["category"], activity=data.get("activity"),
        funding_source=data.get("funding_source"),
        planned_xaf=data.get("planned_xaf") or 0, approved_xaf=data.get("approved_xaf") or 0,
        notes=data.get("notes", ""),
    )
    budget.recompute_total()
    budget.save(update_fields=["total_xaf", "updated_at"])
    audit(action="BUDGET_LINE_ADDED", actor=actor, entity=budget, agency_id=budget.agency_id,
          after={"category": line.category.name_fr, "approved": line.approved_xaf})
    return line


@transaction.atomic
def submit_budget(*, actor, budget: Budget):
    from apps.approvals.services import open_request
    if budget.status != Budget.Status.DRAFT:
        raise ValidationError("Ce budget n'est pas en brouillon.")
    budget.status = Budget.Status.PENDING
    budget.version += 1
    budget.save(update_fields=["status", "version", "updated_at"])
    open_request(entity_type="finance.Budget", entity_id=budget.id, agency=budget.agency,
                 actor=actor, comment=f"Budget {budget.code}")
    audit(action="BUDGET_SUBMITTED", actor=actor, entity=budget, agency_id=budget.agency_id)


@transaction.atomic
def create_expense(*, actor, agency, data: dict, request=None) -> Expense:
    fiscal_year = data["fiscal_year"]
    ensure_open(fiscal_year)
    # Verrou sur la ligne : deux dépenses simultanées ne peuvent pas dépasser le disponible.
    line: BudgetLine = BudgetLine.objects.select_for_update().select_related("budget").get(pk=data["budget_line"].pk)
    if line.budget.agency_id != agency.id:
        raise ValidationError("La ligne budgétaire appartient à une autre agence.")
    if line.budget.fiscal_year_id != fiscal_year.id:
        raise ValidationError("La ligne budgétaire appartient à un autre exercice.")
    if data["category"].id != line.category_id:
        raise ValidationError("La catégorie ne correspond pas à la ligne budgétaire.")
    categories = line.totals()
    if data["amount_xaf"] > categories["available"] and not data.get("override"):
        raise ValidationError(
            f"Dépassement de ligne budgétaire : disponible {categories['available']} XAF."
        )
    seq = next_sequence(agency.id, "expense", year=fiscal_year.year)
    code = format_number(agency.code, f"DEP{str(fiscal_year.year)[-2:]}", seq, width=5)
    expense = Expense.objects.create(
        code=code, agency=agency, fiscal_year=fiscal_year, budget_line=line,
        category=data["category"], activity=data.get("activity"),
        label=data["label"], amount_xaf=data["amount_xaf"],
        supplier_name=data.get("supplier_name", ""), invoice_ref=data.get("invoice_ref", ""),
        incurred_on=data.get("incurred_on") or timezone.localdate(),
        status=Expense.Status.DRAFT, requested_by=actor, created_by=actor, updated_by=actor,
        document=data.get("document"),
    )
    audit(action="EXPENSE_CREATED", actor=actor, entity=expense, agency_id=agency.id,
          after={"code": code, "amount": expense.amount_xaf}, request=request)
    emit(entity=expense, op_type="CREATE", actor=actor, agency_id=agency.id)
    return expense


@transaction.atomic
def submit_expense(*, actor, expense: Expense, request=None):
    from apps.approvals.services import open_request
    if expense.status != Expense.Status.DRAFT:
        raise ValidationError("Seule une dépense en brouillon peut être soumise.")
    expense.status = Expense.Status.PENDING
    expense.version += 1
    expense.save(update_fields=["status", "version", "updated_at"])
    open_request(entity_type="finance.Expense", entity_id=expense.id, agency=expense.agency,
                 actor=actor, amount_xaf=expense.amount_xaf, comment=expense.label)
    audit(action="EXPENSE_SUBMITTED", actor=actor, entity=expense, agency_id=expense.agency_id, request=request)
    emit(entity=expense, op_type="STATE", actor=actor, agency_id=expense.agency_id)


def apply_validation_status(entity_type: str, entity_id, status: str, actor=None) -> None:
    """Appelé par le réducteur de validation (approvals)."""
    if entity_type == "finance.Expense":
        expense = Expense.objects.filter(pk=entity_id).first()
        if not expense:
            return
        if status == "APPROVED":
            expense.status = Expense.Status.APPROVED
            expense.approved_at = timezone.now()
            expense.approved_by = actor
            expense.version += 1
            expense.save(update_fields=["status", "approved_at", "approved_by", "version", "updated_at"])
            append_financial_event(agency=expense.agency, fiscal_year=expense.fiscal_year,
                                   event_type="EXPENSE_APPROVED", entity_type="finance.Expense",
                                   entity_id=expense.id, amount_xaf=expense.amount_xaf,
                                   actor=expense.approved_by, payload={"code": expense.code})
            emit(entity=expense, op_type="STATE", actor=None, agency_id=expense.agency_id)
        elif status == "REJECTED":
            expense.status = Expense.Status.REJECTED
            expense.version += 1
            expense.save(update_fields=["status", "version", "updated_at"])
        elif status == "CONFLICT":
            expense.status = Expense.Status.CONFLICT
            expense.version += 1
            expense.save(update_fields=["status", "version", "updated_at"])
        elif status == "CANCELLED":
            expense.status = Expense.Status.DRAFT
            expense.version += 1
            expense.save(update_fields=["status", "version", "updated_at"])
    elif entity_type == "finance.Budget":
        budget = Budget.objects.filter(pk=entity_id).first()
        if not budget:
            return
        if status == "APPROVED":
            budget.status = Budget.Status.APPROVED
            budget.approved_at = timezone.now()
            budget.approved_by = actor
            budget.version += 1
            budget.save(update_fields=["status", "approved_at", "approved_by", "version", "updated_at"])
            for line in budget.lines.all():
                if line.approved_xaf == 0:
                    line.approved_xaf = line.planned_xaf
                    line.save(update_fields=["approved_xaf"])
            budget.recompute_total()
            budget.save(update_fields=["total_xaf", "updated_at"])
            append_financial_event(agency=budget.agency, fiscal_year=budget.fiscal_year,
                                   event_type="BUDGET_APPROVED", entity_type="finance.Budget",
                                   entity_id=budget.id, amount_xaf=budget.total_xaf,
                                   actor=budget.approved_by, payload={"code": budget.code})
        elif status in {"REJECTED", "CONFLICT", "CANCELLED"}:
            # Un budget refusé, en conflit ou retiré redevient modifiable.
            budget.status = Budget.Status.DRAFT
            budget.save(update_fields=["status", "updated_at"])
    elif entity_type == "finance.Revenue":
        revenue = Revenue.objects.filter(pk=entity_id).first()
        if revenue and status == "REJECTED":
            revenue.status = Revenue.Status.REJECTED
            revenue.save(update_fields=["status", "updated_at"])
        elif revenue and status in {"CONFLICT", "CANCELLED"}:
            revenue.status = Revenue.Status.DRAFT
            revenue.save(update_fields=["status", "updated_at"])
        elif revenue and status == "APPROVED":
            revenue.status = Revenue.Status.APPROVED
            revenue.approved_by = actor
            revenue.save(update_fields=["status", "approved_by", "updated_at"])
            append_financial_event(agency=revenue.agency, fiscal_year=revenue.fiscal_year,
                                   event_type="REVENUE_APPROVED", entity_type="finance.Revenue",
                                   entity_id=revenue.id, amount_xaf=revenue.amount_xaf,
                                   actor=revenue.approved_by, payload={"code": revenue.code})


@transaction.atomic
def record_payment(*, actor, expense: Expense, amount_xaf: int, method: str,
                   reference: str = "", request=None) -> Payment:
    expense = Expense.objects.select_for_update().get(pk=expense.pk)
    if expense.status not in {Expense.Status.APPROVED, Expense.Status.PARTIALLY_PAID}:
        raise ValidationError("Seule une dépense approuvée peut être payée.")
    remaining = expense.amount_xaf - expense.paid_total
    if amount_xaf <= 0 or amount_xaf > remaining:
        raise ValidationError(f"Montant invalide : reste à payer {remaining} XAF.")
    if not expense.document:
        raise ValidationError("Une pièce justificative est obligatoire avant tout paiement.")
    seq = next_sequence(expense.agency_id, "payment", year=expense.fiscal_year.year)
    payment = Payment.objects.create(
        code=format_number(expense.agency.code, "PAI", seq, width=5),
        agency=expense.agency, expense=expense, amount_xaf=amount_xaf,
        method=method, reference=reference, recorded_by=actor,
    )
    total_paid = expense.paid_total
    expense.status = Expense.Status.PAID if total_paid >= expense.amount_xaf else Expense.Status.PARTIALLY_PAID
    if expense.status == Expense.Status.PAID:
        expense.paid_at = timezone.now()
    expense.save(update_fields=["status", "paid_at", "updated_at"])
    append_financial_event(agency=expense.agency, fiscal_year=expense.fiscal_year,
                           event_type="EXPENSE_PAID", entity_type="finance.Expense",
                           entity_id=expense.id, amount_xaf=amount_xaf, actor=actor,
                           payload={"payment": payment.code, "total_paid": total_paid})
    audit(action="PAYMENT_RECORDED", actor=actor, entity=expense, agency_id=expense.agency_id,
          after={"amount": amount_xaf, "method": method}, request=request)
    emit(entity=expense, op_type="STATE", actor=actor, agency_id=expense.agency_id)
    return payment


@transaction.atomic
def create_revenue(*, actor, agency, data: dict, request=None) -> Revenue:
    fiscal_year = data["fiscal_year"]
    ensure_open(fiscal_year)
    seq = next_sequence(agency.id, "revenue", year=fiscal_year.year)
    revenue = Revenue.objects.create(
        code=format_number(agency.code, f"REC{str(fiscal_year.year)[-2:]}", seq, width=5),
        agency=agency, fiscal_year=fiscal_year, budget_line=data.get("budget_line"),
        category=data["category"], funding_source=data.get("funding_source"),
        activity=data.get("activity"), label=data["label"], amount_xaf=data["amount_xaf"],
        received_on=data.get("received_on") or timezone.localdate(),
        payment_method=data.get("payment_method", ""), reference=data.get("reference", ""),
        status=Revenue.Status.DRAFT, created_by=actor,
    )
    audit(action="REVENUE_CREATED", actor=actor, entity=revenue, agency_id=agency.id, request=request)
    emit(entity=revenue, op_type="CREATE", actor=actor, agency_id=agency.id)
    return revenue


@transaction.atomic
def submit_revenue(*, actor, revenue: Revenue):
    from apps.approvals.services import open_request
    if revenue.status not in {Revenue.Status.DRAFT, Revenue.Status.REJECTED}:
        raise ValidationError("Seule une recette en brouillon peut être soumise.")
    revenue.status = Revenue.Status.PENDING
    revenue.save(update_fields=["status", "updated_at"])
    open_request(entity_type="finance.Revenue", entity_id=revenue.id, agency=revenue.agency,
                 actor=actor, amount_xaf=revenue.amount_xaf, comment=revenue.label)


def indicators(agency, fiscal_year=None) -> dict:
    fiscal_year = fiscal_year or current_fiscal_year(agency)
    if not fiscal_year:
        return {"approved": 0, "engaged": 0, "executed": 0, "available": 0, "rate": 0, "revenue": 0}
    budget = Budget.objects.filter(agency=agency, fiscal_year=fiscal_year,
                                   status__in=["APPROVED", "REVISED"]).order_by("-version_number").first()
    if budget is None:
        budget = Budget.objects.filter(agency=agency, fiscal_year=fiscal_year).order_by("-version_number").first()
    approved = budget.total_xaf if budget else 0
    from django.db.models import Q
    expenses = Expense.objects.filter(agency=agency, fiscal_year=fiscal_year)
    sums = expenses.aggregate(
        engaged=Sum("amount_xaf", filter=Q(status__in=ENGAGED_STATUSES)),
        executed=Sum("amount_xaf", filter=Q(status__in=EXECUTED_STATUSES)),
    )
    engaged = sums["engaged"] or 0
    executed = sums["executed"] or 0
    revenues = Revenue.objects.filter(
        agency=agency, fiscal_year=fiscal_year, status__in=["APPROVED", "RECEIVED"]
    ).aggregate(total=Sum("amount_xaf"))["total"] or 0
    return {
        "budget": budget, "approved": approved, "engaged": engaged,
        "executed": executed, "available": approved - engaged,
        "rate": round(executed / approved * 100, 1) if approved else 0,
        "revenue": revenues,
        "by_category": list(
            expenses.filter(status__in=ENGAGED_STATUSES).values("category__name_fr")
            .annotate(total=Sum("amount_xaf")).order_by("-total")
        ),
    }
