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


class Bank(models.Model):
    class BankCategory(models.TextChoices):
        CLASS_A_COMMERCIAL = "CLASS_A_COMMERCIAL", "Class A — Commercial Bank"
        CLASS_B_DEVELOPMENT = "CLASS_B_DEVELOPMENT", "Class B — Development Bank"
        CLASS_C_FINANCE = "CLASS_C_FINANCE", "Class C — Finance Company"
        CLASS_D_MICROFINANCE = "CLASS_D_MICROFINANCE", "Class D — Microfinance"
        FOREIGN = "FOREIGN", "Permitted Foreign Bank"
        OTHER = "OTHER", "Other Financial Institution"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="banks")
    name = models.CharField(max_length=150)
    short_code = models.CharField(max_length=24)
    swift_code = models.CharField(max_length=16, blank=True)
    bank_category = models.CharField(
        max_length=24, choices=BankCategory.choices, default=BankCategory.CLASS_A_COMMERCIAL
    )
    nrb_institution_code = models.CharField(max_length=24, blank=True)
    nrb_source_date = models.CharField(max_length=24, blank=True)
    nrb_directory_version = models.CharField(max_length=40, blank=True)
    is_active = models.BooleanField(default=True)

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

    def __str__(self) -> str:
        return f"{self.short_code} — {self.name}"


class BankBranch(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    bank = models.ForeignKey(Bank, on_delete=models.CASCADE, related_name="branches")
    branch_code = models.CharField(max_length=24)
    name = models.CharField(max_length=150)
    address = models.CharField(max_length=255, blank=True)

    class Meta:
        unique_together = [("bank", "branch_code")]
        ordering = ["name"]

    def __str__(self) -> str:
        return f"{self.bank.short_code} / {self.name}"


class BankAccount(models.Model):
    class AccountType(models.TextChoices):
        CURRENT = "CURRENT", "Current Account"
        SAVINGS = "SAVINGS", "Savings Account"
        FIXED_DEPOSIT = "FIXED_DEPOSIT", "Fixed Deposit"
        CALL_DEPOSIT = "CALL_DEPOSIT", "Call Deposit"
        FOREIGN_CURRENCY = "FOREIGN_CURRENCY", "Foreign Currency Account"
        PROJECT_ACCOUNT = "PROJECT_ACCOUNT", "Project Bank Account"
        PAYROLL = "PAYROLL", "Payroll Account"
        COLLECTION = "COLLECTION", "Collection Account"
        ESCROW = "ESCROW", "Escrow Account"
        LOAN = "LOAN", "Loan Account"
        OD = "OD", "Overdraft (OD) Account"
        CC = "CC", "Cash Credit (CC) Account"

    class Purpose(models.TextChoices):
        GENERAL = "GENERAL", "General Operations"
        PROJECT_COLLECTION = "PROJECT_COLLECTION", "Project Collection"
        PROJECT_EXPENDITURE = "PROJECT_EXPENDITURE", "Project Expenditure"

    class Status(models.TextChoices):
        ACTIVE = "ACTIVE", "Active"
        FROZEN = "FROZEN", "Frozen"
        CLOSED = "CLOSED", "Closed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="bank_accounts"
    )
    bank_branch = models.ForeignKey(
        BankBranch, on_delete=models.PROTECT, related_name="bank_accounts"
    )
    branch = models.ForeignKey(
        "tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True
    )
    project = models.ForeignKey(
        "projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="bank_accounts"
    )
    account_code = models.CharField(max_length=32, blank=True)
    account_name = models.CharField(max_length=150)
    account_number_masked = models.CharField(max_length=32)
    account_number_encrypted = models.TextField()
    account_number_hash = models.CharField(max_length=64)
    account_type = models.CharField(max_length=20, choices=AccountType.choices, default=AccountType.CURRENT)
    purpose = models.CharField(max_length=24, choices=Purpose.choices, default=Purpose.GENERAL)
    currency = models.CharField(max_length=3, default="NPR")
    account_open_date = models.DateField(null=True, blank=True)
    cheque_facility_enabled = models.BooleanField(default=True)
    online_banking_ref = models.CharField(max_length=120, blank=True)
    gl_account = models.OneToOneField(
        "accounting.Account", on_delete=models.PROTECT, related_name="bank_account"
    )
    interest_income_ledger = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="interest_bank_accounts"
    )
    interest_receivable_ledger = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="interest_recv_bank_accounts"
    )
    bank_charge_ledger = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="charge_bank_accounts"
    )
    restricted_cash_ledger = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="restricted_bank_accounts"
    )
    fx_gain_ledger = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="fx_gain_bank_accounts"
    )
    fx_loss_ledger = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="fx_loss_bank_accounts"
    )
    recon_clearing_ledger = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="recon_clearing_bank_accounts"
    )
    account_owner_name = models.CharField(max_length=150, blank=True)
    bank_manager_name = models.CharField(max_length=150, blank=True)
    bank_contact_phone = models.CharField(max_length=64, blank=True)
    routing_details = models.CharField(max_length=255, blank=True)
    opening_balance = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=12, choices=Status.choices, default=Status.ACTIVE)
    closed_at = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self) -> str:
        return f"{self.account_name} ({self.account_number_masked})"


class BankAccountSignatory(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    bank_account = models.ForeignKey(BankAccount, on_delete=models.CASCADE, related_name="signatories")
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
    full_name = models.CharField(max_length=150)
    designation = models.CharField(max_length=100, blank=True)
    signing_limit_npr = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    joint_signature_required = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["full_name"]


class BankAccountDocument(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    bank_account = models.ForeignKey(BankAccount, on_delete=models.CASCADE, related_name="documents")
    doc_category = models.CharField(max_length=32, default="OPENING_FORM")  # OPENING_FORM | SIGNATORY_SPECIMEN | BANK_LETTER | STATEMENT_PDF | KYC
    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, null=True, blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)


class CashAccount(models.Model):
    class CashType(models.TextChoices):
        HEAD_OFFICE = "HEAD_OFFICE", "Head Office Cash"
        ADMINISTRATIVE = "ADMINISTRATIVE", "Administrative Cash"
        BRANCH = "BRANCH", "Branch Cash"
        SITE = "SITE", "Project Site Cash"
        PETTY = "PETTY", "Petty Cash"
        EMPLOYEE_CUSTODY = "EMPLOYEE_CUSTODY", "Employee Cash Custody"
        EMERGENCY = "EMERGENCY", "Emergency Cash"
        IMPREST = "IMPREST", "Imprest Cash"
        VEHICLE = "VEHICLE", "Vehicle Cash"
        FOREIGN_CURRENCY = "FOREIGN_CURRENCY", "Foreign Currency Cash"
        TEMPORARY_FUND = "TEMPORARY_FUND", "Temporary Cash Fund"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="cash_accounts"
    )
    branch = models.ForeignKey(
        "tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True
    )
    project = models.ForeignKey(
        "projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="cash_accounts"
    )
    site = models.ForeignKey(
        "projects.Site", on_delete=models.PROTECT, null=True, blank=True
    )
    custodian = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="cash_custodies"
    )
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=150)
    cash_type = models.CharField(max_length=20, choices=CashType.choices, default=CashType.HEAD_OFFICE)
    currency = models.CharField(max_length=3, default="NPR")
    imprest_limit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    opening_float = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    replenishment_level = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    max_holding_limit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    gl_account = models.OneToOneField(
        "accounting.Account", on_delete=models.PROTECT, related_name="cash_account"
    )
    is_frozen = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

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

    def __str__(self) -> str:
        return f"{self.code} — {self.name}"


class CashTransfer(models.Model):
    class TransferType(models.TextChoices):
        CASH_TO_BANK = "CASH_TO_BANK", "Cash Deposit to Bank"
        BANK_TO_CASH = "BANK_TO_CASH", "Bank Withdrawal to Cash"
        BANK_TO_BANK = "BANK_TO_BANK", "Bank to Bank Transfer"
        CASH_TO_CASH = "CASH_TO_CASH", "Cash to Cash Transfer"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    transfer_type = models.CharField(max_length=20, choices=TransferType.choices)
    transfer_date = models.DateField()
    from_gl_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, related_name="outgoing_transfers"
    )
    to_gl_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, related_name="incoming_transfers"
    )
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    fee_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    transfer_ref = models.CharField(max_length=64, blank=True, db_index=True)
    currency = models.CharField(max_length=3, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    narration = models.TextField(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 CashCountReconciliation(models.Model):
    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending Approval"
        APPROVED = "APPROVED", "Approved & Posted"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    cash_account = models.ForeignKey(CashAccount, on_delete=models.CASCADE, related_name="counts")
    count_date = models.DateField()
    book_balance = models.DecimalField(max_digits=18, decimal_places=2)
    physical_balance = models.DecimalField(max_digits=18, decimal_places=2)
    variance = models.DecimalField(max_digits=18, decimal_places=2)  # physical - book (+ excess, - shortage)
    denominations = models.JSONField(default=dict, blank=True)
    is_surprise_check = models.BooleanField(default=False)
    attachment_ref = models.CharField(max_length=255, blank=True)
    notes = models.TextField(blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True)
    counted_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="cash_counts"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_cash_counts"
    )
    created_at = models.DateTimeField(auto_now_add=True)


class ImprestAdvance(models.Model):
    class Status(models.TextChoices):
        REQUESTED = "REQUESTED", "Requested"
        MANAGER_APPROVED = "MANAGER_APPROVED", "Manager Approved"
        FINANCE_APPROVED = "FINANCE_APPROVED", "Finance Authorized"
        ISSUED = "ISSUED", "Issued to Custodian"
        PARTIALLY_SETTLED = "PARTIALLY_SETTLED", "Partially Settled"
        SETTLED = "SETTLED", "Fully Settled"
        REJECTED = "REJECTED", "Rejected"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="imprest_advances")
    imprest_no = models.CharField(max_length=40)
    cash_account = models.ForeignKey(CashAccount, on_delete=models.PROTECT, related_name="imprests")
    funding_gl_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, related_name="imprest_funding_sources", null=True, blank=True
    )
    imprest_gl_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, related_name="imprest_receivables"
    )
    custodian = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="imprest_custodies"
    )
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    purpose = models.CharField(max_length=255, blank=True)
    request_date = models.DateField()
    due_date = models.DateField(null=True, blank=True)
    approved_limit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    issued_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    settled_expense_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    returned_cash_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.REQUESTED, db_index=True)
    issue_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="imprest_issues"
    )
    manager_approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    finance_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:
        unique_together = [("company", "imprest_no")]
        ordering = ["-request_date", "-created_at"]

    @property
    def outstanding_balance(self) -> Decimal:
        return max(
            Decimal("0.00"),
            self.issued_amount - self.settled_expense_amount - self.returned_cash_amount,
        )


class ImprestSettlement(models.Model):
    class Status(models.TextChoices):
        SUBMITTED = "SUBMITTED", "Submitted Bills"
        APPROVED = "APPROVED", "Verified & Settled"
        REJECTED = "REJECTED", "Rejected"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    imprest = models.ForeignKey(ImprestAdvance, on_delete=models.CASCADE, related_name="settlements")
    settlement_date = models.DateField()
    expense_lines = models.JSONField(default=list, blank=True)  # [{account_id, project_id, site_id, description, bill_ref, amount}]
    verified_expense_total = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    unused_cash_returned = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    return_to_gl_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    replenish_requested = models.BooleanField(default=False)
    replenished_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    settlement_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="imprest_settlement_vouchers"
    )
    return_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="imprest_return_vouchers"
    )
    replenishment_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="imprest_replenishment_vouchers"
    )
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.SUBMITTED)
    submitted_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="+"
    )
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

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


class CashCustodyHandover(models.Model):
    class Status(models.TextChoices):
        PENDING_ACCEPTANCE = "PENDING_ACCEPTANCE", "Pending Receiver Confirmation"
        COMPLETED = "COMPLETED", "Handover Completed"
        REJECTED = "REJECTED", "Disputed / Rejected"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    cash_account = models.ForeignKey(CashAccount, on_delete=models.CASCADE, related_name="handovers")
    handover_date = models.DateField()
    from_custodian = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="cash_handovers_out")
    to_custodian = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="cash_handovers_in")
    physical_amount = models.DecimalField(max_digits=18, decimal_places=2)
    denominations = models.JSONField(default=dict, blank=True)
    certificate_no = models.CharField(max_length=48, blank=True)
    notes = models.TextField(blank=True)
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.PENDING_ACCEPTANCE)
    confirmed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    confirmed_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)


class ChequeBook(models.Model):
    class BookStatus(models.TextChoices):
        ACTIVE = "ACTIVE", "Active"
        EXHAUSTED = "EXHAUSTED", "Exhausted"
        SUSPENDED = "SUSPENDED", "Suspended"
        CANCELLED = "CANCELLED", "Cancelled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    bank_account = models.ForeignKey(
        BankAccount, on_delete=models.CASCADE, related_name="cheque_books"
    )
    book_code = models.CharField(max_length=40)
    bank_book_number = models.CharField(max_length=64, blank=True)
    prefix = models.CharField(max_length=16, blank=True)
    start_number = models.PositiveIntegerField()
    end_number = models.PositiveIntegerField()
    issued_date = models.DateField()
    assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    low_stock_threshold = models.PositiveSmallIntegerField(default=5)
    status = models.CharField(max_length=16, choices=BookStatus.choices, default=BookStatus.ACTIVE)
    handover_notes = models.TextField(blank=True)
    last_handed_over_at = models.DateTimeField(null=True, blank=True)
    is_active = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = [("bank_account", "book_code")]


def normalize_cheque_number(raw: str) -> str:
    """Normalize cheque number for strict duplicate protection across company + bank account."""
    clean = "".join(ch for ch in (raw or "").strip().upper() if ch.isalnum() or ch in ("-", "/"))
    if clean.isdigit():
        return str(int(clean)).zfill(6)
    return clean


class ChequeLeaf(models.Model):
    class Direction(models.TextChoices):
        ISSUED = "ISSUED", "Issued Cheque"
        RECEIVED = "RECEIVED", "Received Cheque"

    class Status(models.TextChoices):
        AVAILABLE = "AVAILABLE", "Available"
        RESERVED = "RESERVED", "Reserved"
        PREPARED = "PREPARED", "Prepared"
        APPROVED = "APPROVED", "Approved"
        ISSUED = "ISSUED", "Issued"
        PRESENTED = "PRESENTED", "Presented at Bank"
        RECEIVED = "RECEIVED", "Received"
        VERIFIED = "VERIFIED", "Verified"
        DEPOSITED = "DEPOSITED", "Deposited"
        UNDER_CLEARING = "UNDER_CLEARING", "Under Clearing"
        IN_HAND = "IN_HAND", "Cheque in Hand"
        CLEARED = "CLEARED", "Cleared"
        BOUNCED = "BOUNCED", "Bounced"
        STOP_PAYMENT = "STOP_PAYMENT", "Stop Payment"
        STOPPED = "STOPPED", "Stopped"
        CANCELLED = "CANCELLED", "Cancelled"
        SKIPPED = "SKIPPED", "Skipped"
        LOST = "LOST", "Lost"
        DAMAGED = "DAMAGED", "Damaged"
        LOST_DAMAGED = "LOST_DAMAGED", "Lost / Damaged"
        STALE = "STALE", "Stale / Expired"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    bank_account = models.ForeignKey(
        BankAccount, on_delete=models.CASCADE, related_name="cheques"
    )
    cheque_book = models.ForeignKey(
        ChequeBook, on_delete=models.SET_NULL, null=True, blank=True, related_name="leaves"
    )
    cheque_number = models.CharField(max_length=32)
    normalized_cheque_number = models.CharField(max_length=40, blank=True, db_index=True)
    issued_unique_key = models.CharField(max_length=40, null=True, blank=True, db_index=True)
    direction = models.CharField(max_length=12, choices=Direction.choices, default=Direction.ISSUED)
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.AVAILABLE, db_index=True)
    party = models.ForeignKey("accounting.Party", on_delete=models.SET_NULL, null=True, blank=True)
    party_name = models.CharField(max_length=200, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    drawer_name = models.CharField(max_length=200, blank=True)
    drawer_bank = models.CharField(max_length=150, blank=True)
    drawer_account_ref = models.CharField(max_length=64, blank=True)
    purpose = models.CharField(max_length=200, blank=True)
    receiving_date = models.DateField(null=True, blank=True)
    deposit_date = models.DateField(null=True, blank=True)
    cheque_date = models.DateField(null=True, blank=True)
    expected_presentation_date = models.DateField(null=True, blank=True)
    cleared_date = models.DateField(null=True, blank=True)
    bounce_date = models.DateField(null=True, blank=True)
    amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    currency = models.CharField(max_length=3, default="NPR")
    signing_authority = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="signed_cheques"
    )
    voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="cheques"
    )
    reserved_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="reserved_cheques"
    )
    reserved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="reserved_cheque_leaves"
    )
    reserved_at = models.DateTimeField(null=True, blank=True)
    reservation_expires_at = models.DateTimeField(null=True, blank=True)
    clearing_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="cheque_clearings"
    )
    reversal_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="cheque_reversals"
    )
    bank_reconciled = models.BooleanField(default=False)
    image_ref = models.CharField(max_length=255, blank=True)
    bounce_reason = models.CharField(max_length=255, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        if not self.normalized_cheque_number and self.cheque_number:
            self.normalized_cheque_number = normalize_cheque_number(self.cheque_number)
        if self.direction == self.Direction.ISSUED and self.normalized_cheque_number:
            self.issued_unique_key = self.normalized_cheque_number
        else:
            self.issued_unique_key = None
        super().save(*args, **kwargs)

    class Meta:
        unique_together = [("bank_account", "cheque_number", "direction")]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "bank_account", "issued_unique_key"],
                name="uniq_issued_cheque_per_company_account",
            )
        ]
        ordering = ["cheque_number"]


class BankStatementTemplate(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="statement_templates")
    bank = models.ForeignKey(Bank, on_delete=models.CASCADE, null=True, blank=True)
    template_name = models.CharField(max_length=120)
    file_format = models.CharField(max_length=16, default="CSV")
    date_format = models.CharField(max_length=32, default="%Y-%m-%d")
    column_mapping = models.JSONField(default=dict, blank=True)
    is_active = models.BooleanField(default=True)


class BankStatementImport(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    bank_account = models.ForeignKey(
        BankAccount, on_delete=models.CASCADE, related_name="statement_imports"
    )
    file_name = models.CharField(max_length=255)
    file_format = models.CharField(max_length=16, default="CSV")
    statement_period_start = models.DateField(null=True, blank=True)
    statement_period_end = models.DateField(null=True, blank=True)
    imported_count = models.PositiveIntegerField(default=0)
    skipped_duplicates = models.PositiveIntegerField(default=0)
    imported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    imported_at = models.DateTimeField(auto_now_add=True)


class BankStatementLine(models.Model):
    class MatchStatus(models.TextChoices):
        UNMATCHED = "UNMATCHED", "Unmatched Bank"
        MATCHED = "MATCHED", "Matched"
        PARTIAL = "PARTIAL", "Partially Matched"
        PENDING_CHEQUE = "PENDING_CHEQUE", "Pending Cheque"
        DEPOSIT_IN_TRANSIT = "DEPOSIT_IN_TRANSIT", "Deposit in Transit"
        BANK_CHARGE = "BANK_CHARGE", "Bank Charges"
        BANK_INTEREST = "BANK_INTEREST", "Bank Interest"
        DUPLICATE = "DUPLICATE", "Duplicate"
        UNDER_REVIEW = "UNDER_REVIEW", "Under Review"
        FINALIZED = "FINALIZED", "Finalized"
        EXCLUDED = "EXCLUDED", "Excluded"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    bank_account = models.ForeignKey(
        BankAccount, on_delete=models.CASCADE, related_name="statement_lines"
    )
    statement_import = models.ForeignKey(
        BankStatementImport, on_delete=models.CASCADE, related_name="lines"
    )
    txn_date = models.DateField(db_index=True)
    value_date = models.DateField(null=True, blank=True)
    reference_no = models.CharField(max_length=80, blank=True)
    cheque_no = models.CharField(max_length=32, blank=True)
    description = models.CharField(max_length=255, blank=True)
    debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    balance = models.DecimalField(max_digits=18, decimal_places=2, null=True, blank=True)
    line_fingerprint = models.CharField(max_length=64)
    match_status = models.CharField(
        max_length=24, choices=MatchStatus.choices, default=MatchStatus.UNMATCHED, db_index=True
    )
    matched_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    match_confidence = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    match_reason = models.CharField(max_length=160, blank=True)
    supporting_doc_ref = models.CharField(max_length=255, blank=True)
    suggested_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True
    )

    class Meta:
        unique_together = [("bank_account", "line_fingerprint")]
        ordering = ["txn_date", "id"]


class ReconciliationMatch(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    statement_line = models.ForeignKey(
        BankStatementLine, on_delete=models.CASCADE, related_name="matches"
    )
    ledger_entry = models.ForeignKey(
        "accounting.LedgerEntry", on_delete=models.PROTECT, related_name="bank_matches"
    )
    matched_amount = models.DecimalField(max_digits=18, decimal_places=2)
    match_type = models.CharField(max_length=16, default="AUTO")  # AUTO | MANUAL | PARTIAL
    matched_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    matched_at = models.DateTimeField(auto_now_add=True)


class BankReconciliationSession(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "In Progress"
        APPROVED = "APPROVED", "Approved & Locked"
        REOPENED = "REOPENED", "Reopened for Review"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    bank_account = models.ForeignKey(
        BankAccount, on_delete=models.CASCADE, related_name="reconciliations"
    )
    period_start = models.DateField()
    period_end = models.DateField()
    statement_closing_balance = models.DecimalField(max_digits=18, decimal_places=2)
    book_closing_balance = models.DecimalField(max_digits=18, decimal_places=2)
    deposits_in_transit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    outstanding_cheques = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    other_reconciling_items = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    unreconciled_difference = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    is_opening_recon = models.BooleanField(default=False)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT)
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True
    )
    approved_at = models.DateTimeField(null=True, blank=True)
    reopen_reason = models.CharField(max_length=255, blank=True)
    reopened_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    reopened_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-period_end"]


class BankTransaction(models.Model):
    class TransactionKind(models.TextChoices):
        CASH_TO_BANK = "CASH_TO_BANK", "Cash Deposited to Bank (Contra)"
        BANK_TO_CASH = "BANK_TO_CASH", "Cash Withdrawn from Bank (Contra)"
        BANK_TO_BANK = "BANK_TO_BANK", "Bank-to-Bank Transfer (Contra)"
        BANK_TRANSFER_IN_TRANSIT = "BANK_TRANSFER_IN_TRANSIT", "Bank Transfer In-Transit (Contra)"
        INCOMING_TRANSFER_CONFIRMATION = "INCOMING_TRANSFER_CONFIRMATION", "Incoming Transfer Confirmation (Contra)"
        PAYMENT = "PAYMENT", "External Payment Voucher"
        RECEIPT = "RECEIPT", "Receipt Voucher"
        OTHER = "OTHER", "Other Bank Entry"

    class Method(models.TextChoices):
        CASH = "CASH", "Cash"
        CHEQUE = "CHEQUE", "Cheque"
        TRANSFER = "TRANSFER", "Bank Transfer"
        ELECTRONIC = "ELECTRONIC", "Electronic / IPS / RTGS"
        OTHER = "OTHER", "Other"

    class ReconStatus(models.TextChoices):
        UNRECONCILED = "UNRECONCILED", "Pending Reconciliation"
        RECONCILED = "RECONCILED", "Reconciled / Cleared"
        NOT_APPLICABLE = "NOT_APPLICABLE", "N/A"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="bank_transactions")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.SET_NULL, null=True, blank=True)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.SET_NULL, null=True, blank=True)
    voucher = models.OneToOneField(
        "accounting.Voucher", on_delete=models.CASCADE, related_name="bank_transaction_record"
    )
    transaction_kind = models.CharField(max_length=32, choices=TransactionKind.choices, db_index=True)
    method = models.CharField(max_length=16, choices=Method.choices, default=Method.TRANSFER, db_index=True)
    bank_account = models.ForeignKey(
        BankAccount, on_delete=models.PROTECT, null=True, blank=True, related_name="primary_bank_transactions"
    )
    counter_bank_account = models.ForeignKey(
        BankAccount, on_delete=models.PROTECT, null=True, blank=True, related_name="counter_bank_transactions"
    )
    cash_account = models.ForeignKey(
        CashAccount, on_delete=models.PROTECT, null=True, blank=True, related_name="bank_transactions"
    )
    cheque_leaf = models.ForeignKey(
        ChequeLeaf, on_delete=models.SET_NULL, null=True, blank=True, related_name="bank_transactions"
    )
    txn_date = models.DateField(db_index=True)
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    currency = models.CharField(max_length=3, default="NPR")
    reference_no = models.CharField(max_length=80, blank=True)
    payee_or_account = models.CharField(max_length=200, blank=True)
    narration = models.TextField(blank=True)
    debit_reconciliation_status = models.CharField(
        max_length=16, choices=ReconStatus.choices, default=ReconStatus.UNRECONCILED, db_index=True
    )
    credit_reconciliation_status = models.CharField(
        max_length=16, choices=ReconStatus.choices, default=ReconStatus.UNRECONCILED, db_index=True
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "bank_transactions"
        ordering = ["-txn_date", "-created_at"]


