from decimal import Decimal
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, BillAllocation, Party, PartyLedgerEntry, Voucher


class SubledgerService:
    @staticmethod
    def get_party_summary(company, party: Party) -> dict:
        agg = PartyLedgerEntry.objects.filter(company=company, party=party).aggregate(
            d=Sum("debit"), c=Sum("credit"), ret=Sum("retention_amount"), adv=Sum("advance_adjusted")
        )
        opening_net = party.opening_debit - party.opening_credit
        period_d = agg["d"] or Decimal("0.00")
        period_c = agg["c"] or Decimal("0.00")
        net = opening_net + period_d - period_c
        return {
            "id": str(party.id),
            "code": party.code,
            "name": party.name,
            "party_type": party.party_type,
            "pan_vat_no": party.pan_vat_no,
            "credit_limit": str(party.credit_limit),
            "opening_net": str(opening_net),
            "total_debit": str(period_d),
            "total_credit": str(period_c),
            "closing_balance": str(abs(net)),
            "closing_side": "Dr" if net >= 0 else "Cr",
            "net_signed": str(net),
            "retention_total": str(agg["ret"] or Decimal("0.00")),
        }

    @staticmethod
    def get_party_statement(company, party: Party) -> dict:
        entries = (
            PartyLedgerEntry.objects.select_related("voucher", "control_account", "project")
            .filter(company=company, party=party)
            .order_by("entry_date", "created_at")
        )
        summary = SubledgerService.get_party_summary(company, party)
        running = party.opening_debit - party.opening_credit
        rows = []
        for e in entries:
            running += e.debit - e.credit
            rows.append(
                {
                    "id": str(e.id),
                    "entry_date": e.entry_date.isoformat(),
                    "bs_date": e.bs_date,
                    "due_date": e.due_date.isoformat() if e.due_date else "",
                    "voucher_id": str(e.voucher_id),
                    "voucher_no": e.voucher.voucher_no,
                    "voucher_type": e.voucher.voucher_type,
                    "entry_kind": e.entry_kind,
                    "project_code": e.project.code if e.project else "",
                    "debit": str(e.debit),
                    "credit": str(e.credit),
                    "running_balance": str(abs(running)),
                    "running_side": "Dr" if running >= 0 else "Cr",
                    "narration": e.narration,
                }
            )
        return {"party": summary, "entries": rows}

    @staticmethod
    def get_party_aging(company, party_type: str | None = None) -> dict:
        today = timezone.localdate()
        qs = Party.objects.filter(company=company, is_active=True)
        if party_type:
            qs = qs.filter(party_type=party_type)

        rows = []
        totals = {"0_30": Decimal("0.00"), "31_60": Decimal("0.00"), "61_90": Decimal("0.00"), "over_90": Decimal("0.00"), "total": Decimal("0.00")}
        for p in qs:
            b = {"0_30": Decimal("0.00"), "31_60": Decimal("0.00"), "61_90": Decimal("0.00"), "over_90": Decimal("0.00")}
            net = p.opening_debit - p.opening_credit
            for e in PartyLedgerEntry.objects.filter(company=company, party=p):
                delta = e.debit - e.credit
                net += delta
                age_days = (today - (e.due_date or e.entry_date)).days
                amt = abs(delta)
                if age_days <= 30:
                    b["0_30"] += amt
                elif age_days <= 60:
                    b["31_60"] += amt
                elif age_days <= 90:
                    b["61_90"] += amt
                else:
                    b["over_90"] += amt
            if net == 0 and all(v == 0 for v in b.values()):
                continue
            for k in b:
                totals[k] += b[k]
            totals["total"] += abs(net)
            rows.append(
                {
                    "party_id": str(p.id),
                    "code": p.code,
                    "name": p.name,
                    "party_type": p.party_type,
                    "closing_balance": str(abs(net)),
                    "closing_side": "Dr" if net >= 0 else "Cr",
                    "0_30": str(b["0_30"]),
                    "31_60": str(b["31_60"]),
                    "61_90": str(b["61_90"]),
                    "over_90": str(b["over_90"]),
                }
            )
        return {"rows": rows, "totals": {k: str(v) for k, v in totals.items()}}

    @staticmethod
    @transaction.atomic
    def allocate_bill(*, company, party: Party, settlement_voucher: Voucher, against_voucher: Voucher, allocated_amount: Decimal, tds_withheld: Decimal = Decimal("0.00"), retention_released: Decimal = Decimal("0.00")) -> BillAllocation:
        if settlement_voucher.company_id != company.id or against_voucher.company_id != company.id:
            raise ValidationError("Cross-company bill allocation blocked.")
        if allocated_amount <= 0:
            raise ValidationError("Allocated amount must exceed zero.")
        obj, _ = BillAllocation.objects.update_or_create(
            settlement_voucher=settlement_voucher,
            against_voucher=against_voucher,
            defaults={
                "company": company,
                "party": party,
                "allocated_amount": allocated_amount,
                "tds_withheld": tds_withheld,
                "retention_released": retention_released,
            },
        )
        return obj

    @staticmethod
    def reconcile_control_account(company, control_role: str) -> dict:
        ctrl_accs = list(Account.objects.filter(company=company, control_role=control_role, is_group=False).order_by("code"))
        if not ctrl_accs:
            return {
                "control_role": control_role,
                "account_code": "",
                "gl_balance": "0.00",
                "subledger_balance": "0.00",
                "difference": "0.00",
                "is_reconciled": True,
            }
        from apps.accounting.models import LedgerEntry

        gl_net = Decimal("0.00")
        sub_net = Decimal("0.00")
        for acc in ctrl_accs:
            gl_agg = LedgerEntry.objects.filter(company=company, account=acc).aggregate(
                d=Sum("base_debit"), c=Sum("base_credit")
            )
            gl_net += (acc.opening_debit - acc.opening_credit) + (gl_agg["d"] or Decimal("0.00")) - (gl_agg["c"] or Decimal("0.00"))
            sub_agg = PartyLedgerEntry.objects.filter(company=company, control_account=acc).aggregate(
                d=Sum("debit"), c=Sum("credit")
            )
            sub_net += (sub_agg["d"] or Decimal("0.00")) - (sub_agg["c"] or Decimal("0.00"))
            for p in Party.objects.filter(company=company, control_account=acc):
                sub_net += p.opening_debit - p.opening_credit

        codes = ", ".join(a.code for a in ctrl_accs)
        return {
            "control_role": control_role,
            "account_code": codes,
            "gl_balance": str(gl_net),
            "subledger_balance": str(sub_net),
            "difference": str(gl_net - sub_net),
            "is_reconciled": gl_net == sub_net,
        }

