from decimal import Decimal
from django.db import transaction
from django.db.models import Q, Sum
from django.utils import timezone

from economy.models import LedgerEntry, Wallet
from .constants import (
    BudgetStatus, FFPStatus, FinanceCategory, FinanceDirection,
    INCOME_TYPES, EXPENSE_TYPES, FINANCING_IN_TYPES, FINANCING_OUT_TYPES,
)
from .models import (
    AccountingPeriod, LedgerClassification, ClubBudget, BudgetLine,
    FFPPolicy, FFPAssessment, FinancialControlEvent,
)
from .exceptions import BudgetIntegrityError, FFPPolicyError

ZERO = Decimal("0")


def q8(value):
    return Decimal(value or 0).quantize(Decimal("0.00000001"))


class AccountingPeriodService:
    @staticmethod
    def current_for(club, at=None):
        at = at or timezone.now()
        return AccountingPeriod.objects.filter(club=club, starts_at__lte=at, ends_at__gt=at).order_by("-starts_at").first()

    @staticmethod
    @transaction.atomic
    def close(period):
        # Period close is now a controlled GL operation: sync accruals, post
        # depreciation/amortization, assert trial-balance equality, snapshot all
        # three statements, post closing entries, then lock the period.
        from .accounting import PeriodCloseService
        return PeriodCloseService.close(period)


class LedgerClassificationService:
    """Projects canonical Economy ledger entries into club accounting/FFP categories.

    Marketplace escrow/refund movements are intentionally *not* projected into
    accounting.  A club-asset acquisition is classified only after the market
    settlement succeeds, via :meth:`classify_marketplace_purchase`.
    """

    TEMPORARY_MARKET_TYPES = {"MARKETPLACE_ESCROW", "MARKETPLACE_REFUND", "FRIENDLY_RESERVE", "FRIENDLY_REFUND"}

    @staticmethod
    def _category(entry, club_wallet):
        is_income = entry.destination_wallet_id == club_wallet.id
        is_expense = entry.source_wallet_id == club_wallet.id
        if is_income and entry.transaction_type in FINANCING_IN_TYPES:
            return FinanceDirection.FINANCING, FINANCING_IN_TYPES[entry.transaction_type]
        if is_expense and entry.transaction_type in FINANCING_OUT_TYPES:
            return FinanceDirection.FINANCING, FINANCING_OUT_TYPES[entry.transaction_type]
        # ITEM_PURCHASE is used by multiple asset workflows. Maintenance is a
        # period operating cost; upgrades and durable acquisitions are CAPEX.
        if is_expense and entry.transaction_type == "ITEM_PURCHASE":
            if entry.reference_type == "CLUB_ASSET_MAINTENANCE":
                return FinanceDirection.EXPENSE, FinanceCategory.FACILITY_OPEX
            return FinanceDirection.EXPENSE, FinanceCategory.MARKETPLACE_CAPEX
        if is_expense and entry.reference_type == 'CLUB_LEVEL_UPGRADE':
            return FinanceDirection.EXPENSE,FinanceCategory.MARKETPLACE_CAPEX
        if is_income:
            return FinanceDirection.INCOME, INCOME_TYPES.get(entry.transaction_type, FinanceCategory.OTHER_INCOME)
        if is_expense:
            return FinanceDirection.EXPENSE, EXPENSE_TYPES.get(entry.transaction_type, FinanceCategory.OTHER_EXPENSE)
        return FinanceDirection.NEUTRAL, FinanceCategory.OTHER_EXPENSE

    @classmethod
    @transaction.atomic
    def classify_entry(cls, *, club, entry):
        # Escrow/refund are balance-sheet movements, not realized expenses.
        if entry.transaction_type in cls.TEMPORARY_MARKET_TYPES:
            return None
        wallet = Wallet.objects.filter(club=club).first()
        if wallet is None:
            raise ValueError("Club wallet does not exist")
        if entry.source_wallet_id != wallet.id and entry.destination_wallet_id != wallet.id:
            raise ValueError("Ledger entry does not affect this club")
        existing = LedgerClassification.objects.filter(ledger_entry=entry, club=club).first()
        if existing:
            return existing
        direction, category = cls._category(entry, wallet)
        period = AccountingPeriod.objects.filter(club=club, starts_at__lte=entry.created_at, ends_at__gt=entry.created_at).order_by("-starts_at").first()
        capex = category == FinanceCategory.MARKETPLACE_CAPEX
        ffp_relevant = entry.transaction_type not in {"DEPOSIT", "WITHDRAWAL", "ADMIN_ADJUSTMENT", "REFUND", "MARKETPLACE_REFUND", "MARKETPLACE_ESCROW", "CLUB_LOAN_DISBURSEMENT", "CLUB_LOAN_PRINCIPAL_REPAYMENT"}
        return LedgerClassification.objects.create(
            ledger_entry=entry, club=club, period=period, direction=direction,
            category=category, amount=entry.amount, ffp_relevant=ffp_relevant,
            capex=capex,
            evidence={
                "transaction_type": entry.transaction_type,
                "reference_type": entry.reference_type,
                "reference_id": entry.reference_id,
                "source_wallet": str(entry.source_wallet_id or ""),
                "destination_wallet": str(entry.destination_wallet_id or ""),
            },
        )

    @classmethod
    @transaction.atomic
    def classify_marketplace_purchase(cls, *, club, entry):
        """Classify a successfully settled club-asset acquisition as CAPEX.

        ``entry`` is the original club-wallet -> marketplace-escrow funding
        ledger.  We only promote it into accounting once ownership transfer has
        completed inside the same outer transaction.
        """
        wallet = Wallet.objects.filter(club=club).first()
        if wallet is None:
            raise ValueError("Club wallet does not exist")
        if entry.source_wallet_id != wallet.id:
            raise ValueError("Marketplace purchase was not funded by this club")
        existing = LedgerClassification.objects.filter(ledger_entry=entry, club=club).first()
        if existing:
            if (
                existing.club_id == club.id
                and existing.direction == FinanceDirection.EXPENSE
                and existing.category == FinanceCategory.MARKETPLACE_CAPEX
                and existing.capex
            ):
                return existing
            raise ValueError("Funding ledger already has a conflicting accounting classification")
        period = AccountingPeriod.objects.filter(
            club=club, starts_at__lte=entry.created_at, ends_at__gt=entry.created_at
        ).order_by("-starts_at").first()
        return LedgerClassification.objects.create(
            ledger_entry=entry, club=club, period=period,
            direction=FinanceDirection.EXPENSE,
            category=FinanceCategory.MARKETPLACE_CAPEX,
            amount=entry.amount, ffp_relevant=True, capex=True,
            evidence={
                "transaction_type": entry.transaction_type,
                "reference_type": entry.reference_type,
                "reference_id": entry.reference_id,
                "source_wallet": str(entry.source_wallet_id or ""),
                "destination_wallet": str(entry.destination_wallet_id or ""),
                "marketplace_settled": True,
            },
        )

    @classmethod
    @transaction.atomic
    def classify_marketplace_lease_rent(cls, *, club, entry):
        """Classify only the non-refundable rent leg of a club-asset lease."""
        wallet = Wallet.objects.filter(club=club).first()
        if wallet is None:
            raise ValueError("Club wallet does not exist")
        if entry.source_wallet_id != wallet.id:
            raise ValueError("Marketplace lease rent was not funded by this club")
        existing = LedgerClassification.objects.filter(ledger_entry=entry, club=club).first()
        if existing:
            if (existing.club_id == club.id and existing.direction == FinanceDirection.EXPENSE
                    and existing.category == FinanceCategory.FACILITY_OPEX and not existing.capex):
                return existing
            raise ValueError("Lease funding ledger already has a conflicting accounting classification")
        period = AccountingPeriod.objects.filter(
            club=club, starts_at__lte=entry.created_at, ends_at__gt=entry.created_at
        ).order_by("-starts_at").first()
        return LedgerClassification.objects.create(
            ledger_entry=entry, club=club, period=period,
            direction=FinanceDirection.EXPENSE, category=FinanceCategory.FACILITY_OPEX,
            amount=entry.amount, ffp_relevant=True, capex=False,
            evidence={
                "transaction_type": entry.transaction_type,
                "reference_type": entry.reference_type,
                "reference_id": entry.reference_id,
                "marketplace_lease_rent_settled": True,
            },
        )

    @classmethod
    def sync_club(cls, *, club, period=None):
        wallet = Wallet.objects.filter(club=club).first()
        if wallet is None:
            return {"created": 0, "total": 0}
        qs = (LedgerEntry.objects
              .filter(Q(source_wallet=wallet) | Q(destination_wallet=wallet))
              .exclude(transaction_type__in=cls.TEMPORARY_MARKET_TYPES)
              .order_by("created_at", "id"))
        if period:
            qs = qs.filter(created_at__gte=period.starts_at, created_at__lt=period.ends_at)
        created = 0
        for entry in qs.iterator():
            if not LedgerClassification.objects.filter(ledger_entry=entry, club=club).exists():
                classification = cls.classify_entry(club=club, entry=entry)
                if classification is not None:
                    created += 1
        return {"created": created, "total": qs.count()}


class BudgetService:
    @staticmethod
    @transaction.atomic
    def activate(budget):
        from clubs.models import Club
        Club.objects.select_for_update().get(pk=budget.club_id)
        locked = ClubBudget.objects.select_for_update().get(pk=budget.pk)
        if locked.period.is_closed: raise BudgetIntegrityError("Cannot activate a budget for a closed period")
        if locked.status == BudgetStatus.ACTIVE:
            return locked
        if locked.status != BudgetStatus.DRAFT:
            raise BudgetIntegrityError("Only DRAFT budgets can be activated")
        if not locked.lines.exists():
            raise BudgetIntegrityError("Budget requires at least one line")
        ClubBudget.objects.filter(club=locked.club, period=locked.period, status=BudgetStatus.ACTIVE).update(status=BudgetStatus.CLOSED, closed_at=timezone.now())
        locked.status = BudgetStatus.ACTIVE
        locked.activated_at = timezone.now()
        locked.save(update_fields=["status", "activated_at", "updated_at"])
        FinancialControlEvent.objects.create(club=locked.club, event_type="BUDGET_ACTIVATED", reference_type="BUDGET", reference_id=str(locked.pk))
        return locked

    @staticmethod
    def actual_by_category(budget):
        qs = LedgerClassification.objects.filter(club=budget.club, period=budget.period, direction__in=[FinanceDirection.EXPENSE, FinanceDirection.FINANCING])
        values = {row["category"]: q8(row["actual"]) for row in qs.values("category").annotate(actual=Sum("amount"))}
        return values

    @classmethod
    def report(cls, budget):
        actuals = cls.actual_by_category(budget)
        lines = []
        total_plan = ZERO
        total_actual = ZERO
        for line in budget.lines.all().order_by("category"):
            actual = actuals.get(line.category, ZERO)
            variance = q8(line.planned_amount - actual)
            used_pct = (actual / line.planned_amount * 100) if line.planned_amount > 0 else (Decimal("100") if actual > 0 else ZERO)
            status = "OVER" if actual > line.planned_amount else ("WARNING" if used_pct >= line.warning_threshold_pct else "OK")
            lines.append({
                "category": line.category, "planned": str(q8(line.planned_amount)), "actual": str(q8(actual)),
                "variance": str(variance), "used_pct": str(used_pct.quantize(Decimal("0.01"))),
                "hard_limit": line.hard_limit, "status": status,
            })
            total_plan += line.planned_amount
            total_actual += actual
        return {"budget_id": str(budget.pk), "status": budget.status, "planned_total": str(q8(total_plan)), "actual_total": str(q8(total_actual)), "lines": lines}

    @classmethod
    def check_spend(cls, *, club, category, amount, period=None):
        period = period or AccountingPeriodService.current_for(club)
        if period is None:
            return {"allowed": True, "reason": "NO_ACTIVE_PERIOD"}
        budget = ClubBudget.objects.filter(club=club, period=period, status=BudgetStatus.ACTIVE).prefetch_related("lines").first()
        if budget is None:
            return {"allowed": True, "reason": "NO_ACTIVE_BUDGET"}
        line = budget.lines.filter(category=category).first()
        if line is None:
            return {"allowed": True, "reason": "UNBUDGETED_CATEGORY"}
        actual = LedgerClassification.objects.filter(club=club, period=period, direction__in=[FinanceDirection.EXPENSE, FinanceDirection.FINANCING], category=category).aggregate(v=Sum("amount"))["v"] or ZERO
        if category == FinanceCategory.MARKETPLACE_CAPEX:
            # Bid/offer holds commit budget until refunded or realized. Settled
            # purchases already occur in classifications and are not counted twice.
            from marketplace.models import MarketplaceBid, MarketplaceOffer
            for model, states in [(MarketplaceBid,['LEADING']),(MarketplaceOffer,['OPEN'])]:
                actual += model.objects.filter(funding_wallet__club=club,status__in=states,
                    funding_ledger__created_at__gte=period.starts_at,
                    funding_ledger__created_at__lt=period.ends_at).aggregate(v=Sum('amount'))['v'] or ZERO
        projected = q8(actual + Decimal(amount))
        allowed = not line.hard_limit or projected <= line.planned_amount
        return {"allowed": allowed, "reason": "OK" if allowed else "HARD_LIMIT_EXCEEDED", "actual": str(q8(actual)), "projected": str(projected), "limit": str(q8(line.planned_amount))}


class FFPService:
    @staticmethod
    def active_policy(at=None):
        at = at or timezone.now()
        policy = FFPPolicy.objects.filter(is_active=True, effective_from__lte=at).filter(Q(effective_to__isnull=True) | Q(effective_to__gt=at)).order_by("-effective_from", "-version").first()
        if policy is None:
            raise FFPPolicyError("No active FFP policy")
        return policy

    @classmethod
    def assess(cls, *, club, period, policy=None):
        LedgerClassificationService.sync_club(club=club, period=period)
        policy = policy or cls.active_policy(period.ends_at)
        qs = LedgerClassification.objects.filter(club=club, period=period, ffp_relevant=True)
        income = q8(qs.filter(direction=FinanceDirection.INCOME).aggregate(v=Sum("amount"))["v"] or ZERO)
        expense = q8(qs.filter(direction=FinanceDirection.EXPENSE).aggregate(v=Sum("amount"))["v"] or ZERO)
        gross_wage = q8(qs.filter(direction=FinanceDirection.EXPENSE, category__in=[FinanceCategory.PLAYER_WAGES, FinanceCategory.STAFF_WAGES, FinanceCategory.PAYROLL_BONUS, FinanceCategory.SIGNING_BONUS, FinanceCategory.TERMINATION_COMPENSATION]).aggregate(v=Sum("amount"))["v"] or ZERO)
        loan_wage_recovery = q8(qs.filter(direction=FinanceDirection.INCOME, category=FinanceCategory.LOAN_WAGE_RECOVERY).aggregate(v=Sum("amount"))["v"] or ZERO)
        wage = max(ZERO, q8(gross_wage - loan_wage_recovery))
        transfer = q8(qs.filter(direction=FinanceDirection.EXPENSE, category=FinanceCategory.TRANSFER_SPEND).aggregate(v=Sum("amount"))["v"] or ZERO)
        result = q8(income - expense)
        wage_ratio = (wage / income) if income > 0 else None
        transfer_ratio = (transfer / income) if income > 0 else None
        reasons = []
        breach = False
        warning = False
        if result < -policy.max_loss:
            breach = True; reasons.append("MAX_LOSS_EXCEEDED")
        if wage_ratio is not None and wage_ratio > policy.max_wage_to_revenue_ratio:
            breach = True; reasons.append("WAGE_TO_REVENUE_EXCEEDED")
        if transfer_ratio is not None and transfer_ratio > policy.max_transfer_spend_to_revenue_ratio:
            breach = True; reasons.append("TRANSFER_SPEND_TO_REVENUE_EXCEEDED")
        buffer = Decimal("1") - (policy.warning_buffer_pct / Decimal("100"))
        if not breach:
            if result < -(policy.max_loss * buffer): warning = True; reasons.append("LOSS_NEAR_LIMIT")
            if wage_ratio is not None and wage_ratio > policy.max_wage_to_revenue_ratio * buffer: warning = True; reasons.append("WAGE_RATIO_NEAR_LIMIT")
            if transfer_ratio is not None and transfer_ratio > policy.max_transfer_spend_to_revenue_ratio * buffer: warning = True; reasons.append("TRANSFER_RATIO_NEAR_LIMIT")
        if income == 0 and (expense > 0 or transfer > 0 or wage > 0):
            warning = True; reasons.append("NO_RELEVANT_REVENUE")
        status = FFPStatus.BREACH if breach else (FFPStatus.WARNING if warning else FFPStatus.COMPLIANT)
        evidence = {
            "classification_count": qs.count(), "policy_version": policy.version,
            "gross_wage_cost": str(gross_wage), "loan_wage_recovery": str(loan_wage_recovery),
            "period_start": period.starts_at.isoformat(), "period_end": period.ends_at.isoformat(),
        }
        assessment = FFPAssessment.objects.create(
            club=club, period=period, policy=policy, status=status,
            relevant_income=income, relevant_expense=expense, result=result,
            wage_cost=wage, transfer_spend=transfer,
            wage_to_revenue_ratio=wage_ratio, transfer_spend_to_revenue_ratio=transfer_ratio,
            reasons=reasons, evidence=evidence,
        )
        if status != FFPStatus.COMPLIANT:
            FinancialControlEvent.objects.create(club=club, event_type="FFP_ASSESSMENT_ALERT", severity="HIGH" if status == FFPStatus.BREACH else "WARNING", reference_type="FFP_ASSESSMENT", reference_id=str(assessment.pk), payload={"status": status, "reasons": reasons})
            from core_runtime.services import OutboxService
            OutboxService.enqueue(
                topic="club_finance.ffp", event_type="ffp.assessment.alert", aggregate_type="Club", aggregate_id=club.pk,
                deduplication_key=f"ffp-alert:{assessment.pk}",
                payload={
                    "club_id": str(club.pk), "assessment_id": str(assessment.pk), "status": status,
                    "reasons": reasons, "period_id": str(period.pk),
                    "message": "FFP assessment requires attention.",
                },
            )
        return assessment


class FinanceDashboardService:
    @staticmethod
    def summary(*, club, period=None):
        period = period or AccountingPeriodService.current_for(club)
        if period is None:
            return {"club_id": str(club.pk), "period": None}
        LedgerClassificationService.sync_club(club=club, period=period)
        qs = LedgerClassification.objects.filter(club=club, period=period)
        income = q8(qs.filter(direction=FinanceDirection.INCOME).exclude(ledger_entry__transaction_type__in=['DEPOSIT','ADMIN_ADJUSTMENT']).aggregate(v=Sum("amount"))["v"] or ZERO)
        expense = q8(qs.filter(direction=FinanceDirection.EXPENSE).aggregate(v=Sum("amount"))["v"] or ZERO)
        financing_in = q8(qs.filter(direction=FinanceDirection.FINANCING, category=FinanceCategory.LOAN_PROCEEDS).aggregate(v=Sum("amount"))["v"] or ZERO)
        owner_funding=q8(qs.filter(ledger_entry__transaction_type__in=['DEPOSIT','ADMIN_ADJUSTMENT'],ledger_entry__destination_wallet__club=club).aggregate(v=Sum('amount'))['v'] or ZERO)
        financing_in=q8(financing_in+owner_funding)
        financing_out = q8(qs.filter(direction=FinanceDirection.FINANCING, category=FinanceCategory.DEBT_PRINCIPAL).aggregate(v=Sum("amount"))["v"] or ZERO)
        by_category = list(qs.values("direction", "category").annotate(amount=Sum("amount")).order_by("direction", "category"))
        budget = ClubBudget.objects.filter(club=club, period=period, status=BudgetStatus.ACTIVE).first()
        latest_ffp = FFPAssessment.objects.filter(club=club, period=period).first()
        return {
            "club_id": str(club.pk), "period": {"id": str(period.pk), "name": period.name},
            "income": str(income), "expense": str(expense), "net": str(q8(income-expense)),
            "financing_in": str(financing_in), "financing_out": str(financing_out), "cash_after_financing": str(q8(income-expense+financing_in-financing_out)),
            "owner_funding":str(owner_funding),
            "categories": [{**x, "amount": str(q8(x["amount"]))} for x in by_category],
            "budget": BudgetService.report(budget) if budget else None,
            "ffp": ({"id": str(latest_ffp.pk), "status": latest_ffp.status, "result": str(latest_ffp.result), "reasons": latest_ffp.reasons} if latest_ffp else None),
        }
