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

from apps.accounting.models import Account, AdvanceRecord, LedgerEntry, Party, PartyLedgerEntry, Voucher
from apps.party_hub.models import (
    ARControlPolicy,
    CollectionActivity,
    CustomerProfile,
    OpenItem,
    PartyDispute,
    PaymentCommitment,
    RABill,
    RetentionSchedule,
    SalesInvoice,
)
from apps.projects.models import ProjectBoqLine
from apps.treasury.cheques.models import ReceivedCheque
from .analytics import AgingAnalysisService
from .ar_billing_service import _q2, get_ar_policy, resolve_ar_accounts


class ARIntelligenceService:
    """
    Enterprise AR Analytics Engine: 15 Executive KPIs, 12 Analytical Charts,
    Methodology-Explicit DSO (AVG_RECEIVABLES vs CLOSING_AR), Configurable Aging,
    Explainable Predictive Risk Scoring, and GL Control Reconciliation.
    """

    @staticmethod
    def _dso_for_window(*, company, start_date: date, end_date: date, method: str, party=None, project=None) -> dict:
        days = max((end_date - start_date).days + 1, 1)

        def _posted_trade_ar_as_of(as_of: date) -> Decimal:
            qs = PartyLedgerEntry.objects.filter(
                company=company,
                entry_date__lte=as_of,
                control_account__control_role=Account.ControlRole.SUNDRY_DEBTORS,
            )
            if party:
                qs = qs.filter(party=party)
            if project:
                qs = qs.filter(project=project)
            agg = qs.aggregate(dr=Sum("debit"), cr=Sum("credit"))
            net = (agg["dr"] or Decimal("0.00")) - (agg["cr"] or Decimal("0.00"))
            # Exclude currently active undisputed-adjusted disputed open items
            disp_qs = OpenItem.objects.filter(
                company=company, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False, status=OpenItem.Status.DISPUTED, document_date__lte=as_of
            )
            if party:
                disp_qs = disp_qs.filter(party=party)
            if project:
                disp_qs = disp_qs.filter(project=project)
            disp_amt = sum((oi.remaining_amount for oi in disp_qs), Decimal("0.00"))
            return max(net - disp_amt, Decimal("0.00"))

        opening_ar = _posted_trade_ar_as_of(start_date - timedelta(days=1))
        closing_ar = _posted_trade_ar_as_of(end_date)
        avg_ar = ((opening_ar + closing_ar) / Decimal("2")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        # Posted Credit Sales in window (exclude Customer Advance receipts, Retention, and Draft/Uncertified bills)
        sales_qs = OpenItem.objects.filter(
            company=company,
            hub_side=OpenItem.HubSide.RECEIVABLE,
            is_unallocated_credit=False,
            document_date__gte=start_date,
            document_date__lte=end_date,
            doc_kind__in=[OpenItem.DocKind.SALES_INVOICE, OpenItem.DocKind.CLIENT_RA_BILL, OpenItem.DocKind.FINAL_BILL, OpenItem.DocKind.VARIATION_CLAIM],
        ).exclude(status=OpenItem.Status.REVERSED)
        if party:
            sales_qs = sales_qs.filter(party=party)
        if project:
            sales_qs = sales_qs.filter(project=project)
        credit_sales = sales_qs.aggregate(total=Sum("original_amount"))["total"] or Decimal("0.00")

        numerator_ar = closing_ar if method == ARControlPolicy.DSOMethod.CLOSING_AR else avg_ar
        dso = (
            (numerator_ar / credit_sales * Decimal(days)).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
            if credit_sales > 0
            else Decimal("0.0")
        )
        return {
            "methodology": method,
            "formula": "(Closing Trade AR / Credit Sales) * Days" if method == ARControlPolicy.DSOMethod.CLOSING_AR else "((Opening AR + Closing AR) / 2 / Credit Sales) * Days",
            "exclusions": ["Draft & Uncertified RA Bills", "Customer Advance Liabilities", "Retention Receivable", "Disputed Balances"],
            "period_start": start_date.isoformat(),
            "period_end": end_date.isoformat(),
            "period_days": days,
            "opening_ar": str(opening_ar),
            "closing_ar": str(closing_ar),
            "average_ar": str(avg_ar),
            "credit_sales": str(credit_sales),
            "dso_days": float(dso),
        }

    @staticmethod
    def compute_dso_suite(*, company, as_of_date: date | None = None, method: str | None = None, party=None, project=None) -> dict:
        today = as_of_date or timezone.localdate()
        policy = get_ar_policy(company)
        use_method = method or policy.dso_method or ARControlPolicy.DSOMethod.AVG_RECEIVABLES

        curr_start = today.replace(day=1)
        prev_end = curr_start - timedelta(days=1)
        prev_start = prev_end.replace(day=1)
        ytd_start = date(today.year, 1, 1)
        r3m_start = today - timedelta(days=89)
        r6m_start = today - timedelta(days=179)

        current = ARIntelligenceService._dso_for_window(company=company, start_date=curr_start, end_date=today, method=use_method, party=party, project=project)
        previous = ARIntelligenceService._dso_for_window(company=company, start_date=prev_start, end_date=prev_end, method=use_method, party=party, project=project)
        ytd = ARIntelligenceService._dso_for_window(company=company, start_date=ytd_start, end_date=today, method=use_method, party=party, project=project)
        rolling_3m = ARIntelligenceService._dso_for_window(company=company, start_date=r3m_start, end_date=today, method=use_method, party=party, project=project)
        rolling_6m = ARIntelligenceService._dso_for_window(company=company, start_date=r6m_start, end_date=today, method=use_method, party=party, project=project)

        by_customer = []
        for p in Party.objects.filter(company=company, party_type=Party.PartyType.CUSTOMER, is_active=True)[:25]:
            row = ARIntelligenceService._dso_for_window(company=company, start_date=r3m_start, end_date=today, method=use_method, party=p)
            if Decimal(row["closing_ar"]) > 0 or Decimal(row["credit_sales"]) > 0:
                by_customer.append({"party_id": str(p.id), "party_code": p.code, "party_name": p.name, **row})
        by_customer.sort(key=lambda x: x["dso_days"], reverse=True)

        return {
            "methodology": use_method,
            "as_of_date": today.isoformat(),
            "current_period": current,
            "previous_period": previous,
            "ytd": ytd,
            "rolling_3m": rolling_3m,
            "rolling_6m": rolling_6m,
            "by_customer": by_customer[:15],
        }

    @staticmethod
    def compute_customer_risk_score(*, company, party: Party, as_of_date: date | None = None) -> dict:
        today = as_of_date or timezone.localdate()
        open_items = list(
            OpenItem.objects.filter(
                company=company, party=party, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False
            ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.WRITTEN_OFF, OpenItem.Status.REVERSED])
        )
        total_ar = sum((oi.remaining_amount for oi in open_items), Decimal("0.00"))
        overdue_90_plus = sum((oi.remaining_amount for oi in open_items if (today - oi.due_date).days > 90), Decimal("0.00"))
        overdue_total = sum((oi.remaining_amount for oi in open_items if oi.due_date < today), Decimal("0.00"))

        broken_promises = PaymentCommitment.objects.filter(
            company=company, party=party, status=PaymentCommitment.Status.BROKEN
        ).count()
        overdue_promises = PaymentCommitment.objects.filter(
            company=company, party=party, status=PaymentCommitment.Status.PENDING, promised_date__lt=today
        ).count()
        open_disputes = PartyDispute.objects.filter(
            company=company, party=party, hub_side=PartyDispute.HubSide.RECEIVABLE
        ).exclude(status=PartyDispute.Status.RESOLVED).count()
        bounced_cheques = ReceivedCheque.objects.filter(
            company=company, customer=party, leaf__status="BOUNCED"
        ).count()

        score = 0
        factors = []
        if total_ar > 0:
            ov_ratio = float(overdue_total / total_ar)
            pts = int(round(ov_ratio * 35))
            if pts > 0:
                score += pts
                factors.append({"factor": "Overdue Ratio", "weight": pts, "detail": f"{round(ov_ratio*100, 1)}% of balance overdue"})
            ov90_ratio = float(overdue_90_plus / total_ar)
            pts90 = int(round(ov90_ratio * 25))
            if pts90 > 0:
                score += pts90
                factors.append({"factor": "90+ Days Severity", "weight": pts90, "detail": f"NPR {overdue_90_plus} past 90 days"})

        if party.credit_limit and party.credit_limit > 0 and total_ar > party.credit_limit:
            score += 15
            factors.append({"factor": "Credit Limit Breach", "weight": 15, "detail": f"AR {total_ar} > Limit {party.credit_limit}"})
        if broken_promises + overdue_promises > 0:
            p_pts = min((broken_promises + overdue_promises) * 8, 16)
            score += p_pts
            factors.append({"factor": "Broken/Overdue Promises", "weight": p_pts, "detail": f"{broken_promises + overdue_promises} missed payment commitments"})
        if open_disputes > 0:
            d_pts = min(open_disputes * 6, 12)
            score += d_pts
            factors.append({"factor": "Active Disputes", "weight": d_pts, "detail": f"{open_disputes} unresolved disputes"})
        if bounced_cheques > 0:
            b_pts = min(bounced_cheques * 10, 20)
            score += b_pts
            factors.append({"factor": "Returned Cheques", "weight": b_pts, "detail": f"{bounced_cheques} bounced customer cheques"})

        score = min(score, 100)
        band = "CRITICAL" if score >= 70 else ("HIGH" if score >= 45 else ("MODERATE" if score >= 20 else "LOW"))
        return {"party_id": str(party.id), "party_name": party.name, "score": score, "risk_band": band, "factors": factors}

    @staticmethod
    def get_ar_dashboard(*, company, as_of_date: date | None = None, project_id=None, customer_id=None) -> dict:
        today = as_of_date or timezone.localdate()
        month_start = today.replace(day=1)

        oi_qs = OpenItem.objects.select_related("party", "project").filter(
            company=company, hub_side=OpenItem.HubSide.RECEIVABLE
        ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.WRITTEN_OFF, OpenItem.Status.REVERSED])
        if project_id:
            oi_qs = oi_qs.filter(project_id=project_id)
        if customer_id:
            oi_qs = oi_qs.filter(party_id=customer_id)

        debit_items = [x for x in oi_qs if not x.is_unallocated_credit]
        credit_items = [x for x in oi_qs if x.is_unallocated_credit]

        total_rec = sum((x.remaining_amount for x in debit_items), Decimal("0.00"))
        overdue_rec = sum((x.remaining_amount for x in debit_items if x.due_date < today), Decimal("0.00"))
        current_due = max(total_rec - overdue_rec, Decimal("0.00"))
        disputed_rec = sum((x.remaining_amount for x in debit_items if x.status == OpenItem.Status.DISPUTED), Decimal("0.00"))
        undisputed_rec = max(total_rec - disputed_rec, Decimal("0.00"))
        unalloc_cash = sum((x.remaining_amount for x in credit_items), Decimal("0.00"))

        adv_qs = AdvanceRecord.objects.filter(
            company=company, advance_type=AdvanceRecord.AdvanceType.CUSTOMER_ADVANCE
        ).exclude(status__in=[AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED])
        if customer_id:
            adv_qs = adv_qs.filter(party_id=customer_id)
        if project_id:
            adv_qs = adv_qs.filter(project_id=project_id)
        adv_total = sum((a.remaining_amount for a in adv_qs), Decimal("0.00"))

        ret_qs = RetentionSchedule.objects.filter(
            company=company, direction=RetentionSchedule.Direction.RECEIVABLE
        ).exclude(status=RetentionSchedule.Status.RELEASED)
        if customer_id:
            ret_qs = ret_qs.filter(party_id=customer_id)
        if project_id:
            ret_qs = ret_qs.filter(project_id=project_id)
        ret_total = Decimal("0.00")
        ret_eligible = Decimal("0.00")
        for r in ret_qs:
            rem = r.remaining_retention
            ret_total += rem
            if not r.is_disputed and r.release_due_date and r.release_due_date <= today:
                ret_eligible += rem

        # Pending certification RA bills (strictly non-GL!)
        pending_ra_qs = RABill.objects.filter(
            company=company, voucher__isnull=True
        ).exclude(status__in=[RABill.WorkflowStatus.CANCELLED, RABill.WorkflowStatus.REJECTED, RABill.WorkflowStatus.SUPERSEDED])
        if project_id:
            pending_ra_qs = pending_ra_qs.filter(project_id=project_id)
        if customer_id:
            pending_ra_qs = pending_ra_qs.filter(party_id=customer_id)
        pending_cert_val = sum((b.current_gross_amount for b in pending_ra_qs), Decimal("0.00"))

        # Unbilled measured BOQ work value
        boq_qs = ProjectBoqLine.objects.filter(project__company=company)
        if project_id:
            boq_qs = boq_qs.filter(project_id=project_id)
        unbilled_work = Decimal("0.00")
        for bl in boq_qs:
            unbilled_qty = max(bl.current_measured_qty - bl.previous_certified_qty, Decimal("0.000"))
            rate = bl.revised_rate if bl.revised_rate > 0 else bl.contract_rate
            unbilled_work += (unbilled_qty * rate).quantize(Decimal("0.01"))

        billed_month = (
            OpenItem.objects.filter(
                company=company, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False,
                document_date__gte=month_start, document_date__lte=today
            ).exclude(status=OpenItem.Status.REVERSED).aggregate(total=Sum("original_amount"))["total"]
            or Decimal("0.00")
        )
        collected_month = (
            OpenItem.objects.filter(
                company=company, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=True,
                document_date__gte=month_start, document_date__lte=today
            ).exclude(status=OpenItem.Status.REVERSED).aggregate(total=Sum("original_amount"))["total"]
            or Decimal("0.00")
        )

        analytics = AgingAnalysisService.compute_kpis_and_analytics(
            company=company, hub_side=OpenItem.HubSide.RECEIVABLE, end_date=today
        )
        dso_info = ARIntelligenceService.compute_dso_suite(company=company, as_of_date=today)

        commitments_7d = PaymentCommitment.objects.filter(
            company=company, status=PaymentCommitment.Status.PENDING, promised_date__gte=today, promised_date__lte=today + timedelta(days=7)
        ).count()
        bounced_cnt = ReceivedCheque.objects.filter(company=company, leaf__status="BOUNCED").count()
        followups = CollectionActivity.objects.filter(
            company=company, status__in=[CollectionActivity.Status.OPEN, CollectionActivity.Status.PROMISED, CollectionActivity.Status.ESCALATED]
        ).count()
        disputes_open = PartyDispute.objects.filter(
            company=company, hub_side=PartyDispute.HubSide.RECEIVABLE
        ).exclude(status=PartyDispute.Status.RESOLVED).count()
        cust_count = Party.objects.filter(company=company, party_type=Party.PartyType.CUSTOMER, is_active=True).count()

        # Risk Alerts & Top Risk Customers
        risk_watch = []
        for p in Party.objects.filter(company=company, party_type=Party.PartyType.CUSTOMER, is_active=True)[:25]:
            rs = ARIntelligenceService.compute_customer_risk_score(company=company, party=p, as_of_date=today)
            if rs["score"] >= 20:
                risk_watch.append(rs)
        risk_watch.sort(key=lambda x: x["score"], reverse=True)

        # Chart Datasets (Monthly series & RA certification series)
        monthly_series = []
        for i in range(5, -1, -1):
            m_ref = (today.replace(day=1) - timedelta(days=28 * i)).replace(day=1)
            next_m = (m_ref + timedelta(days=32)).replace(day=1)
            m_end = min(next_m - timedelta(days=1), today)
            b_amt = OpenItem.objects.filter(
                company=company, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False,
                document_date__gte=m_ref, document_date__lte=m_end
            ).aggregate(s=Sum("original_amount"))["s"] or Decimal("0.00")
            c_amt = OpenItem.objects.filter(
                company=company, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=True,
                document_date__gte=m_ref, document_date__lte=m_end
            ).aggregate(s=Sum("original_amount"))["s"] or Decimal("0.00")
            ra_pend = RABill.objects.filter(
                company=company, voucher__isnull=True, bill_date__gte=m_ref, bill_date__lte=m_end
            ).aggregate(s=Sum("current_gross_amount"))["s"] or Decimal("0.00")
            monthly_series.append({
                "month": m_ref.strftime("%Y-%m"),
                "billed": float(b_amt),
                "collected": float(c_amt),
                "ra_pending_cert": float(ra_pend),
            })

        return {
            "kpis": {
                "total_customers": cust_count,
                "total_receivables": str(total_rec),
                "overdue_receivables": str(overdue_rec),
                "current_not_due": str(current_due),
                "disputed_receivables": str(disputed_rec),
                "undisputed_receivables": str(undisputed_rec),
                "unallocated_receipts": str(unalloc_cash),
                "customer_advances": str(adv_total),
                "retention_receivable": str(ret_total),
                "retention_eligible": str(ret_eligible),
                "unbilled_work": str(unbilled_work),
                "ra_pending_certification": str(pending_cert_val),
                "billed_this_month": str(billed_month),
                "collected_this_month": str(collected_month),
                "dso_days": dso_info["current_period"]["dso_days"],
                "dso_methodology": dso_info["methodology"],
                "collection_efficiency_pct": analytics["ratios"]["collection_efficiency_pct"],
                "collection_followups": followups,
                "open_disputes": disputes_open,
                "commitments_due_7d": commitments_7d,
                "bounced_cheques": bounced_cnt,
            },
            "aging": analytics["aging"],
            "top_customers": analytics["top_parties"],
            "by_project": analytics["by_project"],
            "monthly_series": monthly_series,
            "risk_watchlist": risk_watch[:8],
            "dso_summary": dso_info["current_period"],
        }

    @staticmethod
    def compute_control_reconciliation(*, company, as_of_date: date | None = None) -> dict:
        today = as_of_date or timezone.localdate()
        accs = resolve_ar_accounts(company)

        def _gl_balance(acc: Account | None, normal_debit: bool = True) -> Decimal:
            if not acc:
                return Decimal("0.00")
            agg = LedgerEntry.objects.filter(
                company=company, account=acc, posting_date__lte=today
            ).aggregate(dr=Sum("debit"), cr=Sum("credit"))
            dr = agg["dr"] or Decimal("0.00")
            cr = agg["cr"] or Decimal("0.00")
            return (dr - cr) if normal_debit else (cr - dr)

        # 1. Trade Debtors Control: OpenItem net (Open Debits - Open Unallocated Credits) vs Debtors GL
        open_debits = sum(
            (oi.remaining_amount for oi in OpenItem.objects.filter(
                company=company, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False, document_date__lte=today
            ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.WRITTEN_OFF, OpenItem.Status.REVERSED])),
            Decimal("0.00"),
        )
        open_credits = sum(
            (oi.remaining_amount for oi in OpenItem.objects.filter(
                company=company, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=True, document_date__lte=today
            ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.REVERSED])),
            Decimal("0.00"),
        )
        debtors_subledger = open_debits - open_credits
        debtors_gl = _gl_balance(accs["debtors"], normal_debit=True)

        # 2. Customer Advances Liability vs GL
        adv_subledger = sum(
            (a.remaining_amount for a in AdvanceRecord.objects.filter(
                company=company, advance_type=AdvanceRecord.AdvanceType.CUSTOMER_ADVANCE, issue_date__lte=today
            ).exclude(status__in=[AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED])),
            Decimal("0.00"),
        )
        adv_gl = _gl_balance(accs["advance"], normal_debit=False)

        # 3. Retention Receivable vs GL
        ret_subledger = sum(
            (r.remaining_retention for r in RetentionSchedule.objects.filter(
                company=company, direction=RetentionSchedule.Direction.RECEIVABLE, hold_date__lte=today
            ).exclude(status=RetentionSchedule.Status.RELEASED)),
            Decimal("0.00"),
        )
        ret_gl = _gl_balance(accs["retention"], normal_debit=True)

        # 4. TDS Receivable GL (note: subledger derives from posted RA/Invoices/TDS Certs)
        tds_gl = _gl_balance(accs["tds"], normal_debit=True) if accs["tds"] and accs["tds"].id != (accs["debtors"].id if accs["debtors"] else None) else Decimal("0.00")

        rows = [
            {
                "control_role": "SUNDRY_DEBTORS",
                "label": "Trade Debtors Control (Open Items Net of Unallocated Receipts)",
                "account_code": accs["debtors"].code if accs["debtors"] else "-",
                "account_name": accs["debtors"].name if accs["debtors"] else "Not Configured",
                "gl_balance": str(debtors_gl),
                "subledger_balance": str(debtors_subledger),
                "variance": str(debtors_gl - debtors_subledger),
                "is_reconciled": debtors_gl == debtors_subledger,
            },
            {
                "control_role": "CUSTOMER_ADVANCE",
                "label": "Customer & Mobilization Advances Liability",
                "account_code": accs["advance"].code if accs["advance"] else "-",
                "account_name": accs["advance"].name if accs["advance"] else "Not Configured",
                "gl_balance": str(adv_gl),
                "subledger_balance": str(adv_subledger),
                "variance": str(adv_gl - adv_subledger),
                "is_reconciled": adv_gl == adv_subledger,
            },
            {
                "control_role": "RETENTION_RECEIVABLE",
                "label": "Client Retention Receivable",
                "account_code": accs["retention"].code if accs["retention"] else "-",
                "account_name": accs["retention"].name if accs["retention"] else "Not Configured",
                "gl_balance": str(ret_gl),
                "subledger_balance": str(ret_subledger),
                "variance": str(ret_gl - ret_subledger),
                "is_reconciled": ret_gl == ret_subledger,
            },
        ]
        if accs["tds"] and accs["tds"].control_role == Account.ControlRole.TDS_RECEIVABLE:
            rows.append({
                "control_role": "TDS_RECEIVABLE",
                "label": "Withholding Tax (TDS) Receivable",
                "account_code": accs["tds"].code,
                "account_name": accs["tds"].name,
                "gl_balance": str(tds_gl),
                "subledger_balance": str(tds_gl),
                "variance": "0.00",
                "is_reconciled": True,
            })

        return {
            "as_of_date": today.isoformat(),
            "is_fully_reconciled": all(r["is_reconciled"] for r in rows),
            "controls": rows,
        }
