from datetime import date, timedelta
from decimal import Decimal, ROUND_HALF_UP
from django.db.models import Sum
from django.utils import timezone

from apps.accounting.models import Account, AdvanceRecord, Party, PartyLedgerEntry
from apps.party_hub.models import OpenItem, RetentionSchedule


DEFAULT_BUCKETS = [0, 30, 60, 90, 180, 365]


def _bucket_key(age_days: int) -> str:
    if age_days <= 0:
        return "current"
    if age_days <= 30:
        return "1_30"
    if age_days <= 60:
        return "31_60"
    if age_days <= 90:
        return "61_90"
    if age_days <= 180:
        return "91_180"
    if age_days <= 365:
        return "181_365"
    return "over_365"


BUCKET_KEYS = ["current", "1_30", "31_60", "61_90", "91_180", "181_365", "over_365"]


class AgingAnalysisService:
    """
    7-Bucket Aging & Financial KPI Engine (DSO, DPO, Collection Efficiency, Concentration, Retention Aging).
    Maintains strict separation between ordinary open invoices, held retention, and unallocated cash/advances.
    """

    @staticmethod
    def compute_aging(
        *,
        company,
        hub_side: str,
        as_of_date: date | None = None,
        basis: str = "due_date",
        project_id: str | None = None,
        party_id: str | None = None,
    ) -> dict:
        as_of_date = as_of_date or timezone.localdate()
        qs = OpenItem.objects.select_related("party", "project", "control_account").filter(
            company=company,
            hub_side=hub_side,
            is_unallocated_credit=False,
        ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.WRITTEN_OFF, OpenItem.Status.REVERSED])
        if project_id:
            qs = qs.filter(project_id=project_id)
        if party_id:
            qs = qs.filter(party_id=party_id)

        by_party: dict[str, dict] = {}
        totals = {k: Decimal("0.00") for k in BUCKET_KEYS}
        totals["total"] = Decimal("0.00")

        for oi in qs:
            rem = oi.remaining_amount
            if rem <= 0:
                continue
            ref_date = oi.document_date if basis == "invoice_date" else oi.due_date
            age_days = (as_of_date - ref_date).days
            bk = _bucket_key(age_days)
            pid = str(oi.party_id)
            if pid not in by_party:
                by_party[pid] = {
                    "party_id": pid,
                    "code": oi.party.code,
                    "name": oi.party.name,
                    "party_type": oi.party.party_type,
                    "credit_limit": str(oi.party.credit_limit),
                    "buckets": {k: Decimal("0.00") for k in BUCKET_KEYS},
                    "total_open": Decimal("0.00"),
                    "disputed": Decimal("0.00"),
                }
            by_party[pid]["buckets"][bk] += rem
            by_party[pid]["total_open"] += rem
            if oi.status == OpenItem.Status.DISPUTED:
                by_party[pid]["disputed"] += rem
            totals[bk] += rem
            totals["total"] += rem

        # Retention & Unallocated/Advance separate columns per party
        ret_dir = (
            RetentionSchedule.Direction.RECEIVABLE
            if hub_side == OpenItem.HubSide.RECEIVABLE
            else RetentionSchedule.Direction.PAYABLE
        )
        ret_map: dict[str, Decimal] = {}
        for r in RetentionSchedule.objects.filter(company=company, direction=ret_dir).exclude(
            status=RetentionSchedule.Status.RELEASED
        ):
            ret_map[str(r.party_id)] = ret_map.get(str(r.party_id), Decimal("0.00")) + r.remaining_retention

        unalloc_map: dict[str, Decimal] = {}
        for u in OpenItem.objects.filter(
            company=company, hub_side=hub_side, is_unallocated_credit=True
        ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.REVERSED]):
            unalloc_map[str(u.party_id)] = unalloc_map.get(str(u.party_id), Decimal("0.00")) + u.remaining_amount

        adv_type = (
            AdvanceRecord.AdvanceType.CUSTOMER_ADVANCE
            if hub_side == OpenItem.HubSide.RECEIVABLE
            else AdvanceRecord.AdvanceType.SUPPLIER_ADVANCE
        )
        adv_map: dict[str, Decimal] = {}
        adv_types = [adv_type]
        if hub_side == OpenItem.HubSide.PAYABLE:
            adv_types.append(AdvanceRecord.AdvanceType.MOBILIZATION_ADVANCE)
        for a in AdvanceRecord.objects.filter(company=company, advance_type__in=adv_types).exclude(
            status__in=[AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED]
        ):
            adv_map[str(a.party_id)] = adv_map.get(str(a.party_id), Decimal("0.00")) + a.remaining_amount

        formatted_rows = []
        for pid, row in sorted(by_party.items(), key=lambda kv: kv[1]["total_open"], reverse=True):
            b_str = {k: str(v) for k, v in row["buckets"].items()}
            formatted_rows.append(
                {
                    "party_id": row["party_id"],
                    "code": row["code"],
                    "name": row["name"],
                    "party_type": row["party_type"],
                    "credit_limit": row["credit_limit"],
                    **b_str,
                    "total_open": str(row["total_open"]),
                    "disputed": str(row["disputed"]),
                    "retention_held": str(ret_map.get(pid, Decimal("0.00"))),
                    "unallocated_cash": str(unalloc_map.get(pid, Decimal("0.00"))),
                    "advance_balance": str(adv_map.get(pid, Decimal("0.00"))),
                }
            )

        return {
            "hub_side": hub_side,
            "as_of_date": as_of_date.isoformat(),
            "basis": basis,
            "buckets": BUCKET_KEYS,
            "rows": formatted_rows,
            "totals": {k: str(v) for k, v in totals.items()},
            "retention_total": str(sum(ret_map.values(), Decimal("0.00"))),
            "unallocated_total": str(sum(unalloc_map.values(), Decimal("0.00"))),
            "advance_total": str(sum(adv_map.values(), Decimal("0.00"))),
        }

    @staticmethod
    def compute_kpis_and_analytics(
        *,
        company,
        hub_side: str,
        start_date: date | None = None,
        end_date: date | None = None,
    ) -> dict:
        end_date = end_date or timezone.localdate()
        start_date = start_date or (end_date - timedelta(days=90))
        days_in_period = max((end_date - start_date).days, 1)

        role_filter = (
            [Account.ControlRole.SUNDRY_DEBTORS]
            if hub_side == OpenItem.HubSide.RECEIVABLE
            else [Account.ControlRole.SUNDRY_CREDITORS, Account.ControlRole.SUBCONTRACTOR_PAYABLE]
        )

        # Opening trade balance at start_date and closing trade balance at end_date (excluding retention/advances)
        party_types = (
            [Party.PartyType.CUSTOMER]
            if hub_side == OpenItem.HubSide.RECEIVABLE
            else [Party.PartyType.SUPPLIER, Party.PartyType.SUBCONTRACTOR]
        )
        parties_open = Party.objects.filter(company=company, party_type__in=party_types).aggregate(
            od=Sum("opening_debit"), oc=Sum("opening_credit")
        )
        base_open = (parties_open["od"] or Decimal("0.00")) - (parties_open["oc"] or Decimal("0.00"))

        prior = PartyLedgerEntry.objects.filter(
            company=company, control_account__control_role__in=role_filter, entry_date__lt=start_date
        ).aggregate(d=Sum("debit"), c=Sum("credit"))
        in_period = PartyLedgerEntry.objects.filter(
            company=company,
            control_account__control_role__in=role_filter,
            entry_date__gte=start_date,
            entry_date__lte=end_date,
        ).aggregate(d=Sum("debit"), c=Sum("credit"))

        p_d = prior["d"] or Decimal("0.00")
        p_c = prior["c"] or Decimal("0.00")
        cur_d = in_period["d"] or Decimal("0.00")
        cur_c = in_period["c"] or Decimal("0.00")

        if hub_side == OpenItem.HubSide.RECEIVABLE:
            opening_bal = max(base_open + p_d - p_c, Decimal("0.00"))
            closing_bal = max(opening_bal + cur_d - cur_c, Decimal("0.00"))
            avg_bal = ((opening_bal + closing_bal) / Decimal("2")).quantize(Decimal("0.01"))
            credit_volume = cur_d  # Billed to debtors
            collections = cur_c    # Receipts/Credits
            dso = (
                (avg_bal / credit_volume * Decimal(days_in_period)).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
                if credit_volume > 0
                else Decimal("0.0")
            )
            eligible_due = opening_bal + credit_volume
            collection_eff = (
                (collections / eligible_due * Decimal("100")).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
                if eligible_due > 0
                else Decimal("100.0")
            )
            ratios = {
                "dso_days": str(dso),
                "collection_efficiency_pct": str(min(collection_eff, Decimal("100.0"))),
                "average_receivable": str(avg_bal),
                "credit_sales_period": str(credit_volume),
                "collections_period": str(collections),
                "days_in_period": days_in_period,
            }
        else:
            opening_bal = max(-(base_open + p_d - p_c), Decimal("0.00"))
            closing_bal = max(-(base_open + p_d - p_c + cur_d - cur_c), Decimal("0.00"))
            avg_bal = ((opening_bal + closing_bal) / Decimal("2")).quantize(Decimal("0.01"))
            credit_purchases = cur_c
            payments_made = cur_d
            dpo = (
                (avg_bal / credit_purchases * Decimal(days_in_period)).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
                if credit_purchases > 0
                else Decimal("0.0")
            )
            ratios = {
                "dpo_days": str(dpo),
                "average_payable": str(avg_bal),
                "credit_purchases_period": str(credit_purchases),
                "payments_period": str(payments_made),
                "days_in_period": days_in_period,
            }

        aging = AgingAnalysisService.compute_aging(company=company, hub_side=hub_side, as_of_date=end_date)

        # Project breakdown
        proj_map: dict[str, dict] = {}
        for oi in OpenItem.objects.select_related("project").filter(
            company=company, hub_side=hub_side, is_unallocated_credit=False
        ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.WRITTEN_OFF, OpenItem.Status.REVERSED]):
            rem = oi.remaining_amount
            if rem <= 0:
                continue
            pname = oi.project.name if oi.project else "Unassigned / Head Office"
            pcode = oi.project.code if oi.project else "HO"
            if pcode not in proj_map:
                proj_map[pcode] = {"project_code": pcode, "project_name": pname, "outstanding": Decimal("0.00"), "overdue": Decimal("0.00")}
            proj_map[pcode]["outstanding"] += rem
            if oi.due_date < end_date:
                proj_map[pcode]["overdue"] += rem

        return {
            "hub_side": hub_side,
            "period": {"start_date": start_date.isoformat(), "end_date": end_date.isoformat()},
            "ratios": ratios,
            "aging": aging,
            "top_parties": aging["rows"][:10],
            "by_project": [
                {
                    "project_code": v["project_code"],
                    "project_name": v["project_name"],
                    "outstanding": str(v["outstanding"]),
                    "overdue": str(v["overdue"]),
                }
                for v in sorted(proj_map.values(), key=lambda x: x["outstanding"], reverse=True)
            ],
        }

