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

from apps.accounting.models import Account, LedgerEntry, Voucher
from apps.banking.security import encrypt_account_number, mask_account_number
from apps.banking.services import _post_system_voucher, BankingService
from apps.audit.services import record_audit_event
from apps.treasury.models import record_treasury_audit
from .calculators import calculate_period_interest, generate_repayment_schedule, simulate_daily_interest
from .models import (
    BankFacility,
    BankGuarantee,
    CollateralRelease,
    CollateralValuation,
    DailyFacilityBalance,
    DrawingPowerAssessment,
    DrawingPowerConfig,
    FacilityCollateralLink,
    FacilityRateVersion,
    GuaranteeAmendment,
    GuaranteeClaim,
    GuaranteeExtension,
    GuaranteeRelease,
    InterestCalculationRun,
    InterestDailyDetail,
    LoanCollateral,
    LoanDisbursement,
    LoanFacilityAmendment,
    LoanInterestAccrual,
    LoanRateRevision,
    LoanRepayment,
    LoanScheduleInstallment,
    NrbRegulatoryConfig,
    ODCreditTransaction,
    RevolvingProductConfig,
)


class LoanService:
    @staticmethod
    def get_active_nrb_config(company, as_of: date) -> NrbRegulatoryConfig | None:
        return (
            NrbRegulatoryConfig.objects.filter(
                company=company, is_active=True, effective_from__lte=as_of
            )
            .filter(Q(effective_to__isnull=True) | Q(effective_to__gte=as_of))
            .order_by("-effective_from")
            .first()
        )

    @staticmethod
    def get_outstanding_principal(facility: BankFacility) -> Decimal:
        agg = LedgerEntry.objects.filter(account=facility.linked_liability_account).aggregate(
            d=Sum("base_debit"), c=Sum("base_credit")
        )
        return (
            (facility.linked_liability_account.opening_credit - facility.linked_liability_account.opening_debit)
            + ((agg["c"] or Decimal("0.00")) - (agg["d"] or Decimal("0.00")))
        )

    @staticmethod
    @transaction.atomic
    def create_facility(*, company, user, data: dict) -> BankFacility:
        bank_account = data["bank_account"]
        sdate = data["sanction_date"]
        limit_amt = data["sanctioned_limit"]

        # Validate against active NRB directive if OD limit ceiling applies
        nrb = LoanService.get_active_nrb_config(company, sdate)
        if nrb and data["facility_type"] == BankFacility.FacilityType.OVERDRAFT:
            if limit_amt > nrb.od_max_limit_npr and data.get("currency", "NPR") == "NPR":
                raise ValidationError(
                    f"NRB directive {nrb.directive_code} caps Overdraft limit at NPR {nrb.od_max_limit_npr}."
                )

        liab_acc = data.get("linked_liability_account")
        if not liab_acc:
            liab_grp, _ = Account.objects.get_or_create(
                company=company,
                code="2000",
                defaults={"name": "Liabilities", "account_type": Account.AccountType.LIABILITY, "is_group": True},
            )
            existing = set(Account.objects.filter(company=company, code__startswith="23").values_list("code", flat=True))
            code = next(f"23{n:02d}" for n in range(1, 999) if f"23{n:02d}" not in existing)
            liab_acc = Account.objects.create(
                company=company,
                parent=liab_grp,
                code=code,
                name=f"Loan Liability — {data['facility_name']}",
                account_type=Account.AccountType.LIABILITY,
                nfrs_mapping="NFRS 09",
            )

        int_acc = data.get("linked_interest_account")
        if not int_acc:
            int_acc, _ = Account.objects.get_or_create(
                company=company,
                code="5310",
                defaults={"name": "Bank Loan & OD Interest Expense", "account_type": Account.AccountType.EXPENSE, "nfrs_mapping": "NAS 23"},
            )

        accrued_acc = data.get("accrued_interest_account")
        if not accrued_acc:
            accrued_acc, _ = Account.objects.get_or_create(
                company=company,
                code="2350",
                defaults={"name": "Accrued Loan Interest Payable", "account_type": Account.AccountType.LIABILITY, "nfrs_mapping": "NFRS 09", "allow_direct_posting": True},
            )

        raw_acct_no = (data.get("loan_account_number") or "").strip()
        fac = BankFacility.objects.create(
            company=company,
            bank_account=bank_account,
            bank_branch=data.get("bank_branch") or bank_account.bank_branch,
            project=data.get("project"),
            facility_code=data["facility_code"],
            facility_name=data["facility_name"],
            facility_type=data["facility_type"],
            loan_account_number_masked=mask_account_number(raw_acct_no) if raw_acct_no else "",
            loan_account_number_encrypted=encrypt_account_number(raw_acct_no) if raw_acct_no else "",
            sanction_ref=data.get("sanction_ref", ""),
            sanction_date=sdate,
            agreement_date=data.get("agreement_date"),
            maturity_date=data["maturity_date"],
            renewal_date=data.get("renewal_date"),
            currency=data.get("currency", bank_account.currency),
            sanctioned_limit=limit_amt,
            interest_mode=data.get("interest_mode", BankFacility.InterestMode.FLOATING),
            base_rate=data.get("base_rate", nrb.published_base_rate if nrb else Decimal("8.50")),
            premium_rate=data.get("premium_rate", Decimal("2.00")),
            penal_rate=data.get("penal_rate", nrb.penal_interest_cap_pct if nrb else Decimal("2.00")),
            day_count_basis=data.get("day_count_basis", BankFacility.DayCountBasis.ACT_365),
            schedule_method=data.get("schedule_method", BankFacility.ScheduleMethod.EMI),
            repayment_frequency=data.get("repayment_frequency", BankFacility.Frequency.MONTHLY),
            tenure_months=data.get("tenure_months", 36),
            moratorium_months=data.get("moratorium_months", 0),
            allow_limit_excess_override=bool(data.get("allow_limit_excess_override", False)),
            linked_liability_account=liab_acc,
            linked_interest_account=int_acc,
            accrued_interest_account=accrued_acc,
        )
        eff_rate = fac.effective_interest_rate
        FacilityRateVersion.objects.create(
            company=company,
            facility=fac,
            version_code="R001",
            rate_kind=FacilityRateVersion.RateKind.NORMAL,
            rate_type=fac.interest_mode,
            rate_unit=FacilityRateVersion.RateUnit.MONTHLY if fac.day_count_basis == BankFacility.DayCountBasis.CONTRACT_MONTHLY else FacilityRateVersion.RateUnit.ANNUAL,
            benchmark_name="NRB Base Rate" if fac.interest_mode == BankFacility.InterestMode.FLOATING else "",
            benchmark_value=fac.base_rate,
            spread_pct=fac.premium_rate if fac.interest_mode == BankFacility.InterestMode.FLOATING else Decimal("0.0000"),
            effective_rate_pct=fac.monthly_contract_rate if (fac.day_count_basis == BankFacility.DayCountBasis.CONTRACT_MONTHLY and fac.monthly_contract_rate) else eff_rate,
            penal_rate_pct=fac.penal_rate,
            effective_from=sdate,
            effective_to=None,
            status=FacilityRateVersion.Status.CURRENT,
            reason="Initial sanction rate",
            created_by=user,
            approved_by=user,
        )
        op_amt = Decimal(str(data.get("opening_balance") or "0.00")).quantize(Decimal("0.01"))
        if op_amt > Decimal("0.00"):
            from apps.accounting.services.opening_balance_service import OpeningBalanceCreationService
            is_od_cc = fac.facility_type in (BankFacility.FacilityType.OVERDRAFT, BankFacility.FacilityType.CASH_CREDIT)
            OpeningBalanceCreationService.create_single_account_opening(
                company=company,
                user=user,
                account=fac.linked_liability_account,
                amount=op_amt,
                opening_date=data.get("opening_date") or sdate,
                direction=str(data.get("opening_direction") or "CR"),
                adjustment_account=data.get("adjustment_account"),
                project=fac.project,
                category="OD_CC" if is_od_cc else "LOANS",
                currency=fac.currency,
                source_entity_type="BankFacility",
                source_entity_id=str(fac.id),
                reference_no=fac.facility_code,
                narration=data.get("opening_narration") or f"Opening liability for {fac.facility_name} ({fac.facility_code})",
                override_reason=data.get("override_reason", ""),
                migration_override_reason=data.get("migration_override_reason", ""),
                auto_post=bool(data.get("auto_post_opening", True)),
            )

        record_treasury_audit(
            company=company,
            module="LOANS",
            action="LOAN_FACILITY_CREATED",
            entity_type="BankFacility",
            entity_id=str(fac.id),
            actor=user,
            new_state={"code": fac.facility_code, "type": fac.facility_type, "limit": str(fac.sanctioned_limit)},
        )
        return fac

    @staticmethod
    @transaction.atomic
    def disburse_loan(
        *,
        facility: BankFacility,
        user,
        disbursement_date: date,
        amount: Decimal,
        reference_no: str = "",
        rebuild_schedule: bool = True,
        limit_excess_exception: bool = False,
    ) -> LoanDisbursement:
        if amount <= 0:
            raise ValidationError("Disbursement amount must be positive.")
        current_out = LoanService.get_outstanding_principal(facility)
        eff_limit = facility.sanctioned_limit
        if facility.facility_type == BankFacility.FacilityType.CASH_CREDIT:
            latest_dp = facility.dp_assessments.order_by("-assessment_date").first()
            if latest_dp:
                eff_limit = latest_dp.effective_limit
        if current_out + amount > eff_limit and not (limit_excess_exception and facility.allow_limit_excess_override):
            raise ValidationError(f"Disbursement exceeds effective facility limit ({eff_limit}).")

        v = _post_system_voucher(
            company=facility.company,
            user=user,
            vtype=Voucher.VoucherType.RECEIPT,
            vdate=disbursement_date,
            project=facility.project,
            narration=f"Loan disbursement ({facility.facility_code} — {facility.facility_name})",
            lines_data=[
                {"account": facility.bank_account.gl_account, "debit": amount, "credit": Decimal("0.00"), "project": facility.project},
                {"account": facility.linked_liability_account, "debit": Decimal("0.00"), "credit": amount, "project": facility.project},
            ],
        )
        disb = LoanDisbursement.objects.create(
            facility=facility,
            disbursement_date=disbursement_date,
            amount=amount,
            reference_no=reference_no,
            voucher=v,
            created_by=user,
        )
        if not facility.first_disbursement_date:
            facility.first_disbursement_date = disbursement_date
            facility.save(update_fields=["first_disbursement_date"])

        if rebuild_schedule and facility.facility_type not in (
            BankFacility.FacilityType.OVERDRAFT,
            BankFacility.FacilityType.CASH_CREDIT,
            BankFacility.FacilityType.BANK_GUARANTEE,
        ):
            LoanService.rebuild_schedule(facility=facility, start_date=disbursement_date)
        return disb

    @staticmethod
    @transaction.atomic
    def rebuild_schedule(*, facility: BankFacility, start_date: date | None = None) -> list[LoanScheduleInstallment]:
        outstanding = LoanService.get_outstanding_principal(facility)
        if outstanding <= 0:
            outstanding = facility.sanctioned_limit
        facility.schedule.filter(status=LoanScheduleInstallment.Status.PENDING).delete()
        existing_paid = facility.schedule.count()
        rows = generate_repayment_schedule(
            principal=outstanding,
            annual_rate_pct=facility.effective_interest_rate,
            tenure_months=facility.tenure_months,
            start_date=start_date or facility.sanction_date,
            method=facility.schedule_method,
            frequency=facility.repayment_frequency,
            moratorium_months=facility.moratorium_months,
        )
        created = []
        for idx, r in enumerate(rows, start=existing_paid + 1):
            created.append(
                LoanScheduleInstallment.objects.create(
                    facility=facility,
                    installment_no=idx,
                    due_date=r["due_date"],
                    opening_principal=r["opening_principal"],
                    principal_due=r["principal_due"],
                    interest_due=r["interest_due"],
                    closing_principal=r["closing_principal"],
                )
            )
        return created

    @staticmethod
    @transaction.atomic
    def record_repayment(
        *,
        facility: BankFacility,
        user,
        payment_date: date,
        principal_amount: Decimal,
        interest_amount: Decimal,
        penal_amount: Decimal = Decimal("0.00"),
        installment: LoanScheduleInstallment | None = None,
        is_prepayment: bool = False,
        settle_accrued_interest: bool = False,
    ) -> LoanRepayment:
        total_out = principal_amount + interest_amount + penal_amount
        if total_out <= 0:
            raise ValidationError("Total repayment amount must be positive.")

        lines = []
        if principal_amount > 0:
            lines.append({"account": facility.linked_liability_account, "debit": principal_amount, "credit": Decimal("0.00"), "project": facility.project})
        if interest_amount + penal_amount > 0:
            int_debit_acc = (
                facility.accrued_interest_account
                if settle_accrued_interest and facility.accrued_interest_account_id
                else facility.linked_interest_account
            )
            lines.append({"account": int_debit_acc, "debit": interest_amount + penal_amount, "credit": Decimal("0.00"), "project": facility.project})
        lines.append({"account": facility.bank_account.gl_account, "debit": Decimal("0.00"), "credit": total_out, "project": facility.project})

        v = _post_system_voucher(
            company=facility.company,
            user=user,
            vtype=Voucher.VoucherType.PAYMENT,
            vdate=payment_date,
            project=facility.project,
            narration=f"{'Prepayment' if is_prepayment else 'Installment'} for {facility.facility_code}",
            lines_data=lines,
        )
        rep = LoanRepayment.objects.create(
            facility=facility,
            installment=installment,
            payment_date=payment_date,
            principal_amount=principal_amount,
            interest_amount=interest_amount,
            penal_amount=penal_amount,
            is_prepayment=is_prepayment,
            voucher=v,
            created_by=user,
        )
        if installment:
            installment.principal_paid += principal_amount
            installment.interest_paid += interest_amount
            if installment.principal_paid >= installment.principal_due and installment.interest_paid >= installment.interest_due:
                installment.status = LoanScheduleInstallment.Status.PAID
            else:
                installment.status = LoanScheduleInstallment.Status.PARTIAL
            installment.save(update_fields=["principal_paid", "interest_paid", "status"])
        if settle_accrued_interest:
            facility.interest_accruals.filter(status=LoanInterestAccrual.Status.ACCRUED).update(status=LoanInterestAccrual.Status.SETTLED)
        return rep

    @staticmethod
    def _effective_limit(facility: BankFacility) -> Decimal:
        eff_limit = facility.sanctioned_limit
        if facility.facility_type == BankFacility.FacilityType.CASH_CREDIT:
            latest_dp = facility.dp_assessments.order_by("-assessment_date").first()
            if latest_dp:
                eff_limit = latest_dp.effective_limit
        return eff_limit

    @staticmethod
    def _opening_balance_as_of(facility: BankFacility, target_date: date) -> Decimal:
        """Compute historical facility principal balance right before target_date (start of day)."""
        agg = LedgerEntry.objects.filter(
            account=facility.linked_liability_account,
            posting_date__lt=target_date,
        ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        ledger_bal = (
            (facility.linked_liability_account.opening_credit - facility.linked_liability_account.opening_debit)
            + ((agg["c"] or Decimal("0.00")) - (agg["d"] or Decimal("0.00")))
        )
        # Include any un-vouchered OD transactions prior to target_date
        od_prior = facility.od_transactions.filter(value_date__lt=target_date, voucher__isnull=True).aggregate(
            dr=Sum("debit_amount"), cr=Sum("credit_amount")
        )
        return (ledger_bal + (od_prior["dr"] or Decimal("0.00")) - (od_prior["cr"] or Decimal("0.00"))).quantize(Decimal("0.01"))

    @staticmethod
    def calculate_facility_interest(
        *,
        facility: BankFacility,
        period_start: date,
        period_end: date,
        opening_balance_override: Decimal | None = None,
        extra_transactions: list[dict] | None = None,
    ) -> dict:
        open_bal = (
            opening_balance_override
            if opening_balance_override is not None
            else LoanService._opening_balance_as_of(facility, period_start)
        )
        rate_versions = list(
            facility.rate_versions.filter(rate_kind=FacilityRateVersion.RateKind.NORMAL).values(
                "effective_from", "effective_to", "effective_rate_pct", "penal_rate_pct", "version_code", "rate_unit"
            )
        )
        if not rate_versions:
            # Backwards compatible fallback from LoanRateRevision + facility effective rate
            revs = list(facility.rate_revisions.order_by("effective_date"))
            if revs:
                for i, r in enumerate(revs):
                    next_d = (revs[i + 1].effective_date - timedelta(days=1)) if i + 1 < len(revs) else None
                    rate_versions.append({
                        "effective_from": r.effective_date,
                        "effective_to": next_d,
                        "effective_rate_pct": r.base_rate + r.premium_rate,
                        "penal_rate_pct": facility.penal_rate,
                        "version_code": f"REV{i+1}",
                        "rate_unit": "ANNUAL",
                    })
            else:
                rate_versions.append({
                    "effective_from": facility.sanction_date,
                    "effective_to": None,
                    "effective_rate_pct": facility.monthly_contract_rate if (facility.day_count_basis == BankFacility.DayCountBasis.CONTRACT_MONTHLY and facility.monthly_contract_rate) else facility.effective_interest_rate,
                    "penal_rate_pct": facility.penal_rate,
                    "version_code": "R001",
                    "rate_unit": "MONTHLY" if facility.day_count_basis == BankFacility.DayCountBasis.CONTRACT_MONTHLY else "ANNUAL",
                })

        txns: list[dict] = []
        if opening_balance_override is None:
            for d in facility.disbursements.filter(disbursement_date__gte=period_start, disbursement_date__lte=period_end):
                txns.append({"value_date": d.disbursement_date, "drawdown": d.amount, "repayment": Decimal("0.00")})
            for rp in facility.repayments.filter(payment_date__gte=period_start, payment_date__lte=period_end):
                if rp.principal_amount > 0:
                    txns.append({"value_date": rp.payment_date, "drawdown": Decimal("0.00"), "repayment": rp.principal_amount})
            for od in facility.od_transactions.filter(value_date__gte=period_start, value_date__lte=period_end):
                txns.append({"value_date": od.value_date, "drawdown": od.debit_amount, "repayment": od.credit_amount})
        if extra_transactions:
            txns.extend(extra_transactions)

        return simulate_daily_interest(
            period_start=period_start,
            period_end=period_end,
            opening_balance=open_bal,
            day_count_basis=facility.day_count_basis,
            default_annual_rate=facility.effective_interest_rate,
            penal_rate_pct=facility.penal_rate,
            effective_limit=LoanService._effective_limit(facility),
            monthly_contract_rate=facility.monthly_contract_rate,
            rate_periods=rate_versions,
            transactions=txns,
            charge_interest_on_credit=facility.charge_interest_on_credit,
        )

    @staticmethod
    @transaction.atomic
    def add_rate_version(
        *,
        facility: BankFacility,
        user,
        effective_from: date,
        effective_to: date | None = None,
        rate_kind: str = FacilityRateVersion.RateKind.NORMAL,
        rate_type: str | None = None,
        rate_unit: str | None = None,
        benchmark_name: str = "",
        benchmark_value: Decimal = Decimal("0.0000"),
        spread_pct: Decimal = Decimal("0.0000"),
        effective_rate_pct: Decimal | None = None,
        penal_rate_pct: Decimal | None = None,
        next_reset_date: date | None = None,
        approval_ref: str = "",
        reason: str = "",
        auto_approve: bool = False,
        rebuild_future_schedule: bool = True,
    ) -> FacilityRateVersion:
        if effective_to and effective_to < effective_from:
            raise ValidationError("Rate effective_to cannot precede effective_from.")

        existing_qs = facility.rate_versions.filter(rate_kind=rate_kind).order_by("effective_from")
        # Close previous open-ended version cleanly at effective_from - 1, OR reject true overlaps
        for prev in existing_qs:
            prev_end = prev.effective_to
            if prev_end is None and prev.effective_from < effective_from:
                prev.effective_to = effective_from - timedelta(days=1)
                prev.status = FacilityRateVersion.Status.SUPERSEDED
                prev.save(update_fields=["effective_to", "status"])
                continue
            latest_start = max(prev.effective_from, effective_from)
            earliest_end = min(prev_end, effective_to) if (prev_end and effective_to) else (prev_end or effective_to)
            if earliest_end is None or latest_start <= earliest_end:
                raise ValidationError(
                    f"Overlapping rate period with version {prev.version_code} ({prev.effective_from} to {prev.effective_to or 'Open'})."
                )

        calc_rate = effective_rate_pct if effective_rate_pct is not None else (benchmark_value + spread_pct)
        ver_no = f"R{facility.rate_versions.count() + 1:03d}"
        today = timezone.localdate()
        rv_status = (
            FacilityRateVersion.Status.SCHEDULED
            if effective_from > today
            else FacilityRateVersion.Status.CURRENT
        )
        rv = FacilityRateVersion.objects.create(
            company=facility.company,
            facility=facility,
            version_code=ver_no,
            rate_kind=rate_kind,
            rate_type=rate_type or facility.interest_mode,
            rate_unit=rate_unit or (FacilityRateVersion.RateUnit.MONTHLY if facility.day_count_basis == BankFacility.DayCountBasis.CONTRACT_MONTHLY else FacilityRateVersion.RateUnit.ANNUAL),
            benchmark_name=benchmark_name,
            benchmark_value=benchmark_value,
            spread_pct=spread_pct,
            effective_rate_pct=calc_rate,
            penal_rate_pct=penal_rate_pct if penal_rate_pct is not None else facility.penal_rate,
            effective_from=effective_from,
            effective_to=effective_to,
            next_reset_date=next_reset_date,
            status=rv_status,
            approval_ref=approval_ref,
            reason=reason,
            created_by=user,
            approved_by=user if auto_approve else None,
        )
        if rate_kind == FacilityRateVersion.RateKind.NORMAL and effective_from <= today:
            facility.base_rate = benchmark_value if benchmark_value > 0 else calc_rate
            facility.premium_rate = spread_pct if benchmark_value > 0 else Decimal("0.00")
            if penal_rate_pct is not None:
                facility.penal_rate = penal_rate_pct
            facility.save(update_fields=["base_rate", "premium_rate", "penal_rate"])
            if rebuild_future_schedule and facility.facility_type not in (
                BankFacility.FacilityType.OVERDRAFT,
                BankFacility.FacilityType.CASH_CREDIT,
                BankFacility.FacilityType.BANK_GUARANTEE,
            ):
                LoanService.rebuild_schedule(facility=facility, start_date=effective_from)
        record_treasury_audit(
            company=facility.company,
            module="LOANS",
            action="RATE_VERSION_CREATED",
            entity_type="FacilityRateVersion",
            entity_id=str(rv.id),
            actor=user,
            new_state={"version": ver_no, "rate": str(calc_rate), "effective_from": effective_from.isoformat()},
        )
        return rv

    @staticmethod
    @transaction.atomic
    def accrue_periodic_interest(
        *,
        facility: BankFacility,
        user,
        period_start: date,
        period_end: date,
        bank_debited_interest: Decimal | None = None,
        variance_reason: str = "",
        post_adjustment: bool = False,
        opening_balance_override: Decimal | None = None,
    ) -> LoanInterestAccrual:
        calc = LoanService.calculate_facility_interest(
            facility=facility,
            period_start=period_start,
            period_end=period_end,
            opening_balance_override=opening_balance_override,
        )
        days = calc["days"]
        sys_int = calc["total_interest"]
        avg_prin = (
            sum((r["closing_debit_balance"] for r in calc["daily_rows"]), Decimal("0.00")) / Decimal(max(1, days))
        ).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        rate = calc["segments"][-1]["applicable_rate"] if calc["segments"] else facility.effective_interest_rate
        accrued_acc = facility.accrued_interest_account
        if not accrued_acc:
            accrued_acc, _ = Account.objects.get_or_create(
                company=facility.company,
                code="2350",
                defaults={"name": "Accrued Loan Interest Payable", "account_type": Account.AccountType.LIABILITY, "allow_direct_posting": True},
            )
            facility.accrued_interest_account = accrued_acc
            facility.save(update_fields=["accrued_interest_account"])

        accrual_v = None
        if sys_int > 0:
            accrual_v = _post_system_voucher(
                company=facility.company,
                user=user,
                vtype=Voucher.VoucherType.JOURNAL,
                vdate=period_end,
                project=facility.project,
                narration=f"Interest accrual ({facility.facility_code}) {period_start}..{period_end}",
                lines_data=[
                    {"account": facility.linked_interest_account, "debit": sys_int, "credit": Decimal("0.00"), "project": facility.project},
                    {"account": accrued_acc, "debit": Decimal("0.00"), "credit": sys_int, "project": facility.project},
                ],
            )

        variance = Decimal("0.00")
        adj_v = None
        st = LoanInterestAccrual.Status.ACCRUED
        if bank_debited_interest is not None:
            variance = (bank_debited_interest - sys_int).quantize(Decimal("0.01"))
            if post_adjustment and variance != Decimal("0.00"):
                if variance > 0:
                    adj_lines = [
                        {"account": facility.linked_interest_account, "debit": variance, "credit": Decimal("0.00"), "project": facility.project},
                        {"account": accrued_acc, "debit": Decimal("0.00"), "credit": variance, "project": facility.project},
                    ]
                else:
                    adj_lines = [
                        {"account": accrued_acc, "debit": abs(variance), "credit": Decimal("0.00"), "project": facility.project},
                        {"account": facility.linked_interest_account, "debit": Decimal("0.00"), "credit": abs(variance), "project": facility.project},
                    ]
                adj_v = _post_system_voucher(
                    company=facility.company,
                    user=user,
                    vtype=Voucher.VoucherType.JOURNAL,
                    vdate=period_end,
                    project=facility.project,
                    narration=f"Interest variance adjustment ({facility.facility_code}): {variance_reason}",
                    lines_data=adj_lines,
                )
                st = LoanInterestAccrual.Status.ADJUSTED

        return LoanInterestAccrual.objects.create(
            company=facility.company,
            facility=facility,
            period_start=period_start,
            period_end=period_end,
            days=days,
            day_count_basis=facility.day_count_basis,
            average_principal=avg_prin,
            effective_rate=rate,
            system_calculated_interest=sys_int,
            bank_debited_interest=bank_debited_interest,
            variance_amount=variance,
            variance_reason=variance_reason,
            accrual_voucher=accrual_v,
            adjustment_voucher=adj_v,
            status=st,
            created_by=user,
        )

    @staticmethod
    @transaction.atomic
    def save_interest_calculation_run(
        *,
        facility: BankFacility,
        user,
        period_start: date,
        period_end: date,
        opening_balance_override: Decimal | None = None,
        bank_charged_interest: Decimal | None = None,
        fee_amount: Decimal = Decimal("0.00"),
        post_to_gl: bool = False,
    ) -> InterestCalculationRun:
        calc = LoanService.calculate_facility_interest(
            facility=facility,
            period_start=period_start,
            period_end=period_end,
            opening_balance_override=opening_balance_override,
        )
        total_calc = (calc["normal_interest"] + calc["penal_interest"] + fee_amount).quantize(Decimal("0.01"))
        diff = (bank_charged_interest - total_calc).quantize(Decimal("0.01")) if bank_charged_interest is not None else Decimal("0.00")
        voucher = None
        run_status = InterestCalculationRun.Status.DRAFT
        if post_to_gl and total_calc > 0:
            accrued_acc = facility.accrued_interest_account
            if not accrued_acc:
                accrued_acc, _ = Account.objects.get_or_create(
                    company=facility.company,
                    code="2350",
                    defaults={"name": "Accrued Loan Interest Payable", "account_type": Account.AccountType.LIABILITY, "allow_direct_posting": True},
                )
                facility.accrued_interest_account = accrued_acc
                facility.save(update_fields=["accrued_interest_account"])
            voucher = _post_system_voucher(
                company=facility.company,
                user=user,
                vtype=Voucher.VoucherType.JOURNAL,
                vdate=period_end,
                project=facility.project,
                narration=f"Interest Run ({facility.facility_code}) {period_start}..{period_end}",
                lines_data=[
                    {"account": facility.linked_interest_account, "debit": total_calc, "credit": Decimal("0.00"), "project": facility.project},
                    {"account": accrued_acc, "debit": Decimal("0.00"), "credit": total_calc, "project": facility.project},
                ],
            )
            run_status = InterestCalculationRun.Status.POSTED

        run = InterestCalculationRun.objects.create(
            company=facility.company,
            facility=facility,
            period_start=period_start,
            period_end=period_end,
            day_count_basis=facility.day_count_basis,
            opening_balance=calc["opening_balance"],
            normal_interest=calc["normal_interest"],
            penal_interest=calc["penal_interest"],
            fee_amount=fee_amount,
            total_calculated=total_calc,
            bank_charged_interest=bank_charged_interest,
            difference_amount=diff,
            status=run_status,
            voucher=voucher,
            created_by=user,
            approved_by=user if post_to_gl else None,
        )
        InterestDailyDetail.objects.bulk_create([
            InterestDailyDetail(
                run=run,
                calc_date=r["calc_date"],
                opening_balance=r["opening_balance"],
                drawdown=r["drawdown"],
                repayment=r["repayment"],
                closing_debit_balance=r["closing_debit_balance"],
                applicable_rate=r["applicable_rate"],
                rate_version_code=r["rate_version_code"],
                daily_interest=r["daily_interest"],
                penal_interest=r["penal_interest"],
                is_excess_limit=r["is_excess_limit"],
            )
            for r in calc["daily_rows"]
        ])
        return run

    @staticmethod
    @transaction.atomic
    def record_od_transaction(
        *,
        facility: BankFacility,
        user,
        txn_date: date,
        value_date: date | None = None,
        txn_type: str,
        debit_amount: Decimal = Decimal("0.00"),
        credit_amount: Decimal = Decimal("0.00"),
        reference_no: str = "",
        narration: str = "",
        post_voucher: bool = True,
    ) -> ODCreditTransaction:
        vd = value_date or txn_date
        v = None
        if post_voucher and (debit_amount > 0 or credit_amount > 0):
            if debit_amount > 0:
                lines = [
                    {"account": facility.bank_account.gl_account, "debit": debit_amount, "credit": Decimal("0.00"), "project": facility.project},
                    {"account": facility.linked_liability_account, "debit": Decimal("0.00"), "credit": debit_amount, "project": facility.project},
                ]
                vtype = Voucher.VoucherType.RECEIPT
            else:
                lines = [
                    {"account": facility.linked_liability_account, "debit": credit_amount, "credit": Decimal("0.00"), "project": facility.project},
                    {"account": facility.bank_account.gl_account, "debit": Decimal("0.00"), "credit": credit_amount, "project": facility.project},
                ]
                vtype = Voucher.VoucherType.PAYMENT
            v = _post_system_voucher(
                company=facility.company,
                user=user,
                vtype=vtype,
                vdate=vd,
                project=facility.project,
                narration=narration or f"OD/CC {txn_type} ({facility.facility_code})",
                lines_data=lines,
            )
        return ODCreditTransaction.objects.create(
            company=facility.company,
            facility=facility,
            txn_date=txn_date,
            value_date=vd,
            txn_type=txn_type,
            debit_amount=debit_amount,
            credit_amount=credit_amount,
            reference_no=reference_no,
            narration=narration,
            voucher=v,
            created_by=user,
        )

    @staticmethod
    @transaction.atomic
    def amend_facility(
        *,
        facility: BankFacility,
        user,
        new_limit: Decimal | None = None,
        new_maturity_date: date | None = None,
        new_renewal_date: date | None = None,
        summary: str = "",
        amendment_no: str = "",
    ) -> LoanFacilityAmendment:
        prev_limit = facility.sanctioned_limit
        prev_mat = facility.maturity_date
        if new_limit is not None:
            facility.sanctioned_limit = new_limit
        if new_maturity_date is not None:
            facility.maturity_date = new_maturity_date
        if new_renewal_date is not None:
            facility.renewal_date = new_renewal_date
        facility.save(update_fields=["sanctioned_limit", "maturity_date", "renewal_date"])
        am = LoanFacilityAmendment.objects.create(
            company=facility.company,
            facility=facility,
            amendment_no=amendment_no or f"AMD-{facility.amendments.count() + 1:03d}",
            amendment_date=timezone.localdate(),
            previous_limit=prev_limit,
            new_limit=facility.sanctioned_limit,
            previous_maturity_date=prev_mat,
            new_maturity_date=facility.maturity_date,
            summary=summary or "Facility sanction / renewal amendment",
            approved_by=user,
        )
        record_treasury_audit(
            company=facility.company,
            module="LOANS",
            action="LOAN_FACILITY_AMENDED",
            entity_type="BankFacility",
            entity_id=str(facility.id),
            actor=user,
            previous_state={"limit": str(prev_limit), "maturity": prev_mat.isoformat()},
            new_state={"limit": str(facility.sanctioned_limit), "maturity": facility.maturity_date.isoformat()},
        )
        return am

    @staticmethod
    @transaction.atomic
    def assess_drawing_power(
        *,
        facility: BankFacility,
        assessment_date: date,
        eligible_stock: Decimal,
        eligible_receivables: Decimal,
        eligible_raw_materials: Decimal = Decimal("0.00"),
        eligible_wip: Decimal = Decimal("0.00"),
        creditor_deductions: Decimal = Decimal("0.00"),
        other_deductions: Decimal = Decimal("0.00"),
        notes: str = "",
    ) -> DrawingPowerAssessment:
        if facility.facility_type != BankFacility.FacilityType.CASH_CREDIT:
            raise ValidationError("Drawing power assessment applies to Cash Credit (CC) facilities.")
        cfg, _ = RevolvingProductConfig.objects.get_or_create(
            company=facility.company,
            product_kind=RevolvingProductConfig.ProductKind.CASH_CREDIT,
            defaults={"requires_drawing_power": True},
        )
        dp_cfg = DrawingPowerConfig.objects.filter(facility=facility).first()
        nrb = LoanService.get_active_nrb_config(facility.company, assessment_date)
        st_hair = dp_cfg.stock_margin_pct if dp_cfg else (nrb.cc_default_haircut_pct if nrb else cfg.stock_haircut_pct)
        rm_hair = dp_cfg.raw_material_margin_pct if dp_cfg else st_hair
        wip_hair = dp_cfg.wip_margin_pct if dp_cfg else Decimal("50.00")
        rc_hair = dp_cfg.receivable_margin_pct if dp_cfg else cfg.receivable_haircut_pct

        q = Decimal("0.01")
        dp_stock = eligible_stock * (Decimal("100") - st_hair) / Decimal("100")
        dp_rm = eligible_raw_materials * (Decimal("100") - rm_hair) / Decimal("100")
        dp_wip = (eligible_wip * (Decimal("100") - wip_hair) / Decimal("100")) if (dp_cfg is None or dp_cfg.allow_wip) else Decimal("0.00")
        dp_rec = eligible_receivables * (Decimal("100") - rc_hair) / Decimal("100")
        dp = max(Decimal("0.00"), (dp_stock + dp_rm + dp_wip + dp_rec - creditor_deductions - other_deductions).quantize(q, rounding=ROUND_HALF_UP))
        eff = min(facility.sanctioned_limit, dp)
        if dp_cfg and dp_cfg.drawing_power_cap:
            eff = min(eff, dp_cfg.drawing_power_cap)
        return DrawingPowerAssessment.objects.create(
            facility=facility,
            assessment_date=assessment_date,
            eligible_stock=eligible_stock,
            eligible_raw_materials=eligible_raw_materials,
            eligible_wip=eligible_wip,
            eligible_receivables=eligible_receivables,
            creditor_deductions=creditor_deductions,
            other_deductions=other_deductions,
            stock_haircut_pct=st_hair,
            receivable_haircut_pct=rc_hair,
            computed_drawing_power=dp,
            effective_limit=eff,
            notes=notes[:255],
        )

    @staticmethod
    @transaction.atomic
    def postpone_installment(*, installment: LoanScheduleInstallment, user, new_due_date: date, reason: str = "") -> LoanScheduleInstallment:
        if installment.status == LoanScheduleInstallment.Status.PAID:
            raise ValidationError("Cannot postpone an already paid installment.")
        prev_due = installment.due_date
        installment.due_date = new_due_date
        installment.is_postponed = True
        installment.postponement_reason = reason[:255]
        installment.save(update_fields=["due_date", "is_postponed", "postponement_reason"])
        record_treasury_audit(
            company=installment.facility.company,
            module="LOANS",
            action="INSTALLMENT_POSTPONED",
            entity_type="LoanScheduleInstallment",
            entity_id=str(installment.id),
            actor=user,
            previous_state={"due_date": prev_due.isoformat()},
            new_state={"due_date": new_due_date.isoformat()},
            notes=reason,
        )
        return installment

    @staticmethod
    @transaction.atomic
    def record_daily_revolving_interest(*, facility: BankFacility, balance_date: date, user, post_debit: bool = False) -> DailyFacilityBalance:
        utilized = LoanService.get_outstanding_principal(facility)
        rate = facility.effective_interest_rate
        daily_int = calculate_period_interest(
            principal=max(utilized, Decimal("0.00")),
            annual_rate_pct=rate,
            days=1,
            day_count_basis=facility.day_count_basis,
        )

        eff_limit = facility.sanctioned_limit
        if facility.facility_type == BankFacility.FacilityType.CASH_CREDIT:
            latest_dp = facility.dp_assessments.order_by("-assessment_date").first()
            if latest_dp:
                eff_limit = latest_dp.effective_limit

        excess = utilized > eff_limit
        voucher = None
        if post_debit and daily_int > 0:
            voucher = _post_system_voucher(
                company=facility.company,
                user=user,
                vtype=Voucher.VoucherType.JOURNAL,
                vdate=balance_date,
                project=facility.project,
                narration=f"Daily {facility.facility_type} interest debit ({facility.facility_code})",
                lines_data=[
                    {"account": facility.linked_interest_account, "debit": daily_int, "credit": Decimal("0.00"), "project": facility.project},
                    {"account": facility.linked_liability_account, "debit": Decimal("0.00"), "credit": daily_int, "project": facility.project},
                ],
            )
        obj, _ = DailyFacilityBalance.objects.update_or_create(
            facility=facility,
            balance_date=balance_date,
            defaults={
                "utilized_amount": utilized,
                "applicable_rate": rate,
                "daily_interest": daily_int,
                "is_excess_drawing": excess,
                "interest_voucher": voucher,
            },
        )
        return obj

    @staticmethod
    @transaction.atomic
    def issue_bank_guarantee(*, company, user, data: dict) -> BankGuarantee:
        amt = data["amount"]
        margin_pct = data.get("margin_percent", Decimal("10.00"))
        margin_amt = (amt * margin_pct / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        comm_amt = data.get("commission_amount", Decimal("0.00"))
        bank_acc = data["bank_account"]

        margin_v = None
        if margin_amt > 0 or comm_amt > 0:
            margin_gl, _ = Account.objects.get_or_create(
                company=company,
                code="1310",
                defaults={"name": "Bank Guarantee Margin Deposit", "account_type": Account.AccountType.ASSET},
            )
            comm_gl, _ = Account.objects.get_or_create(
                company=company,
                code="5240",
                defaults={"name": "Bank Guarantee Commission", "account_type": Account.AccountType.EXPENSE},
            )
            lines = []
            if margin_amt > 0:
                lines.append({"account": margin_gl, "debit": margin_amt, "credit": Decimal("0.00"), "project": data.get("project")})
            if comm_amt > 0:
                lines.append({"account": comm_gl, "debit": comm_amt, "credit": Decimal("0.00"), "project": data.get("project")})
            lines.append({"account": bank_acc.gl_account, "debit": Decimal("0.00"), "credit": margin_amt + comm_amt, "project": data.get("project")})
            margin_v = _post_system_voucher(
                company=company,
                user=user,
                vtype=Voucher.VoucherType.PAYMENT,
                vdate=data["issue_date"],
                project=data.get("project"),
                narration=f"BG Margin & Commission ({data['bg_number']} — {data['beneficiary']})",
                lines_data=lines,
            )

        bg = BankGuarantee.objects.create(
            company=company,
            facility=data.get("facility"),
            bank_account=bank_acc,
            bank_branch=data.get("bank_branch") or bank_acc.bank_branch,
            project=data.get("project"),
            internal_ref=data.get("internal_ref", ""),
            bg_number=data["bg_number"],
            bg_type=data["bg_type"],
            beneficiary=data["beneficiary"],
            beneficiary_address=data.get("beneficiary_address", ""),
            beneficiary_pan=data.get("beneficiary_pan", ""),
            beneficiary_contact=data.get("beneficiary_contact", ""),
            beneficiary_org_type=data.get("beneficiary_org_type", ""),
            contract_number=data.get("contract_number", ""),
            tender_number=data.get("tender_number", ""),
            contract_value=data.get("contract_value", Decimal("0.00")),
            purpose=data.get("purpose", ""),
            currency=data.get("currency", bank_acc.currency),
            original_amount=amt,
            amount=amt,
            margin_percent=margin_pct,
            margin_amount=margin_amt,
            commission_rate=data.get("commission_rate", Decimal("0.0000")),
            commission_basis=data.get("commission_basis", "PER_ANNUM"),
            commission_amount=comm_amt,
            bank_charges=data.get("bank_charges", Decimal("0.00")),
            application_date=data.get("application_date") or data["issue_date"],
            issue_date=data["issue_date"],
            effective_date=data.get("effective_date") or data["issue_date"],
            original_expiry_date=data["expiry_date"],
            expiry_date=data["expiry_date"],
            claim_expiry_date=data.get("claim_expiry_date"),
            expected_release_date=data.get("expected_release_date"),
            status=data.get("status", BankGuarantee.Status.ACTIVE),
            margin_voucher=margin_v,
            notes=data.get("notes", ""),
        )
        record_treasury_audit(
            company=company,
            module="GUARANTEES",
            action="BG_ISSUED",
            entity_type="BankGuarantee",
            entity_id=str(bg.id),
            actor=user,
            new_state={"bg_number": bg.bg_number, "amount": str(bg.amount), "margin": str(bg.margin_amount)},
        )
        return bg

    @staticmethod
    @transaction.atomic
    def amend_guarantee(
        *,
        bg: BankGuarantee,
        user,
        amendment_date: date,
        amendment_type: str,
        new_amount: Decimal | None = None,
        new_beneficiary: str = "",
        amendment_charges: Decimal = Decimal("0.00"),
        reason: str = "",
    ) -> GuaranteeAmendment:
        prev_amt = bg.amount
        prev_ben = bg.beneficiary
        tgt_amt = new_amount if new_amount is not None else prev_amt
        tgt_ben = new_beneficiary or prev_ben
        charge_v = None
        if amendment_charges > 0:
            comm_gl, _ = Account.objects.get_or_create(
                company=bg.company,
                code="5240",
                defaults={"name": "Bank Guarantee Commission", "account_type": Account.AccountType.EXPENSE},
            )
            charge_v = _post_system_voucher(
                company=bg.company,
                user=user,
                vtype=Voucher.VoucherType.PAYMENT,
                vdate=amendment_date,
                project=bg.project,
                narration=f"BG Amendment Charges ({bg.bg_number}): {reason}",
                lines_data=[
                    {"account": comm_gl, "debit": amendment_charges, "credit": Decimal("0.00"), "project": bg.project},
                    {"account": bg.bank_account.gl_account, "debit": Decimal("0.00"), "credit": amendment_charges, "project": bg.project},
                ],
            )
        ver_no = bg.amendments.count() + 1
        am = GuaranteeAmendment.objects.create(
            company=bg.company,
            guarantee=bg,
            version_no=ver_no,
            amendment_date=amendment_date,
            amendment_type=amendment_type,
            previous_amount=prev_amt,
            new_amount=tgt_amt,
            previous_beneficiary=prev_ben,
            new_beneficiary=tgt_ben,
            amendment_charges=amendment_charges,
            reason=reason or amendment_type,
            charge_voucher=charge_v,
            approved_by=user,
        )
        bg.amount = tgt_amt
        bg.beneficiary = tgt_ben
        if bg.status in (BankGuarantee.Status.ACTIVE, BankGuarantee.Status.EXTENDED, BankGuarantee.Status.ISSUED):
            bg.status = BankGuarantee.Status.AMENDED
        bg.save(update_fields=["amount", "beneficiary", "status"])
        record_treasury_audit(
            company=bg.company,
            module="GUARANTEES",
            action="BG_AMENDED",
            entity_type="BankGuarantee",
            entity_id=str(bg.id),
            actor=user,
            previous_state={"amount": str(prev_amt), "beneficiary": prev_ben},
            new_state={"amount": str(tgt_amt), "beneficiary": tgt_ben},
        )
        return am

    @staticmethod
    @transaction.atomic
    def extend_guarantee(
        *,
        bg: BankGuarantee,
        user,
        new_expiry_date: date,
        new_claim_expiry_date: date | None = None,
        extension_charges: Decimal = Decimal("0.00"),
        bank_advice_ref: str = "",
        reason: str = "",
    ) -> GuaranteeExtension:
        prev_exp = bg.expiry_date
        prev_claim = bg.claim_expiry_date
        if not bg.original_expiry_date:
            bg.original_expiry_date = prev_exp
        charge_v = None
        if extension_charges > 0:
            comm_gl, _ = Account.objects.get_or_create(
                company=bg.company,
                code="5240",
                defaults={"name": "Bank Guarantee Commission", "account_type": Account.AccountType.EXPENSE},
            )
            charge_v = _post_system_voucher(
                company=bg.company,
                user=user,
                vtype=Voucher.VoucherType.PAYMENT,
                vdate=timezone.localdate(),
                project=bg.project,
                narration=f"BG Extension Charges ({bg.bg_number})",
                lines_data=[
                    {"account": comm_gl, "debit": extension_charges, "credit": Decimal("0.00"), "project": bg.project},
                    {"account": bg.bank_account.gl_account, "debit": Decimal("0.00"), "credit": extension_charges, "project": bg.project},
                ],
            )
        ext = GuaranteeExtension.objects.create(
            company=bg.company,
            guarantee=bg,
            previous_expiry_date=prev_exp,
            new_expiry_date=new_expiry_date,
            previous_claim_expiry_date=prev_claim,
            new_claim_expiry_date=new_claim_expiry_date,
            extension_charges=extension_charges,
            bank_advice_ref=bank_advice_ref,
            reason=reason or "Validity extension",
            charge_voucher=charge_v,
            approved_by=user,
        )
        bg.expiry_date = new_expiry_date
        if new_claim_expiry_date is not None:
            bg.claim_expiry_date = new_claim_expiry_date
        bg.status = BankGuarantee.Status.EXTENDED
        bg.save(update_fields=["original_expiry_date", "expiry_date", "claim_expiry_date", "status"])
        return ext

    @staticmethod
    @transaction.atomic
    def record_bg_claim(
        *,
        bg: BankGuarantee,
        user,
        claim_notice_date: date,
        claimed_amount: Decimal,
        claim_reason: str = "",
        claiming_beneficiary: str = "",
    ) -> GuaranteeClaim:
        if claimed_amount <= 0 or claimed_amount > bg.amount:
            raise ValidationError("Claim amount must be positive and cannot exceed current guarantee amount.")
        claim = GuaranteeClaim.objects.create(
            company=bg.company,
            guarantee=bg,
            claim_notice_date=claim_notice_date,
            claiming_beneficiary=claiming_beneficiary or bg.beneficiary,
            claimed_amount=claimed_amount,
            dispute_status=GuaranteeClaim.DisputeStatus.RECEIVED,
            claim_reason=claim_reason,
            created_by=user,
        )
        bg.status = BankGuarantee.Status.CLAIMED
        bg.save(update_fields=["status"])
        return claim

    @staticmethod
    @transaction.atomic
    def invoke_bank_guarantee(
        *,
        bg: BankGuarantee,
        user,
        invocation_date: date,
        accepted_amount: Decimal | None = None,
        claim: GuaranteeClaim | None = None,
    ) -> BankGuarantee:
        inv_amt = accepted_amount if accepted_amount is not None else bg.amount
        if inv_amt <= 0 or inv_amt > bg.amount:
            raise ValidationError("Invocation amount must be positive and not exceed current guarantee amount.")
        if bg.status == BankGuarantee.Status.INVOKED and accepted_amount is None:
            return bg

        margin_gl, _ = Account.objects.get_or_create(
            company=bg.company,
            code="1310",
            defaults={"name": "Bank Guarantee Margin Deposit", "account_type": Account.AccountType.ASSET},
        )
        claim_exp_gl, _ = Account.objects.get_or_create(
            company=bg.company,
            code="5410",
            defaults={"name": "Invoked Guarantee / Contract Claims", "account_type": Account.AccountType.EXPENSE},
        )
        funded_liab_gl = (
            bg.facility.linked_liability_account
            if bg.facility
            else Account.objects.get_or_create(
                company=bg.company,
                code="2390",
                defaults={"name": "Invoked BG Funded Liability", "account_type": Account.AccountType.LIABILITY},
            )[0]
        )
        margin_used = min(bg.margin_amount, inv_amt)
        shortfall = max(Decimal("0.00"), inv_amt - margin_used)
        lines = [{"account": claim_exp_gl, "debit": inv_amt, "credit": Decimal("0.00"), "project": bg.project}]
        if margin_used > 0:
            lines.append({"account": margin_gl, "debit": Decimal("0.00"), "credit": margin_used, "project": bg.project})
        if shortfall > 0:
            lines.append({"account": funded_liab_gl, "debit": Decimal("0.00"), "credit": shortfall, "project": bg.project})

        inv_v = _post_system_voucher(
            company=bg.company,
            user=user,
            vtype=Voucher.VoucherType.JOURNAL,
            vdate=invocation_date,
            project=bg.project,
            narration=f"BG Invoked -> Funded Liability ({bg.bg_number})",
            lines_data=lines,
        )
        is_partial = inv_amt < bg.amount
        bg.status = BankGuarantee.Status.PARTIALLY_INVOKED if is_partial else BankGuarantee.Status.INVOKED
        bg.invocation_voucher = inv_v
        if margin_used > 0:
            bg.margin_amount = max(Decimal("0.00"), bg.margin_amount - margin_used)
        bg.save(update_fields=["status", "invocation_voucher", "margin_amount"])
        if claim:
            claim.accepted_amount = inv_amt
            claim.settlement_date = invocation_date
            claim.dispute_status = (
                GuaranteeClaim.DisputeStatus.ACCEPTED_PARTIAL
                if is_partial
                else GuaranteeClaim.DisputeStatus.ACCEPTED_FULL
            )
            claim.voucher = inv_v
            claim.save(update_fields=["accepted_amount", "settlement_date", "dispute_status", "voucher"])
        return bg

    @staticmethod
    @transaction.atomic
    def release_bank_guarantee(
        *,
        bg: BankGuarantee,
        user,
        release_date: date,
        beneficiary_discharge_ref: str,
        bank_release_confirmation_ref: str,
        release_type: str = "FORMAL_RELEASE",
        notes: str = "",
    ) -> GuaranteeRelease:
        if not beneficiary_discharge_ref.strip() or not bank_release_confirmation_ref.strip():
            raise ValidationError("Documented release requires both beneficiary discharge reference and bank release confirmation reference.")
        if bg.claims.filter(dispute_status__in=[GuaranteeClaim.DisputeStatus.RECEIVED, GuaranteeClaim.DisputeStatus.UNDER_REVIEW, GuaranteeClaim.DisputeStatus.DISPUTED]).exists():
            raise ValidationError("Cannot release guarantee while unresolved claim notices remain open.")

        refund_v = None
        refund_amt = bg.margin_amount or Decimal("0.00")
        if refund_amt > 0:
            margin_gl, _ = Account.objects.get_or_create(
                company=bg.company,
                code="1310",
                defaults={"name": "Bank Guarantee Margin Deposit", "account_type": Account.AccountType.ASSET},
            )
            refund_v = _post_system_voucher(
                company=bg.company,
                user=user,
                vtype=Voucher.VoucherType.RECEIPT,
                vdate=release_date,
                project=bg.project,
                narration=f"BG Cash Margin Released ({bg.bg_number} — {bank_release_confirmation_ref})",
                lines_data=[
                    {"account": bg.bank_account.gl_account, "debit": refund_amt, "credit": Decimal("0.00"), "project": bg.project},
                    {"account": margin_gl, "debit": Decimal("0.00"), "credit": refund_amt, "project": bg.project},
                ],
            )
        rel = GuaranteeRelease.objects.create(
            company=bg.company,
            guarantee=bg,
            release_type=release_type,
            beneficiary_discharge_ref=beneficiary_discharge_ref,
            bank_release_confirmation_ref=bank_release_confirmation_ref,
            release_date=release_date,
            margin_refunded_amount=refund_amt,
            margin_release_voucher=refund_v,
            notes=notes,
            approved_by=user,
        )
        bg.status = BankGuarantee.Status.RELEASED
        bg.actual_release_date = release_date
        bg.margin_release_voucher = refund_v
        bg.save(update_fields=["status", "actual_release_date", "margin_release_voucher"])
        record_treasury_audit(
            company=bg.company,
            module="GUARANTEES",
            action="BG_RELEASED",
            entity_type="BankGuarantee",
            entity_id=str(bg.id),
            actor=user,
            new_state={"release_ref": bank_release_confirmation_ref, "margin_refunded": str(refund_amt)},
        )
        return rel

    @staticmethod
    @transaction.atomic
    def record_collateral_valuation(
        *,
        collateral: LoanCollateral,
        user,
        valuation_date: date,
        valuer_name: str,
        market_value: Decimal,
        forced_sale_value: Decimal = Decimal("0.00"),
        haircut_pct: Decimal = Decimal("25.00"),
        valuation_report_no: str = "",
        next_valuation_date: date | None = None,
    ) -> CollateralValuation:
        q = Decimal("0.01")
        eligible = (market_value * (Decimal("100") - haircut_pct) / Decimal("100")).quantize(q, rounding=ROUND_HALF_UP)
        val = CollateralValuation.objects.create(
            company=collateral.company,
            collateral=collateral,
            valuation_date=valuation_date,
            valuer_name=valuer_name,
            valuation_report_no=valuation_report_no,
            market_value=market_value,
            forced_sale_value=forced_sale_value,
            haircut_pct=haircut_pct,
            eligible_security_value=eligible,
            next_valuation_date=next_valuation_date,
            approved_by=user,
        )
        collateral.market_value = market_value
        collateral.forced_sale_value = forced_sale_value
        collateral.haircut_pct = haircut_pct
        collateral.assessed_value = eligible
        collateral.next_valuation_date = next_valuation_date
        collateral.lifecycle_status = LoanCollateral.LifecycleStatus.VALUED if collateral.lifecycle_status in (LoanCollateral.LifecycleStatus.PROPOSED, LoanCollateral.LifecycleStatus.SUBMITTED) else collateral.lifecycle_status
        collateral.save(update_fields=["market_value", "forced_sale_value", "haircut_pct", "assessed_value", "next_valuation_date", "lifecycle_status"])
        return val

    @staticmethod
    @transaction.atomic
    def link_collateral(
        *,
        collateral: LoanCollateral,
        allocated_value: Decimal,
        facility: BankFacility | None = None,
        guarantee: BankGuarantee | None = None,
        charge_rank: str = "FIRST_PARI_PASSU",
        charge_ref: str = "",
    ) -> FacilityCollateralLink:
        if not facility and not guarantee:
            raise ValidationError("Provide either facility or guarantee when linking collateral.")
        if allocated_value <= 0:
            raise ValidationError("Allocated collateral value must be positive.")
        currently_allocated = collateral.allocations.filter(is_released=False).aggregate(s=Sum("allocated_value"))["s"] or Decimal("0.00")
        if currently_allocated + allocated_value > collateral.assessed_value:
            raise ValidationError(
                f"Collateral over-allocation blocked: {currently_allocated + allocated_value} exceeds eligible security value {collateral.assessed_value}."
            )
        link = FacilityCollateralLink.objects.create(
            company=collateral.company,
            collateral=collateral,
            facility=facility,
            guarantee=guarantee,
            allocated_value=allocated_value,
            charge_rank=charge_rank,
            charge_ref=charge_ref,
        )
        if collateral.lifecycle_status in (LoanCollateral.LifecycleStatus.PROPOSED, LoanCollateral.LifecycleStatus.VALUED, LoanCollateral.LifecycleStatus.BANK_ACCEPTED):
            collateral.lifecycle_status = LoanCollateral.LifecycleStatus.ACTIVE
            collateral.save(update_fields=["lifecycle_status"])
        return link

    @staticmethod
    @transaction.atomic
    def release_collateral(
        *,
        collateral: LoanCollateral,
        user,
        release_date: date,
        discharge_ref: str,
        is_partial: bool = False,
        link_id: str | None = None,
        notes: str = "",
    ) -> CollateralRelease:
        if not discharge_ref.strip():
            raise ValidationError("Bank discharge reference is required to release collateral.")
        rel = CollateralRelease.objects.create(
            company=collateral.company,
            collateral=collateral,
            release_date=release_date,
            discharge_ref=discharge_ref,
            is_partial=is_partial,
            notes=notes,
            approved_by=user,
        )
        if link_id:
            collateral.allocations.filter(id=link_id).update(is_released=True, released_at=release_date)
        elif not is_partial:
            collateral.allocations.filter(is_released=False).update(is_released=True, released_at=release_date)

        remaining_links = collateral.allocations.filter(is_released=False).exists()
        if not remaining_links and not is_partial:
            collateral.is_released = True
            collateral.released_at = release_date
            collateral.lifecycle_status = LoanCollateral.LifecycleStatus.RELEASED
            collateral.save(update_fields=["is_released", "released_at", "lifecycle_status"])
        record_treasury_audit(
            company=collateral.company,
            module="COLLATERAL",
            action="COLLATERAL_RELEASED",
            entity_type="LoanCollateral",
            entity_id=str(collateral.id),
            actor=user,
            new_state={"discharge_ref": discharge_ref, "is_partial": is_partial},
        )
        return rel

