from decimal import Decimal, ROUND_HALF_UP
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Sum
from django.utils import timezone

from apps.accounting.models import Account, LedgerEntry, Voucher
from apps.accounting.services import PostingRuleEngine
from apps.audit.services import record_audit_event
from .models import (
    Budget,
    BudgetCommitment,
    BudgetLine,
    BudgetTransfer,
    BudgetVersion,
    ForecastScenario,
)


class BudgetControlService:
    """Enterprise baseline budgeting, live commitment reservation/relief & variance engine."""

    @staticmethod
    @transaction.atomic
    def create_budget(*, company, user, data: dict, lines_data: list[dict]) -> Budget:
        budget = Budget.objects.create(
            company=company,
            budget_code=data["budget_code"],
            title=data["title"],
            budget_type=data.get("budget_type", Budget.BudgetType.PROJECT),
            fiscal_year=data["fiscal_year"],
            branch=data.get("branch"),
            project=data.get("project"),
            site=data.get("site"),
            department=data.get("department"),
            notes=data.get("notes", ""),
            created_by=user,
            status=Budget.Status.DRAFT,
        )
        ver = BudgetVersion.objects.create(
            budget=budget,
            version_no=1,
            is_baseline=True,
            is_active=True,
            revision_reason="Initial approved baseline budget",
            created_by=user,
        )
        for line in lines_data:
            BudgetLine.objects.create(
                budget_version=ver,
                cost_category=line.get("cost_category", BudgetLine.CostCategory.MATERIAL),
                cost_code=line.get("cost_code"),
                boq_item=line.get("boq_item"),
                account=line.get("account"),
                description=line.get("description", ""),
                approved_amount=Decimal(str(line.get("approved_amount") or "0.00")),
                month_breakdown=line.get("month_breakdown") or {},
            )
        record_audit_event(
            company=company,
            actor=user,
            action="BUDGET_CREATED",
            entity_type="Budget",
            entity_id=str(budget.id),
            new_state={"budget_code": budget.budget_code, "version": 1},
        )
        return budget

    @staticmethod
    @transaction.atomic
    def approve_budget(*, budget: Budget, user) -> Budget:
        budget = Budget.objects.select_for_update().get(pk=budget.pk)
        if budget.status == Budget.Status.APPROVED:
            return budget
        budget.status = Budget.Status.APPROVED
        budget.approved_by = user
        budget.save(update_fields=["status", "approved_by", "updated_at"])
        ver = budget.versions.filter(version_no=budget.current_version_no).first()
        if ver:
            ver.approved_by = user
            ver.approved_at = timezone.now()
            ver.save(update_fields=["approved_by", "approved_at"])
        record_audit_event(
            company=budget.company,
            actor=user,
            action="BUDGET_APPROVED",
            entity_type="Budget",
            entity_id=str(budget.id),
            new_state={"version": budget.current_version_no},
        )
        return budget

    @staticmethod
    @transaction.atomic
    def create_revision(*, budget: Budget, user, reason: str, lines_data: list[dict]) -> BudgetVersion:
        """Creates a new immutable version preserving the original baseline version untouched."""
        budget = Budget.objects.select_for_update().get(pk=budget.pk)
        budget.versions.filter(is_active=True).update(is_active=False)
        next_ver = budget.current_version_no + 1
        ver = BudgetVersion.objects.create(
            budget=budget,
            version_no=next_ver,
            is_baseline=False,
            is_active=True,
            revision_reason=reason,
            created_by=user,
            approved_by=user,
            approved_at=timezone.now(),
        )
        for line in lines_data:
            BudgetLine.objects.create(
                budget_version=ver,
                cost_category=line.get("cost_category", BudgetLine.CostCategory.MATERIAL),
                cost_code=line.get("cost_code"),
                boq_item=line.get("boq_item"),
                account=line.get("account"),
                description=line.get("description", ""),
                approved_amount=Decimal(str(line.get("approved_amount") or "0.00")),
                month_breakdown=line.get("month_breakdown") or {},
            )
        budget.current_version_no = next_ver
        budget.status = Budget.Status.APPROVED
        budget.save(update_fields=["current_version_no", "status", "updated_at"])
        return ver

    @staticmethod
    def get_line_utilization(company, line: BudgetLine) -> dict:
        b = line.budget_version.budget
        baseline_ver = b.versions.filter(is_baseline=True).first()
        baseline_amt = line.approved_amount
        if baseline_ver and baseline_ver.id != line.budget_version_id:
            base_match = baseline_ver.lines.filter(cost_category=line.cost_category, cost_code=line.cost_code).first()
            baseline_amt = base_match.approved_amount if base_match else Decimal("0.00")

        tin = BudgetTransfer.objects.filter(
            company=company, to_budget_line=line, status=BudgetTransfer.Status.EXECUTED
        ).aggregate(s=Sum("amount"))["s"] or Decimal("0.00")
        tout = BudgetTransfer.objects.filter(
            company=company, from_budget_line=line, status=BudgetTransfer.Status.EXECUTED
        ).aggregate(s=Sum("amount"))["s"] or Decimal("0.00")
        effective_budget = (line.approved_amount + tin - tout).quantize(Decimal("0.01"))

        le_qs = LedgerEntry.objects.filter(
            company=company,
            fiscal_year=b.fiscal_year,
            account__account_type=Account.AccountType.EXPENSE,
        )
        if b.project_id:
            le_qs = le_qs.filter(project_id=b.project_id)
        elif line.cost_code_id:
            le_qs = le_qs.filter(cost_code_id=line.cost_code_id)

        if line.cost_code_id and b.project_id:
            le_qs = le_qs.filter(cost_code_id=line.cost_code_id)
        elif line.boq_item_id:
            le_qs = le_qs.filter(boq_item_id=line.boq_item_id)
        elif line.account_id:
            le_qs = le_qs.filter(account_id=line.account_id)

        # Also capture WIP material consumption debits for MATERIAL budgets
        if line.cost_category == BudgetLine.CostCategory.MATERIAL and b.project_id:
            wip_qs = LedgerEntry.objects.filter(
                company=company,
                fiscal_year=b.fiscal_year,
                project_id=b.project_id,
                account__control_role=Account.ControlRole.PROJECT_WIP,
            )
            if line.cost_code_id:
                wip_qs = wip_qs.filter(cost_code_id=line.cost_code_id)
            wip_agg = wip_qs.aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            wip_actual = (wip_agg["d"] or Decimal("0.00")) - (wip_agg["c"] or Decimal("0.00"))
        else:
            wip_actual = Decimal("0.00")

        exp_agg = le_qs.aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        exp_actual = (exp_agg["d"] or Decimal("0.00")) - (exp_agg["c"] or Decimal("0.00"))
        actual_cost = (exp_actual + max(Decimal("0.00"), wip_actual)).quantize(Decimal("0.01"))

        open_comm = Decimal("0.00")
        for cm in BudgetCommitment.objects.filter(
            company=company,
            budget_line=line,
            status__in=[BudgetCommitment.Status.OPEN, BudgetCommitment.Status.PARTIALLY_RELIEVED],
        ):
            open_comm += cm.open_amount

        available = (effective_budget - actual_cost - open_comm).quantize(Decimal("0.01"))
        util_pct = (
            ((actual_cost + open_comm) * Decimal("100") / effective_budget).quantize(Decimal("0.01"))
            if effective_budget > 0
            else Decimal("0.00")
        )
        return {
            "line_id": str(line.id),
            "cost_category": line.cost_category,
            "cost_code": line.cost_code.code if line.cost_code else "",
            "description": line.description or line.cost_category,
            "original_baseline": str(baseline_amt),
            "revised_amount": str(line.approved_amount),
            "transfer_net": str(tin - tout),
            "effective_budget": str(effective_budget),
            "actual_cost": str(actual_cost),
            "open_commitments": str(open_comm),
            "available_budget": str(available),
            "utilization_pct": str(util_pct),
            "is_over_budget": available < Decimal("0.00"),
        }

    @staticmethod
    def get_budget_summary(company, budget: Budget) -> dict:
        ver = budget.versions.filter(version_no=budget.current_version_no).first()
        lines_out = []
        totals = {
            "baseline": Decimal("0.00"),
            "effective": Decimal("0.00"),
            "actual": Decimal("0.00"),
            "committed": Decimal("0.00"),
            "available": Decimal("0.00"),
        }
        if ver:
            for line in ver.lines.select_related("cost_code", "boq_item", "account"):
                u = BudgetControlService.get_line_utilization(company, line)
                lines_out.append(u)
                totals["baseline"] += Decimal(u["original_baseline"])
                totals["effective"] += Decimal(u["effective_budget"])
                totals["actual"] += Decimal(u["actual_cost"])
                totals["committed"] += Decimal(u["open_commitments"])
                totals["available"] += Decimal(u["available_budget"])
        return {
            "budget_id": str(budget.id),
            "budget_code": budget.budget_code,
            "title": budget.title,
            "budget_type": budget.budget_type,
            "version_no": budget.current_version_no,
            "status": budget.status,
            "project_code": budget.project.code if budget.project else "COMPANY",
            "totals": {k: str(v.quantize(Decimal("0.01"))) for k, v in totals.items()},
            "lines": lines_out,
        }

    @staticmethod
    def check_availability(*, company, budget_line: BudgetLine | None, amount: Decimal, allow_override: bool = False) -> tuple[bool, str]:
        if not budget_line:
            return True, ""
        util = BudgetControlService.get_line_utilization(company, budget_line)
        avail = Decimal(util["available_budget"])
        if amount <= avail:
            return True, ""
        msg = f"Over-budget by {(amount - avail).quantize(Decimal('0.01'))} on {util['description']} (Available: {avail})."
        policy = PostingRuleEngine.get_or_create_policy(company)
        if policy.strict_budget_control and not allow_override:
            raise ValidationError(msg)
        return False, msg

    @staticmethod
    @transaction.atomic
    def reserve_commitment(*, company, budget_line: BudgetLine, project, source_type: str, source_id, source_ref: str, amount: Decimal) -> BudgetCommitment:
        return BudgetCommitment.objects.create(
            company=company,
            budget_line=budget_line,
            project=project,
            source_type=source_type,
            source_id=source_id,
            source_ref=source_ref,
            committed_amount=amount,
            status=BudgetCommitment.Status.OPEN,
        )

    @staticmethod
    @transaction.atomic
    def relieve_commitment(*, company, source_type: str, source_id, amount: Decimal) -> None:
        comms = list(
            BudgetCommitment.objects.select_for_update().filter(
                company=company,
                source_type=source_type,
                source_id=source_id,
                status__in=[BudgetCommitment.Status.OPEN, BudgetCommitment.Status.PARTIALLY_RELIEVED],
            )
        )
        remaining_to_relieve = Decimal(str(amount))
        for cm in comms:
            if remaining_to_relieve <= 0:
                break
            take = min(cm.open_amount, remaining_to_relieve)
            cm.relieved_amount += take
            remaining_to_relieve -= take
            cm.status = (
                BudgetCommitment.Status.CLOSED
                if cm.open_amount <= Decimal("0.00")
                else BudgetCommitment.Status.PARTIALLY_RELIEVED
            )
            cm.save(update_fields=["relieved_amount", "status", "updated_at"])

    @staticmethod
    @transaction.atomic
    def execute_transfer(*, company, user, from_line: BudgetLine, to_line: BudgetLine, amount: Decimal, reason: str, transfer_no: str) -> BudgetTransfer:
        if from_line.id == to_line.id:
            raise ValidationError("Source and destination budget lines must differ.")
        util = BudgetControlService.get_line_utilization(company, from_line)
        avail = Decimal(util["available_budget"])
        if amount > avail:
            raise ValidationError(f"Transfer amount ({amount}) exceeds available budget ({avail}) on source line.")
        tr = BudgetTransfer.objects.create(
            company=company,
            transfer_no=transfer_no,
            from_budget_line=from_line,
            to_budget_line=to_line,
            amount=amount,
            reason=reason,
            status=BudgetTransfer.Status.EXECUTED,
            created_by=user,
            approved_by=user,
        )
        record_audit_event(
            company=company,
            actor=user,
            action="BUDGET_TRANSFER_EXECUTED",
            entity_type="BudgetTransfer",
            entity_id=str(tr.id),
            new_state={"amount": str(amount), "from": str(from_line.id), "to": str(to_line.id)},
        )
        return tr

    @staticmethod
    def generate_forecast(*, company, project, fiscal_year, user, scenario_kind: str, name: str) -> ForecastScenario:
        rev_contract = project.contract_amount if project else Decimal("0.00")
        bud_qs = Budget.objects.filter(company=company, fiscal_year=fiscal_year, status=Budget.Status.APPROVED)
        if project:
            bud_qs = bud_qs.filter(project=project)
        total_eff = Decimal("0.00")
        total_act = Decimal("0.00")
        total_comm = Decimal("0.00")
        for b in bud_qs:
            s = BudgetControlService.get_budget_summary(company, b)
            total_eff += Decimal(s["totals"]["effective"])
            total_act += Decimal(s["totals"]["actual"])
            total_comm += Decimal(s["totals"]["committed"])

        mult = (
            Decimal("1.12")
            if scenario_kind == ForecastScenario.ScenarioKind.CONSERVATIVE
            else Decimal("0.94")
            if scenario_kind == ForecastScenario.ScenarioKind.OPTIMISTIC
            else Decimal("1.00")
        )
        cost_to_complete = max(Decimal("0.00"), total_eff - total_act - total_comm) * mult
        proj_cost = (total_act + total_comm + cost_to_complete).quantize(Decimal("0.01"))
        proj_rev = (rev_contract if rev_contract > 0 else proj_cost * Decimal("1.15")).quantize(Decimal("0.01"))
        proj_margin = (proj_rev - proj_cost).quantize(Decimal("0.01"))

        monthly = (cost_to_complete / Decimal("6")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        cf = [{"month": f"M+{i}", "projected_outflow": str(monthly), "projected_inflow": str((proj_rev / Decimal("6")).quantize(Decimal("0.01")))} for i in range(1, 7)]

        return ForecastScenario.objects.create(
            company=company,
            project=project,
            fiscal_year=fiscal_year,
            name=name,
            scenario_kind=scenario_kind,
            projected_revenue=proj_rev,
            projected_cost=proj_cost,
            projected_margin=proj_margin,
            cashflow_projection=cf,
            created_by=user,
        )

