import uuid
from decimal import Decimal
from django.conf import settings
from django.db import models


class NrbRegulatoryConfig(models.Model):
    """Versioned, effective-dated NRB Unified Directives & Working Capital Guidelines."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="nrb_configs"
    )
    directive_code = models.CharField(max_length=40)
    title = models.CharField(max_length=200)
    effective_from = models.DateField(db_index=True)
    effective_to = models.DateField(null=True, blank=True)
    working_capital_cap_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("25.00"))
    od_max_limit_npr = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("5000000.00"))
    cc_default_haircut_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("25.00"))
    penal_interest_cap_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("2.00"))
    published_base_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("8.50"))
    notes = models.TextField(blank=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-effective_from"]
        unique_together = [("company", "directive_code")]


class RevolvingProductConfig(models.Model):
    """Independent product rules for Overdraft (OD) vs Cash Credit (CC)."""

    class ProductKind(models.TextChoices):
        OVERDRAFT = "OVERDRAFT", "Overdraft (OD)"
        CASH_CREDIT = "CASH_CREDIT", "Cash Credit (CC)"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    product_kind = models.CharField(max_length=16, choices=ProductKind.choices)
    requires_drawing_power = models.BooleanField(default=False)
    stock_haircut_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("25.00"))
    receivable_haircut_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("30.00"))
    max_tenure_days = models.PositiveIntegerField(default=365)
    allow_clean_overdraft = models.BooleanField(default=False)
    eligibility_notes = models.TextField(blank=True)

    class Meta:
        unique_together = [("company", "product_kind")]


class BankFacility(models.Model):
    class FacilityType(models.TextChoices):
        TERM_LOAN = "TERM_LOAN", "Term Loan"
        OVERDRAFT = "OVERDRAFT", "Overdraft (OD)"
        CASH_CREDIT = "CASH_CREDIT", "Cash Credit (CC)"
        SHORT_TERM_WC = "SHORT_TERM_WC", "Short-Term Working Capital"
        PERMANENT_WC_TERM = "PERMANENT_WC_TERM", "Permanent Working Capital Term Loan"
        DEMAND_LOAN = "DEMAND_LOAN", "Demand Loan"
        CONTRACT_LOAN = "CONTRACT_LOAN", "Contract Loan"
        PROJECT_LOAN = "PROJECT_LOAN", "Project Loan"
        EQUIPMENT_LOAN = "EQUIPMENT_LOAN", "Equipment & Machinery Loan"
        IMPORT_TR_LOAN = "IMPORT_TR_LOAN", "Import / Trust Receipt (TR) Loan"
        EXPORT_FINANCE = "EXPORT_FINANCE", "Export Finance"
        BANK_GUARANTEE = "BANK_GUARANTEE", "Bank Guarantee Line"
        LETTER_OF_CREDIT = "LETTER_OF_CREDIT", "Letter of Credit (LC)"
        CONSORTIUM = "CONSORTIUM", "Consortium Financing"
        OTHER = "OTHER", "Other Credit Facility"

    class InterestMode(models.TextChoices):
        FIXED = "FIXED", "Fixed Rate"
        FLOATING = "FLOATING", "Floating (Base Rate + Premium)"
        CUSTOM = "CUSTOM", "Custom Effective-Dated Schedule"

    class ScheduleMethod(models.TextChoices):
        EMI = "EMI", "Equal Monthly/Periodic Installment (EMI)"
        EQUAL_PRINCIPAL = "EQUAL_PRINCIPAL", "Equal Principal + Reducing Interest"
        REDUCING_BALANCE = "REDUCING_BALANCE", "Reducing Balance"
        BULLET = "BULLET", "Bullet Repayment"
        INTEREST_ONLY = "INTEREST_ONLY", "Interest Only + Principal at Maturity"
        BALLOON = "BALLOON", "Balloon Repayment"
        CUSTOM_PRINCIPAL = "CUSTOM_PRINCIPAL", "Custom Principal Schedule"
        IRREGULAR = "IRREGULAR", "Irregular Installments"

    class Frequency(models.TextChoices):
        DAILY = "DAILY", "Daily Accrual"
        MONTHLY = "MONTHLY", "Monthly"
        QUARTERLY = "QUARTERLY", "Quarterly"
        HALF_YEARLY = "HALF_YEARLY", "Half-Yearly"
        ANNUAL = "ANNUAL", "Annual"
        BULLET = "BULLET", "Bullet at Maturity"
        CUSTOM = "CUSTOM", "Custom Contractual"

    class Status(models.TextChoices):
        APPLIED = "APPLIED", "Applied"
        SANCTIONED = "SANCTIONED", "Sanctioned"
        ACTIVE = "ACTIVE", "Active"
        RESTRUCTURED = "RESTRUCTURED", "Restructured"
        CLOSED = "CLOSED", "Closed / Settled"

    class DayCountBasis(models.TextChoices):
        ACT_365 = "ACT_365", "Actual / 365"
        ACT_360 = "ACT_360", "Actual / 360"
        ACT_ACT = "ACT_ACT", "Actual / Actual"
        THIRTY_360 = "30_360", "30 / 360"
        FIXED_30 = "FIXED_30", "Fixed 30-Day Month"
        CALENDAR_MONTH = "CALENDAR_MONTH", "Actual Calendar Month"
        CONTRACT_MONTHLY = "CONTRACT_MONTHLY", "Contract-Specific Monthly Rate"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="bank_facilities"
    )
    bank_account = models.ForeignKey(
        "banking.BankAccount", on_delete=models.PROTECT, related_name="facilities"
    )
    bank_branch = models.ForeignKey(
        "banking.BankBranch", on_delete=models.PROTECT, null=True, blank=True, related_name="loan_facilities"
    )
    project = models.ForeignKey(
        "projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="facilities"
    )
    facility_code = models.CharField(max_length=40)
    facility_name = models.CharField(max_length=200)
    facility_type = models.CharField(max_length=24, choices=FacilityType.choices)
    loan_account_number_masked = models.CharField(max_length=32, blank=True)
    loan_account_number_encrypted = models.TextField(blank=True)
    sanction_ref = models.CharField(max_length=80, blank=True)
    sanction_date = models.DateField()
    agreement_date = models.DateField(null=True, blank=True)
    first_disbursement_date = models.DateField(null=True, blank=True)
    maturity_date = models.DateField()
    renewal_date = models.DateField(null=True, blank=True)
    currency = models.CharField(max_length=3, default="NPR")
    sanctioned_limit = models.DecimalField(max_digits=18, decimal_places=2)

    interest_mode = models.CharField(max_length=12, choices=InterestMode.choices, default=InterestMode.FLOATING)
    base_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("8.50"))
    premium_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("2.00"))
    penal_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("2.00"))
    monthly_contract_rate = models.DecimalField(max_digits=6, decimal_places=4, null=True, blank=True)
    day_count_basis = models.CharField(max_length=20, choices=DayCountBasis.choices, default=DayCountBasis.ACT_365)
    interest_frequency = models.CharField(max_length=16, choices=Frequency.choices, default=Frequency.MONTHLY)
    interest_start_date = models.DateField(null=True, blank=True)
    repayment_start_date = models.DateField(null=True, blank=True)
    charge_interest_on_credit = models.BooleanField(default=False)

    schedule_method = models.CharField(max_length=20, choices=ScheduleMethod.choices, default=ScheduleMethod.EMI)
    repayment_frequency = models.CharField(max_length=16, choices=Frequency.choices, default=Frequency.MONTHLY)
    tenure_months = models.PositiveIntegerField(default=36)
    moratorium_months = models.PositiveSmallIntegerField(default=0)
    allow_limit_excess_override = models.BooleanField(default=False)

    linked_liability_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, related_name="loan_facilities"
    )
    current_portion_liability_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="current_loan_facilities"
    )
    linked_interest_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, related_name="interest_facilities"
    )
    accrued_interest_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="accrued_interest_facilities"
    )
    bank_charges_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="charge_facilities"
    )
    penal_interest_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="penal_facilities"
    )
    processing_fee_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="fee_facilities"
    )
    fx_gain_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="fx_gain_facilities"
    )
    fx_loss_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="fx_loss_facilities"
    )
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = [("company", "facility_code")]
        ordering = ["facility_code"]

    @property
    def effective_interest_rate(self) -> Decimal:
        if self.interest_mode == self.InterestMode.FIXED:
            return self.base_rate
        return self.base_rate + self.premium_rate


class LoanDisbursement(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="disbursements")
    disbursement_date = models.DateField()
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    reference_no = models.CharField(max_length=64, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)


class LoanRateRevision(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="rate_revisions")
    effective_date = models.DateField()
    base_rate = models.DecimalField(max_digits=5, decimal_places=2)
    premium_rate = models.DecimalField(max_digits=5, decimal_places=2)
    reason = models.CharField(max_length=200, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)


class LoanScheduleInstallment(models.Model):
    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending"
        PARTIAL = "PARTIAL", "Partially Paid"
        PAID = "PAID", "Paid"
        OVERDUE = "OVERDUE", "Overdue"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="schedule")
    installment_no = models.PositiveSmallIntegerField()
    due_date = models.DateField(db_index=True)
    opening_principal = models.DecimalField(max_digits=18, decimal_places=2)
    principal_due = models.DecimalField(max_digits=18, decimal_places=2)
    interest_due = models.DecimalField(max_digits=18, decimal_places=2)
    penal_due = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    fees_due = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    principal_paid = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    interest_paid = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    penal_paid = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    fees_paid = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    closing_principal = models.DecimalField(max_digits=18, decimal_places=2)
    is_postponed = models.BooleanField(default=False)
    postponement_reason = models.CharField(max_length=255, blank=True)
    status = models.CharField(max_length=12, choices=Status.choices, default=Status.PENDING)

    class Meta:
        unique_together = [("facility", "installment_no")]
        ordering = ["installment_no"]


class LoanRepayment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="repayments")
    installment = models.ForeignKey(
        LoanScheduleInstallment, on_delete=models.SET_NULL, null=True, blank=True
    )
    payment_date = models.DateField()
    principal_amount = models.DecimalField(max_digits=18, decimal_places=2)
    interest_amount = models.DecimalField(max_digits=18, decimal_places=2)
    penal_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    is_prepayment = models.BooleanField(default=False)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)


class DrawingPowerAssessment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="dp_assessments")
    assessment_date = models.DateField()
    eligible_stock = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    eligible_raw_materials = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    eligible_wip = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    eligible_receivables = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    creditor_deductions = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    other_deductions = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    stock_haircut_pct = models.DecimalField(max_digits=5, decimal_places=2)
    receivable_haircut_pct = models.DecimalField(max_digits=5, decimal_places=2)
    computed_drawing_power = models.DecimalField(max_digits=18, decimal_places=2)
    effective_limit = models.DecimalField(max_digits=18, decimal_places=2)  # min(sanctioned, cap, dp)
    notes = models.CharField(max_length=255, blank=True)


class DrawingPowerConfig(models.Model):
    """Per-CC facility customizable drawing power rules & statement submission schedule."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    facility = models.OneToOneField(BankFacility, on_delete=models.CASCADE, related_name="dp_config")
    stock_margin_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("25.00"))
    raw_material_margin_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("25.00"))
    allow_wip = models.BooleanField(default=False)
    wip_margin_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("50.00"))
    receivable_margin_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("30.00"))
    debtor_aging_limit_days = models.PositiveSmallIntegerField(default=90)
    drawing_power_cap = models.DecimalField(max_digits=18, decimal_places=2, null=True, blank=True)
    submission_frequency = models.CharField(max_length=16, default="MONTHLY")
    next_stock_statement_due = models.DateField(null=True, blank=True)
    next_debtor_statement_due = models.DateField(null=True, blank=True)
    excluded_collateral_notes = models.CharField(max_length=255, blank=True)
    updated_at = models.DateTimeField(auto_now=True)


class DailyFacilityBalance(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="daily_balances")
    balance_date = models.DateField()
    utilized_amount = models.DecimalField(max_digits=18, decimal_places=2)
    applicable_rate = models.DecimalField(max_digits=5, decimal_places=2)
    daily_interest = models.DecimalField(max_digits=18, decimal_places=2)
    is_excess_drawing = models.BooleanField(default=False)
    interest_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True
    )

    class Meta:
        unique_together = [("facility", "balance_date")]
        ordering = ["-balance_date"]


class BankGuarantee(models.Model):
    class BGType(models.TextChoices):
        BID_BOND = "BID_BOND", "Bid Bond / Tender Guarantee"
        PERFORMANCE = "PERFORMANCE", "Performance Guarantee"
        ADVANCE_PAYMENT = "ADVANCE_PAYMENT", "Advance Payment Guarantee"
        MOBILIZATION_ADVANCE = "MOBILIZATION_ADVANCE", "Mobilization Advance Guarantee"
        RETENTION_MONEY = "RETENTION_MONEY", "Retention Money Guarantee"
        FINANCIAL = "FINANCIAL", "Financial Guarantee"
        CUSTOMS = "CUSTOMS", "Customs Guarantee"
        PAYMENT = "PAYMENT", "Payment Guarantee"
        CONTRACTUAL = "CONTRACTUAL", "Contractual Guarantee"
        OTHER = "OTHER", "Other Guarantee"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        APPLIED = "APPLIED", "Application Submitted"
        INTERNAL_APPROVED = "INTERNAL_APPROVED", "Internal Approved"
        BANK_PROCESSING = "BANK_PROCESSING", "Bank Processing"
        ISSUED = "ISSUED", "Issued"
        ACTIVE = "ACTIVE", "Active (Contingent Exposure)"
        AMENDED = "AMENDED", "Amended"
        EXTENDED = "EXTENDED", "Extended"
        EXPIRED_AWAITING_RELEASE = "EXPIRED_AWAITING_RELEASE", "Expired Awaiting Release"
        RELEASE_REQUESTED = "RELEASE_REQUESTED", "Release Requested"
        RELEASE_CONFIRMED = "RELEASE_CONFIRMED", "Release Confirmed"
        RELEASED = "RELEASED", "Released & Closed"
        CLAIMED = "CLAIMED", "Claim Received"
        PARTIALLY_INVOKED = "PARTIALLY_INVOKED", "Partially Invoked"
        INVOKED = "INVOKED", "Fully Invoked (Funded Liability)"
        REVOKED = "REVOKED", "Revoked / Cancelled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="bank_guarantees"
    )
    facility = models.ForeignKey(
        BankFacility, on_delete=models.PROTECT, null=True, blank=True, related_name="guarantees"
    )
    bank_account = models.ForeignKey(
        "banking.BankAccount", on_delete=models.PROTECT, related_name="guarantees"
    )
    bank_branch = models.ForeignKey(
        "banking.BankBranch", on_delete=models.PROTECT, null=True, blank=True, related_name="guarantees"
    )
    project = models.ForeignKey(
        "projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="guarantees"
    )
    internal_ref = models.CharField(max_length=64, blank=True)
    bg_number = models.CharField(max_length=64)
    bg_type = models.CharField(max_length=24, choices=BGType.choices)
    beneficiary = models.CharField(max_length=200)
    beneficiary_address = models.CharField(max_length=255, blank=True)
    beneficiary_pan = models.CharField(max_length=64, blank=True)
    beneficiary_contact = models.CharField(max_length=120, blank=True)
    beneficiary_org_type = models.CharField(max_length=64, blank=True)
    contract_number = models.CharField(max_length=80, blank=True)
    tender_number = models.CharField(max_length=80, blank=True)
    contract_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    purpose = models.CharField(max_length=255, blank=True)
    currency = models.CharField(max_length=3, default="NPR")
    original_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    margin_percent = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("10.00"))
    margin_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    commission_rate = models.DecimalField(max_digits=6, decimal_places=4, default=Decimal("0.0000"))
    commission_basis = models.CharField(max_length=32, default="PER_ANNUM")
    commission_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    bank_charges = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    application_date = models.DateField(null=True, blank=True)
    approval_date = models.DateField(null=True, blank=True)
    issue_date = models.DateField()
    effective_date = models.DateField(null=True, blank=True)
    original_expiry_date = models.DateField(null=True, blank=True)
    expiry_date = models.DateField()
    claim_expiry_date = models.DateField(null=True, blank=True)
    expected_release_date = models.DateField(null=True, blank=True)
    actual_release_date = models.DateField(null=True, blank=True)
    revocation_date = models.DateField(null=True, blank=True)
    status = models.CharField(max_length=28, choices=Status.choices, default=Status.ACTIVE)
    margin_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="bg_margins"
    )
    margin_release_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="bg_margin_releases"
    )
    invocation_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="bg_invocations"
    )
    notes = models.TextField(blank=True)

    class Meta:
        unique_together = [("company", "bg_number")]
        ordering = ["-issue_date"]


class LoanCollateral(models.Model):
    class SecurityType(models.TextChoices):
        LAND_BUILDING = "LAND_BUILDING", "Land & Building"
        EQUIPMENT_VEHICLE = "EQUIPMENT_VEHICLE", "Equipment & Vehicles"
        FIXED_DEPOSIT = "FIXED_DEPOSIT", "Fixed Deposit Lien"
        CASH_MARGIN = "CASH_MARGIN", "Cash Margin Deposit"
        INVENTORY_RECEIVABLES = "INVENTORY_RECEIVABLES", "Inventory & Receivables"
        SHARES_SECURITIES = "SHARES_SECURITIES", "Shares & Securities"
        PERSONAL_GUARANTEE = "PERSONAL_GUARANTEE", "Personal Guarantee"
        CORPORATE_GUARANTEE = "CORPORATE_GUARANTEE", "Corporate Guarantee"
        OTHER = "OTHER", "Other Contractual Security"

    class LifecycleStatus(models.TextChoices):
        PROPOSED = "PROPOSED", "Proposed"
        SUBMITTED = "SUBMITTED", "Submitted"
        VALUED = "VALUED", "Valued"
        BANK_ACCEPTED = "BANK_ACCEPTED", "Bank Accepted"
        CHARGED = "CHARGED", "Charged / Encumbered"
        ACTIVE = "ACTIVE", "Active"
        RELEASE_REQUESTED = "RELEASE_REQUESTED", "Release Requested"
        BANK_DISCHARGED = "BANK_DISCHARGED", "Bank Discharged"
        RELEASED = "RELEASED", "Released"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="collaterals")
    facility = models.ForeignKey(BankFacility, on_delete=models.SET_NULL, null=True, blank=True, related_name="collaterals")
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True, related_name="collaterals")
    collateral_code = models.CharField(max_length=48, blank=True)
    security_type = models.CharField(max_length=28, choices=SecurityType.choices)
    description = models.CharField(max_length=255)
    owner_name = models.CharField(max_length=150, blank=True)
    owner_type = models.CharField(max_length=48, default="COMPANY")  # COMPANY | DIRECTOR | PROMOTER | THIRD_PARTY
    registration_no = models.CharField(max_length=120, blank=True)
    location = models.CharField(max_length=255, blank=True)
    market_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    forced_sale_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    haircut_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("25.00"))
    assessed_value = models.DecimalField(max_digits=18, decimal_places=2)  # Bank-accepted eligible security value
    next_valuation_date = models.DateField(null=True, blank=True)
    lien_mortgage_ref = models.CharField(max_length=120, blank=True)
    encumbrance_date = models.DateField(null=True, blank=True)
    insurance_policy_no = models.CharField(max_length=80, blank=True)
    insurance_expiry = models.DateField(null=True, blank=True)
    lifecycle_status = models.CharField(max_length=24, choices=LifecycleStatus.choices, default=LifecycleStatus.ACTIVE)
    is_released = models.BooleanField(default=False)
    released_at = models.DateField(null=True, blank=True)


class LoanDocument(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="documents")
    doc_type = models.CharField(max_length=48)  # SANCTION_LETTER | AGREEMENT | MORTGAGE | RELEASE
    title = models.CharField(max_length=200)
    document_ref = models.CharField(max_length=120, blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)


class LoanInterestAccrual(models.Model):
    class Status(models.TextChoices):
        ACCRUED = "ACCRUED", "Accrued"
        ADJUSTED = "ADJUSTED", "Variance Adjusted"
        SETTLED = "SETTLED", "Settled by Repayment"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="interest_accruals")
    period_start = models.DateField()
    period_end = models.DateField()
    days = models.PositiveIntegerField()
    day_count_basis = models.CharField(max_length=20, default="ACT_365")
    average_principal = models.DecimalField(max_digits=18, decimal_places=2)
    effective_rate = models.DecimalField(max_digits=5, decimal_places=2)
    system_calculated_interest = models.DecimalField(max_digits=18, decimal_places=2)
    bank_debited_interest = models.DecimalField(max_digits=18, decimal_places=2, null=True, blank=True)
    variance_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    variance_reason = models.CharField(max_length=255, blank=True)
    accrual_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="loan_accruals"
    )
    adjustment_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="loan_accrual_adjustments"
    )
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACCRUED)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-period_end", "-created_at"]


class LoanFacilityAmendment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="amendments")
    amendment_no = models.CharField(max_length=48)
    amendment_date = models.DateField()
    previous_limit = models.DecimalField(max_digits=18, decimal_places=2)
    new_limit = models.DecimalField(max_digits=18, decimal_places=2)
    previous_maturity_date = models.DateField()
    new_maturity_date = models.DateField()
    summary = models.CharField(max_length=255)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)


class LoanCovenant(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="covenants")
    covenant_title = models.CharField(max_length=160)
    threshold_rule = models.CharField(max_length=160)
    review_frequency = models.CharField(max_length=24, default="QUARTERLY")
    next_review_date = models.DateField(null=True, blank=True)
    compliance_status = models.CharField(max_length=24, default="COMPLIANT")  # COMPLIANT | WARNING | BREACHED
    notes = models.TextField(blank=True)


class FacilityRateVersion(models.Model):
    """Effective-dated rate version preventing overlapping active periods per rate kind."""

    class RateKind(models.TextChoices):
        NORMAL = "NORMAL", "Normal Interest"
        PENAL = "PENAL", "Penal Interest"
        OVERDUE = "OVERDUE", "Overdue Default Rate"

    class RateUnit(models.TextChoices):
        ANNUAL = "ANNUAL", "Annual Rate (% p.a.)"
        MONTHLY = "MONTHLY", "Contractual Monthly Rate (% p.m.)"
        DAILY = "DAILY", "Daily Rate (%)"

    class Status(models.TextChoices):
        SCHEDULED = "SCHEDULED", "Scheduled"
        CURRENT = "CURRENT", "Current"
        SUPERSEDED = "SUPERSEDED", "Superseded"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="rate_versions")
    version_code = models.CharField(max_length=24)  # R001, R002
    rate_kind = models.CharField(max_length=16, choices=RateKind.choices, default=RateKind.NORMAL)
    rate_type = models.CharField(max_length=12, choices=BankFacility.InterestMode.choices, default=BankFacility.InterestMode.FLOATING)
    rate_unit = models.CharField(max_length=12, choices=RateUnit.choices, default=RateUnit.ANNUAL)
    benchmark_name = models.CharField(max_length=80, blank=True)
    benchmark_value = models.DecimalField(max_digits=6, decimal_places=4, default=Decimal("0.0000"))
    spread_pct = models.DecimalField(max_digits=6, decimal_places=4, default=Decimal("0.0000"))
    effective_rate_pct = models.DecimalField(max_digits=7, decimal_places=4)
    penal_rate_pct = models.DecimalField(max_digits=6, decimal_places=4, default=Decimal("2.0000"))
    effective_from = models.DateField(db_index=True)
    effective_to = models.DateField(null=True, blank=True)
    next_reset_date = models.DateField(null=True, blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.CURRENT)
    approval_ref = models.CharField(max_length=80, blank=True)
    reason = models.CharField(max_length=255, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="+")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["effective_from", "created_at"]
        unique_together = [("facility", "version_code")]


class ODCreditTransaction(models.Model):
    """Value-dated Overdraft & Cash Credit account transactions driving daily interest calculations."""

    class TxnType(models.TextChoices):
        DRAWDOWN = "DRAWDOWN", "Drawdown"
        DEPOSIT = "DEPOSIT", "Deposit / Recovery"
        TRANSFER = "TRANSFER", "Transfer"
        INTEREST_DEBIT = "INTEREST_DEBIT", "Interest Debit"
        BANK_CHARGE = "BANK_CHARGE", "Bank Charge"
        EXCESS_TEMP = "EXCESS_TEMP", "Temporary Enhancement / Excess"
        LIMIT_CHANGE = "LIMIT_CHANGE", "Limit Reduction / Renewal"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="od_transactions")
    txn_date = models.DateField(db_index=True)
    value_date = models.DateField(db_index=True)
    txn_type = models.CharField(max_length=20, choices=TxnType.choices)
    debit_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    credit_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    reference_no = models.CharField(max_length=80, blank=True)
    narration = models.CharField(max_length=255, blank=True)
    is_cleared = models.BooleanField(default=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["value_date", "created_at"]


class InterestCalculationRun(models.Model):
    """Saved interactive / month-end interest calculation run with daily breakdown."""

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        SUBMITTED = "SUBMITTED", "Submitted for Approval"
        APPROVED = "APPROVED", "Approved"
        POSTED = "POSTED", "Posted to GL"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, related_name="calculation_runs")
    period_start = models.DateField()
    period_end = models.DateField()
    day_count_basis = models.CharField(max_length=20, default="ACT_365")
    opening_balance = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    normal_interest = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    penal_interest = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    fee_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_calculated = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    bank_charged_interest = models.DecimalField(max_digits=18, decimal_places=2, null=True, blank=True)
    difference_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="+")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-period_end", "-created_at"]


class InterestDailyDetail(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    run = models.ForeignKey(InterestCalculationRun, on_delete=models.CASCADE, related_name="daily_details")
    calc_date = models.DateField()
    opening_balance = models.DecimalField(max_digits=18, decimal_places=2)
    drawdown = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    repayment = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    closing_debit_balance = models.DecimalField(max_digits=18, decimal_places=2)
    applicable_rate = models.DecimalField(max_digits=7, decimal_places=4)
    rate_version_code = models.CharField(max_length=24, blank=True)
    daily_interest = models.DecimalField(max_digits=18, decimal_places=4)
    penal_interest = models.DecimalField(max_digits=18, decimal_places=4, default=Decimal("0.0000"))
    is_excess_limit = models.BooleanField(default=False)

    class Meta:
        ordering = ["calc_date"]


class GuaranteeAmendment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    guarantee = models.ForeignKey(BankGuarantee, on_delete=models.CASCADE, related_name="amendments")
    version_no = models.PositiveSmallIntegerField(default=1)
    amendment_date = models.DateField()
    amendment_type = models.CharField(max_length=32)  # AMOUNT_INCREASE | AMOUNT_DECREASE | BENEFICIARY | CONTRACT | OTHER
    previous_amount = models.DecimalField(max_digits=18, decimal_places=2)
    new_amount = models.DecimalField(max_digits=18, decimal_places=2)
    previous_beneficiary = models.CharField(max_length=200, blank=True)
    new_beneficiary = models.CharField(max_length=200, blank=True)
    amendment_charges = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    reason = models.CharField(max_length=255)
    charge_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-version_no", "-created_at"]


class GuaranteeExtension(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    guarantee = models.ForeignKey(BankGuarantee, on_delete=models.CASCADE, related_name="extensions")
    previous_expiry_date = models.DateField()
    new_expiry_date = models.DateField()
    previous_claim_expiry_date = models.DateField(null=True, blank=True)
    new_claim_expiry_date = models.DateField(null=True, blank=True)
    extension_charges = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    bank_advice_ref = models.CharField(max_length=120, blank=True)
    reason = models.CharField(max_length=255)
    charge_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]


class GuaranteeClaim(models.Model):
    class DisputeStatus(models.TextChoices):
        RECEIVED = "RECEIVED", "Notice Received"
        UNDER_REVIEW = "UNDER_REVIEW", "Under Assessment"
        DISPUTED = "DISPUTED", "Disputed"
        ACCEPTED_PARTIAL = "ACCEPTED_PARTIAL", "Partially Accepted"
        ACCEPTED_FULL = "ACCEPTED_FULL", "Fully Invoked & Settled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    guarantee = models.ForeignKey(BankGuarantee, on_delete=models.CASCADE, related_name="claims")
    claim_notice_date = models.DateField()
    claiming_beneficiary = models.CharField(max_length=200)
    claimed_amount = models.DecimalField(max_digits=18, decimal_places=2)
    accepted_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    recovery_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    dispute_status = models.CharField(max_length=24, choices=DisputeStatus.choices, default=DisputeStatus.RECEIVED)
    claim_reason = models.TextField(blank=True)
    bank_response = models.TextField(blank=True)
    settlement_date = models.DateField(null=True, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)


class GuaranteeRelease(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    guarantee = models.OneToOneField(BankGuarantee, on_delete=models.CASCADE, related_name="release_record")
    release_type = models.CharField(max_length=32, default="FORMAL_RELEASE")  # PRE_ISSUE_CANCEL | EXPIRY_DISCHARGE | FORMAL_RELEASE | BANK_REVOCATION
    beneficiary_discharge_ref = models.CharField(max_length=120)
    bank_release_confirmation_ref = models.CharField(max_length=120)
    release_date = models.DateField()
    margin_refunded_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    margin_release_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    notes = models.TextField(blank=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)


class GuaranteeDocument(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    guarantee = models.ForeignKey(BankGuarantee, on_delete=models.CASCADE, related_name="documents")
    doc_category = models.CharField(max_length=40, default="ORIGINAL_BG")  # ORIGINAL_BG | APPLICATION | SANCTION | AMENDMENT | EXTENSION | RELEASE_LETTER | CLAIM_NOTICE | MARGIN_ADVICE
    version_no = models.PositiveSmallIntegerField(default=1)
    title = models.CharField(max_length=200)
    document_ref = models.CharField(max_length=120, blank=True)
    file_name = models.CharField(max_length=255, blank=True)
    uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-uploaded_at"]


class CollateralValuation(models.Model):
    """Immutable historical valuation record for collateral assets."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    collateral = models.ForeignKey(LoanCollateral, on_delete=models.CASCADE, related_name="valuations")
    valuation_date = models.DateField()
    valuer_name = models.CharField(max_length=150)
    valuation_report_no = models.CharField(max_length=80, blank=True)
    market_value = models.DecimalField(max_digits=18, decimal_places=2)
    forced_sale_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    haircut_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("25.00"))
    eligible_security_value = models.DecimalField(max_digits=18, decimal_places=2)
    next_valuation_date = models.DateField(null=True, blank=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-valuation_date", "-created_at"]


class FacilityCollateralLink(models.Model):
    """Shared M2M collateral allocation preventing silent double counting across loans/BGs."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    collateral = models.ForeignKey(LoanCollateral, on_delete=models.CASCADE, related_name="allocations")
    facility = models.ForeignKey(BankFacility, on_delete=models.CASCADE, null=True, blank=True, related_name="collateral_links")
    guarantee = models.ForeignKey(BankGuarantee, on_delete=models.CASCADE, null=True, blank=True, related_name="collateral_links")
    allocated_value = models.DecimalField(max_digits=18, decimal_places=2)
    charge_rank = models.CharField(max_length=32, default="FIRST_PARI_PASSU")
    charge_ref = models.CharField(max_length=120, blank=True)
    is_released = models.BooleanField(default=False)
    released_at = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)


class CollateralRelease(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    collateral = models.ForeignKey(LoanCollateral, on_delete=models.CASCADE, related_name="release_records")
    release_date = models.DateField()
    discharge_ref = models.CharField(max_length=120)
    is_partial = models.BooleanField(default=False)
    notes = models.TextField(blank=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)


