from collections import defaultdict
from datetime import timedelta
from decimal import Decimal
from django.db.models import Sum
from django.utils import timezone

from apps.accounting.models import Account, LedgerEntry, PartyLedgerEntry
from apps.banking.models import (
    BankAccount,
    BankStatementLine,
    CashAccount,
    CashCountReconciliation,
    CashTransfer,
    ChequeLeaf,
    ImprestAdvance,
)
from apps.banking.services import BankingService
from apps.loans.models import (
    BankFacility,
    BankGuarantee,
    LoanCollateral,
    LoanInterestAccrual,
    LoanRepayment,
    LoanScheduleInstallment,
)
from apps.loans.services import LoanService


class TreasuryAnalyticsService:
    @staticmethod
    def get_executive_dashboard(*, company) -> dict:
        today = timezone.localdate()
        month_start = today.replace(day=1)
        next_30 = today + timedelta(days=30)

        # 1. Bank Balances & Bank Summary
        bank_accounts = BankAccount.objects.select_related("bank_branch__bank", "gl_account", "project").filter(
            company=company
        ).exclude(status=BankAccount.Status.CLOSED)
        bank_rows = []
        total_bank_npr = Decimal("0.00")
        fx_assets = defaultdict(lambda: Decimal("0.00"))
        fx_liabilities = defaultdict(lambda: Decimal("0.00"))

        for ba in bank_accounts:
            book_bal = BankingService.get_gl_balance(ba.gl_account)
            uncleared = ChequeLeaf.objects.filter(
                bank_account=ba,
                direction=ChequeLeaf.Direction.ISSUED,
                status__in=[ChequeLeaf.Status.ISSUED, ChequeLeaf.Status.PRESENTED],
            ).aggregate(s=Sum("amount"))["s"] or Decimal("0.00")
            avail_bal = book_bal - uncleared
            total_bank_npr += book_bal
            if ba.currency != company.base_currency:
                fx_assets[ba.currency] += book_bal
            bank_rows.append(
                {
                    "id": str(ba.id),
                    "account_code": ba.account_code,
                    "name": ba.account_name,
                    "bank": ba.bank_branch.bank.short_code,
                    "masked": ba.account_number_masked,
                    "account_type": ba.account_type,
                    "currency": ba.currency,
                    "book_balance": str(book_bal),
                    "available_balance": str(avail_bal),
                    "status": ba.status,
                }
            )

        # 2. Cash & Custody Summary + Daily Cash Movement
        cash_accounts = CashAccount.objects.select_related("gl_account", "custodian", "project").filter(
            company=company, is_active=True
        )
        cash_rows = []
        total_cash = Decimal("0.00")
        employee_custody = defaultdict(lambda: Decimal("0.00"))
        daily_opening = Decimal("0.00")
        daily_receipts = Decimal("0.00")
        daily_payments = Decimal("0.00")
        for ca in cash_accounts:
            bal = BankingService.get_gl_balance(ca.gl_account)
            total_cash += bal
            open_bal = BankingService.get_gl_balance(ca.gl_account, as_of=today - timedelta(days=1))
            daily_opening += open_bal
            day_agg = LedgerEntry.objects.filter(account=ca.gl_account, posting_date=today).aggregate(
                d=Sum("base_debit"), c=Sum("base_credit")
            )
            daily_receipts += day_agg["d"] or Decimal("0.00")
            daily_payments += day_agg["c"] or Decimal("0.00")
            if ca.custodian:
                employee_custody[ca.custodian.username] += bal
            cash_rows.append(
                {
                    "id": str(ca.id),
                    "code": ca.code,
                    "name": ca.name,
                    "cash_type": ca.cash_type,
                    "custodian": ca.custodian.username if ca.custodian else "Unassigned",
                    "balance": str(bal),
                }
            )

        unsettled_imprests = sum(
            (i.outstanding_balance for i in ImprestAdvance.objects.filter(company=company).exclude(status=ImprestAdvance.Status.SETTLED)),
            Decimal("0.00"),
        )
        shortage_total = (
            CashCountReconciliation.objects.filter(company=company, status=CashCountReconciliation.Status.PENDING).aggregate(s=Sum("variance"))["s"]
            or Decimal("0.00")
        )

        # 3. Cheque Monitoring
        issued_out = ChequeLeaf.objects.filter(
            company=company,
            direction=ChequeLeaf.Direction.ISSUED,
            status__in=[ChequeLeaf.Status.ISSUED, ChequeLeaf.Status.PRESENTED],
        )
        received_pending = ChequeLeaf.objects.filter(
            company=company,
            direction=ChequeLeaf.Direction.RECEIVED,
            status__in=[ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.DEPOSITED, ChequeLeaf.Status.UNDER_CLEARING],
        )
        cheque_monitoring = {
            "issued_outstanding_count": issued_out.count(),
            "issued_outstanding_amount": str(issued_out.aggregate(s=Sum("amount"))["s"] or Decimal("0.00")),
            "received_clearing_count": received_pending.count(),
            "received_clearing_amount": str(received_pending.aggregate(s=Sum("amount"))["s"] or Decimal("0.00")),
            "bounced_count": ChequeLeaf.objects.filter(company=company, status=ChequeLeaf.Status.BOUNCED).count(),
            "cleared_count": ChequeLeaf.objects.filter(company=company, status=ChequeLeaf.Status.CLEARED).count(),
        }

        # 4. Reconciliation Status
        stmt_matched = BankStatementLine.objects.filter(
            company=company, match_status__in=[BankStatementLine.MatchStatus.MATCHED, BankStatementLine.MatchStatus.FINALIZED]
        ).count()
        stmt_unmatched = BankStatementLine.objects.filter(
            company=company, match_status__in=[BankStatementLine.MatchStatus.UNMATCHED, BankStatementLine.MatchStatus.UNDER_REVIEW]
        ).count()

        # 5. Loans, OD/CC Utilization & Interest Monitoring
        facilities = BankFacility.objects.select_related("bank_account__bank_branch__bank").filter(
            company=company
        ).exclude(status=BankFacility.Status.CLOSED)
        total_loan_out = Decimal("0.00")
        total_sanctioned = Decimal("0.00")
        od_cc_limit = Decimal("0.00")
        od_cc_used = Decimal("0.00")
        loan_exposure_rows = []
        maturity_calendar = []
        by_type = defaultdict(lambda: Decimal("0.00"))

        for fac in facilities:
            out = LoanService.get_outstanding_principal(fac)
            total_loan_out += out
            total_sanctioned += fac.sanctioned_limit
            by_type[fac.facility_type] += out
            if fac.currency != company.base_currency:
                fx_liabilities[fac.currency] += out
            eff_limit = fac.sanctioned_limit
            if fac.facility_type == BankFacility.FacilityType.CASH_CREDIT:
                dp = fac.dp_assessments.order_by("-assessment_date").first()
                if dp:
                    eff_limit = dp.effective_limit
            if fac.facility_type in (BankFacility.FacilityType.OVERDRAFT, BankFacility.FacilityType.CASH_CREDIT):
                od_cc_limit += eff_limit
                od_cc_used += out
            loan_exposure_rows.append(
                {
                    "id": str(fac.id),
                    "code": fac.facility_code,
                    "name": fac.facility_name,
                    "bank": fac.bank_account.bank_branch.bank.short_code,
                    "type": fac.facility_type,
                    "sanctioned_limit": str(eff_limit),
                    "outstanding": str(out),
                    "available_limit": str(max(eff_limit - out, Decimal("0.00"))),
                    "effective_rate": str(fac.effective_interest_rate),
                    "maturity_date": fac.maturity_date.isoformat(),
                    "renewal_date": fac.renewal_date.isoformat() if fac.renewal_date else None,
                }
            )
            maturity_calendar.append(
                {
                    "id": str(fac.id),
                    "code": fac.facility_code,
                    "name": fac.facility_name,
                    "type": fac.facility_type,
                    "maturity_date": fac.maturity_date.isoformat(),
                    "renewal_date": fac.renewal_date.isoformat() if fac.renewal_date else None,
                    "outstanding": str(out),
                }
            )

        upcoming_inst_qs = LoanScheduleInstallment.objects.select_related("facility").filter(
            facility__company=company,
            status__in=[LoanScheduleInstallment.Status.PENDING, LoanScheduleInstallment.Status.PARTIAL],
            due_date__range=(today, next_30),
        ).order_by("due_date")
        upcoming_installments_30d = sum(
            ((i.principal_due - i.principal_paid) + (i.interest_due - i.interest_paid) for i in upcoming_inst_qs),
            Decimal("0.00"),
        )

        accrued_interest = LoanInterestAccrual.objects.filter(
            company=company, status=LoanInterestAccrual.Status.ACCRUED
        ).aggregate(s=Sum("system_calculated_interest"))["s"] or Decimal("0.00")
        paid_interest = LoanRepayment.objects.filter(facility__company=company).aggregate(
            s=Sum("interest_amount")
        )["s"] or Decimal("0.00")

        # 6. Monthly Bank Charges & FX Exposure (including AR/AP)
        monthly_bank_charges = LedgerEntry.objects.filter(
            company=company, account__code="5230", posting_date__gte=month_start
        ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        charges_net = (monthly_bank_charges["d"] or Decimal("0.00")) - (monthly_bank_charges["c"] or Decimal("0.00"))

        fc_ar_ap = (
            LedgerEntry.objects.filter(company=company)
            .exclude(transaction_currency=company.base_currency)
            .values("transaction_currency", "account__control_role")
            .annotate(d=Sum("debit"), c=Sum("credit"))
        )
        for row in fc_ar_ap:
            net = (row["d"] or Decimal("0.00")) - (row["c"] or Decimal("0.00"))
            if row["account__control_role"] == Account.ControlRole.SUNDRY_DEBTORS:
                fx_assets[row["transaction_currency"]] += net
            elif row["account__control_role"] == Account.ControlRole.SUNDRY_CREDITORS:
                fx_liabilities[row["transaction_currency"]] += abs(net)

        all_fx_currencies = sorted(set(fx_assets.keys()) | set(fx_liabilities.keys()))
        fx_exposure = [
            {
                "currency": cur,
                "assets": str(fx_assets[cur]),
                "liabilities": str(fx_liabilities[cur]),
                "net_exposure": str(fx_assets[cur] - fx_liabilities[cur]),
            }
            for cur in all_fx_currencies
        ]

        # 7. Treasury 30-day Cash Flow Forecast (AR expected inflows vs upcoming Loan + Issued Cheque outflows)
        expected_inflows = (
            PartyLedgerEntry.objects.filter(company=company, due_date__range=(today, next_30))
            .aggregate(d=Sum("debit"))["d"]
            or Decimal("0.00")
        ) + Decimal(cheque_monitoring["received_clearing_amount"])
        expected_outflows = upcoming_installments_30d + Decimal(cheque_monitoring["issued_outstanding_amount"])

        active_bgs = BankGuarantee.objects.select_related("project", "bank_account__bank_branch__bank").filter(
            company=company,
            status__in=[BankGuarantee.Status.ACTIVE, BankGuarantee.Status.EXTENDED, BankGuarantee.Status.AMENDED, BankGuarantee.Status.ISSUED],
        )
        bg_exposure = sum((b.amount for b in active_bgs), Decimal("0.00"))
        bg_margin_blocked = sum((b.margin_amount for b in active_bgs), Decimal("0.00"))
        next_60 = today + timedelta(days=60)
        bg_exp_30 = active_bgs.filter(expiry_date__range=(today, next_30)).count()
        bg_exp_60 = active_bgs.filter(expiry_date__range=(today, next_60)).count()
        bg_awaiting_release = BankGuarantee.objects.filter(
            company=company,
            expiry_date__lt=today,
            status__in=[BankGuarantee.Status.ACTIVE, BankGuarantee.Status.EXTENDED, BankGuarantee.Status.AMENDED, BankGuarantee.Status.EXPIRED_AWAITING_RELEASE],
        ).count()
        bg_by_type = defaultdict(lambda: Decimal("0.00"))
        bank_exposure = defaultdict(lambda: Decimal("0.00"))
        project_exposure = defaultdict(lambda: Decimal("0.00"))
        for b in active_bgs:
            bg_by_type[b.bg_type] += b.amount
            bank_exposure[b.bank_account.bank_branch.bank.short_code] += b.amount
            if b.project:
                project_exposure[b.project.code] += b.amount
        for fac in facilities:
            out_f = LoanService.get_outstanding_principal(fac)
            bank_exposure[fac.bank_account.bank_branch.bank.short_code] += out_f
            if fac.project:
                project_exposure[fac.project.code] += out_f

        active_cols = LoanCollateral.objects.filter(company=company, is_released=False).prefetch_related("allocations")
        collateral_cov = sum((c.assessed_value for c in active_cols), Decimal("0.00"))
        collateral_encumbered = sum(
            (sum((l.allocated_value for l in c.allocations.filter(is_released=False)), Decimal("0.00")) for c in active_cols),
            Decimal("0.00"),
        )
        overdue_installments_amt = sum(
            (
                (i.principal_due - i.principal_paid) + (i.interest_due - i.interest_paid)
                for i in LoanScheduleInstallment.objects.filter(
                    facility__company=company,
                    status__in=[LoanScheduleInstallment.Status.PENDING, LoanScheduleInstallment.Status.PARTIAL, LoanScheduleInstallment.Status.OVERDUE],
                    due_date__lt=today,
                )
            ),
            Decimal("0.00"),
        )
        alerts = TreasuryAnalyticsService.evaluate_alerts(company=company)

        # Monthly Cashflow Inflow vs Outflow (last 6 months posted bank/cash ledger)
        monthly_cashflow = []
        for m_offset in range(5, -1, -1):
            ref_d = (today.replace(day=1) - timedelta(days=m_offset * 28)).replace(day=1)
            next_m = (ref_d + timedelta(days=32)).replace(day=1)
            agg_cf = LedgerEntry.objects.filter(
                company=company,
                account__control_role__in=["BANK", "CASH"],
                posting_date__gte=ref_d,
                posting_date__lt=next_m,
            ).aggregate(inflow=Sum("base_debit"), outflow=Sum("base_credit"))
            monthly_cashflow.append({
                "month": ref_d.strftime("%Y-%m"),
                "inflow": float(agg_cf["inflow"] or 0),
                "outflow": float(agg_cf["outflow"] or 0),
            })

        return {
            "kpis": {
                "total_cash_position": str(total_cash),
                "total_bank_balances": str(total_bank_npr),
                "total_available_funds": str((total_cash + total_bank_npr) - bg_margin_blocked),
                "restricted_cash_margin": str(bg_margin_blocked),
                "total_loan_outstanding": str(total_loan_out),
                "total_sanctioned_facilities": str(total_sanctioned),
                "available_od_cc_limit": str(max(od_cc_limit - od_cc_used, Decimal("0.00"))),
                "upcoming_installments_30d": str(upcoming_installments_30d),
                "overdue_installments": str(overdue_installments_amt),
                "unreconciled_transactions": stmt_unmatched,
                "monthly_bank_charges": str(charges_net),
                "bg_exposure": str(bg_exposure),
                "bg_active_count": active_bgs.count(),
                "bg_expiring_30d": bg_exp_30,
                "bg_expiring_60d": bg_exp_60,
                "bg_awaiting_release": bg_awaiting_release,
                "collateral_coverage": str(collateral_cov),
                "collateral_encumbered": str(collateral_encumbered),
            },
            "bank_balance_summary": bank_rows,
            "daily_cash_movement": {
                "date": today.isoformat(),
                "opening": str(daily_opening),
                "receipts": str(daily_receipts),
                "payments": str(daily_payments),
                "closing": str(total_cash),
                "unsettled_imprest": str(unsettled_imprests),
                "pending_count_variance": str(shortage_total),
            },
            "cash_custody": [
                {"custodian": k, "amount": str(v)} for k, v in sorted(employee_custody.items())
            ],
            "cash_accounts": cash_rows,
            "cheque_monitoring": cheque_monitoring,
            "reconciliation_summary": {
                "matched": stmt_matched,
                "unmatched": stmt_unmatched,
                "total_bank_accounts": len(bank_rows),
            },
            "fx_exposure": fx_exposure,
            "loan_exposure": loan_exposure_rows,
            "loan_portfolio_breakdown": [
                {"facility_type": k, "outstanding": str(v)} for k, v in sorted(by_type.items())
            ],
            "bg_breakdown": [{"bg_type": k, "exposure": str(v)} for k, v in sorted(bg_by_type.items())],
            "bank_wise_exposure": [{"bank": k, "exposure": float(v)} for k, v in sorted(bank_exposure.items())],
            "project_wise_exposure": [{"project": k, "exposure": float(v)} for k, v in sorted(project_exposure.items())],
            "monthly_cashflow": monthly_cashflow,
            "alerts": alerts,
            "od_utilization": {
                "sanctioned_limit": str(od_cc_limit),
                "utilized": str(od_cc_used),
                "available": str(max(od_cc_limit - od_cc_used, Decimal("0.00"))),
                "utilization_pct": str(
                    ((od_cc_used / od_cc_limit) * Decimal("100")).quantize(Decimal("0.01"))
                    if od_cc_limit > 0
                    else Decimal("0.00")
                ),
            },
            "interest_monitoring": {
                "accrued_unsettled": str(accrued_interest),
                "paid_total": str(paid_interest),
            },
            "maturity_calendar": maturity_calendar,
            "upcoming_installments": [
                {
                    "facility_code": i.facility.facility_code,
                    "due_date": i.due_date.isoformat(),
                    "principal_due": str(i.principal_due),
                    "interest_due": str(i.interest_due),
                }
                for i in upcoming_inst_qs[:10]
            ],
            "treasury_forecast": {
                "window_days": 30,
                "expected_receipts": str(expected_inflows),
                "expected_payments": str(expected_outflows),
                "net_projected_cash_flow": str(expected_inflows - expected_outflows),
            },
        }

    @staticmethod
    def evaluate_alerts(*, company) -> list[dict]:
        """Dynamic 17-rule executive treasury risk & compliance alert detector."""
        today = timezone.localdate()
        alerts: list[dict] = []

        # 1. Negative bank book balance & BRS diff
        for ba in BankAccount.objects.filter(company=company).exclude(status=BankAccount.Status.CLOSED).select_related("gl_account"):
            bal = BankingService.get_gl_balance(ba.gl_account)
            if bal < 0:
                alerts.append({
                    "alert_code": "NEGATIVE_BANK_BALANCE",
                    "severity": "CRITICAL",
                    "title": f"Negative Book Balance: {ba.account_name}",
                    "message": f"GL balance is {bal} {ba.currency}.",
                    "entity_type": "BankAccount",
                    "entity_id": str(ba.id),
                    "route_key": "banking:accounts",
                })
        unmatched_lines = BankStatementLine.objects.filter(
            company=company, match_status__in=[BankStatementLine.MatchStatus.UNMATCHED, BankStatementLine.MatchStatus.UNDER_REVIEW]
        ).count()
        if unmatched_lines > 0:
            alerts.append({
                "alert_code": "BRS_DIFFERENCE",
                "severity": "WARNING",
                "title": f"{unmatched_lines} Unreconciled Bank Statement Line(s)",
                "message": "Bank statement transactions require matching against book entries.",
                "entity_type": "BankReconciliation",
                "entity_id": "",
                "route_key": "banking:reconciliation",
            })

        # 2. Overdue loan installments & upcoming 7d due
        for inst in LoanScheduleInstallment.objects.filter(
            facility__company=company,
            status__in=[LoanScheduleInstallment.Status.PENDING, LoanScheduleInstallment.Status.PARTIAL, LoanScheduleInstallment.Status.OVERDUE],
            due_date__lte=today + timedelta(days=7),
        ).select_related("facility")[:20]:
            is_ov = inst.due_date < today
            alerts.append({
                "alert_code": "LOAN_INSTALLMENT_OVERDUE" if is_ov else "LOAN_INSTALLMENT_DUE",
                "severity": "CRITICAL" if is_ov else "WARNING",
                "title": f"{'Overdue' if is_ov else 'Upcoming'} Installment: {inst.facility.facility_code}",
                "message": f"Installment #{inst.installment_no} due {inst.due_date}.",
                "entity_type": "BankFacility",
                "entity_id": str(inst.facility_id),
                "route_key": "loans:dashboard",
            })

        # 3. OD/CC excess utilization, renewal approaching, DP overdue, facility maturity
        for fac in BankFacility.objects.filter(company=company).exclude(status=BankFacility.Status.CLOSED):
            out = LoanService.get_outstanding_principal(fac)
            eff = LoanService._effective_limit(fac)
            if out > eff:
                alerts.append({
                    "alert_code": "SANCTION_OR_DP_EXCEEDED",
                    "severity": "CRITICAL",
                    "title": f"Limit Exceeded: {fac.facility_code}",
                    "message": f"Utilized {out} exceeds effective limit {eff}.",
                    "entity_type": "BankFacility",
                    "entity_id": str(fac.id),
                    "route_key": "loans:dashboard",
                })
            if fac.renewal_date and fac.renewal_date <= today + timedelta(days=30):
                alerts.append({
                    "alert_code": "FACILITY_RENEWAL_DUE",
                    "severity": "WARNING",
                    "title": f"Facility Renewal Due: {fac.facility_code}",
                    "message": f"Renewal date is {fac.renewal_date}.",
                    "entity_type": "BankFacility",
                    "entity_id": str(fac.id),
                    "route_key": "loans:dashboard",
                })
            if fac.maturity_date <= today + timedelta(days=30):
                alerts.append({
                    "alert_code": "LOAN_MATURITY_APPROACHING",
                    "severity": "WARNING",
                    "title": f"Loan Maturity Approaching: {fac.facility_code}",
                    "message": f"Matures on {fac.maturity_date}.",
                    "entity_type": "BankFacility",
                    "entity_id": str(fac.id),
                    "route_key": "loans:dashboard",
                })

        # 4. BG expiry (90/60/30/15/7d), claim window, & expired awaiting formal release
        for bg in BankGuarantee.objects.filter(company=company).exclude(status__in=[BankGuarantee.Status.RELEASED, BankGuarantee.Status.REVOKED]):
            if bg.expiry_date < today and bg.status != BankGuarantee.Status.INVOKED:
                alerts.append({
                    "alert_code": "BG_EXPIRED_AWAITING_RELEASE",
                    "severity": "CRITICAL",
                    "title": f"Expired BG Awaiting Formal Release: {bg.bg_number}",
                    "message": f"Expired on {bg.expiry_date}; cash margin {bg.margin_amount} still blocked.",
                    "entity_type": "BankGuarantee",
                    "entity_id": str(bg.id),
                    "route_key": "loans:guarantees",
                })
            elif bg.expiry_date <= today + timedelta(days=30):
                alerts.append({
                    "alert_code": "BG_EXPIRY_SOON",
                    "severity": "WARNING",
                    "title": f"BG Expiring Soon ({bg.expiry_date}): {bg.bg_number}",
                    "message": f"{bg.beneficiary} · {bg.currency} {bg.amount}.",
                    "entity_type": "BankGuarantee",
                    "entity_id": str(bg.id),
                    "route_key": "loans:guarantees",
                })
            if bg.claim_expiry_date and today <= bg.claim_expiry_date <= today + timedelta(days=15):
                alerts.append({
                    "alert_code": "BG_CLAIM_WINDOW",
                    "severity": "WARNING",
                    "title": f"BG Claim Period Ending: {bg.bg_number}",
                    "message": f"Claim period ends {bg.claim_expiry_date}.",
                    "entity_type": "BankGuarantee",
                    "entity_id": str(bg.id),
                    "route_key": "loans:guarantees",
                })

        # 5. Collateral valuation or insurance expiry
        for col in LoanCollateral.objects.filter(company=company, is_released=False):
            if col.insurance_expiry and col.insurance_expiry <= today + timedelta(days=30):
                alerts.append({
                    "alert_code": "COLLATERAL_INSURANCE_EXPIRY",
                    "severity": "CRITICAL" if col.insurance_expiry < today else "WARNING",
                    "title": f"Collateral Insurance Expiry: {col.description[:50]}",
                    "message": f"Policy {col.insurance_policy_no} expires {col.insurance_expiry}.",
                    "entity_type": "LoanCollateral",
                    "entity_id": str(col.id),
                    "route_key": "loans:dashboard",
                })
            if col.next_valuation_date and col.next_valuation_date <= today:
                alerts.append({
                    "alert_code": "COLLATERAL_VALUATION_EXPIRED",
                    "severity": "WARNING",
                    "title": f"Collateral Revaluation Due: {col.description[:50]}",
                    "message": f"Next valuation date {col.next_valuation_date} reached.",
                    "entity_type": "LoanCollateral",
                    "entity_id": str(col.id),
                    "route_key": "loans:dashboard",
                })
        return alerts

