import uuid
from decimal import Decimal
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models

from apps.localization.bs_calendar import ad_to_bs
from .coa import Account, BoqItem, CostCategory, CostCenter, Department, EquipmentAsset, WorkPackage
from .parties import Party
from .voucher_config import VoucherClass, VoucherTypeConfig


class VoucherSequence(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.CASCADE)
    voucher_type = models.CharField(max_length=48)
    series_code = models.CharField(max_length=24, default="DEFAULT")
    period_tag = models.CharField(max_length=16, default="FY")
    last_number = models.PositiveIntegerField(default=0)

    class Meta:
        unique_together = [("company", "fiscal_year", "voucher_type", "series_code", "period_tag")]


class Voucher(models.Model):
    class VoucherType(models.TextChoices):
        # A. Primary Accounting Vouchers (20)
        PAYMENT = "PAYMENT", "Payment Voucher (F5)"
        RECEIPT = "RECEIPT", "Receipt Voucher (F6)"
        JOURNAL = "JOURNAL", "Journal Voucher (F7)"
        CONTRA = "CONTRA", "Contra Voucher (F4)"
        PURCHASE = "PURCHASE", "Purchase Voucher (F9)"
        SALES = "SALES", "Sales Voucher / Invoice (F8)"
        DEBIT_NOTE = "DEBIT_NOTE", "Debit Note"
        CREDIT_NOTE = "CREDIT_NOTE", "Credit Note"
        OPENING_BALANCE = "OPENING_BALANCE", "Opening Balance Voucher"
        DEPRECIATION = "DEPRECIATION", "Depreciation Voucher"
        PROVISION = "PROVISION", "Provisions Voucher"
        ACCRUAL = "ACCRUAL", "Accrual Voucher"
        REVERSAL = "REVERSAL", "Reversal Voucher"
        YEAR_END_CLOSING = "YEAR_END_CLOSING", "Year-End Closing Voucher"
        RECTIFICATION = "RECTIFICATION", "Rectification Voucher"
        FX_ADJUSTMENT = "FX_ADJUSTMENT", "Foreign Exchange Adjustment"
        BANK_INTEREST = "BANK_INTEREST", "Bank Interest Voucher"
        LOAN_DISBURSEMENT = "LOAN_DISBURSEMENT", "Loan Disbursement Voucher"
        LOAN_REPAYMENT = "LOAN_REPAYMENT", "Loan Repayment Voucher"
        PAYROLL = "PAYROLL", "Payroll Voucher"

        # B. Construction-Specific Financial Vouchers (22)
        MATERIAL_PURCHASE = "MATERIAL_PURCHASE", "Material Purchase Voucher"
        SITE_PURCHASE = "SITE_PURCHASE", "Site Purchase Voucher"
        DIRECT_EXPENSE = "DIRECT_EXPENSE", "Direct Project Expense Voucher"
        INDIRECT_EXPENSE = "INDIRECT_EXPENSE", "Indirect / Admin Expense Voucher"
        LABOR_PAYMENT = "LABOR_PAYMENT", "Contractor & Labor Payment"
        WAGES = "WAGES", "Daily & Monthly Wages Voucher"
        SUBCONTRACTOR_BILL = "SUBCONTRACTOR_BILL", "Subcontractor RA Bill"
        CLIENT_RA_BILL = "CLIENT_RA_BILL", "Client Running Account (RA) Bill"
        MOBILIZATION_ADVANCE = "MOBILIZATION_ADVANCE", "Mobilization Advance Voucher"
        ADVANCE_RECOVERY = "ADVANCE_RECOVERY", "Advance Recovery Voucher"
        RETENTION = "RETENTION", "Retention Payable / Receivable"
        VARIATION_ORDER = "VARIATION_ORDER", "Variation Order Financial Impact"
        EQUIPMENT_HIRE = "EQUIPMENT_HIRE", "Equipment Hire & Rental"
        MACHINE_INCOME = "MACHINE_INCOME", "Machine & Equipment Income"
        FUEL_EXPENSE = "FUEL_EXPENSE", "Fuel & Machinery Operating Expense"
        SITE_PETTY_CASH = "SITE_PETTY_CASH", "Site Petty Cash Expense"
        STAFF_ADVANCE = "STAFF_ADVANCE", "Staff Advance Voucher"
        STAFF_SETTLEMENT = "STAFF_SETTLEMENT", "Staff Advance Settlement"
        MATERIAL_ISSUE = "MATERIAL_ISSUE", "Material Issue (Site)"
        MATERIAL_CONSUMPTION = "MATERIAL_CONSUMPTION", "Material Consumption / Site Issue"
        PROJECT_COST_TRANSFER = "PROJECT_COST_TRANSFER", "Project Cost Transfer"
        WIP_ADJUSTMENT = "WIP_ADJUSTMENT", "Work-in-Progress (WIP) Voucher"
        ASSET_ACQUISITION = "ASSET_ACQUISITION", "Fixed Asset / Machinery Acquisition"
        ASSET_DISPOSAL = "ASSET_DISPOSAL", "Asset Disposal Voucher"
        SITE_EXPENSE = "SITE_EXPENSE", "Site Expense Voucher"
        SITE_CASH = "SITE_CASH", "Site Cash Transaction"
        MATERIAL_RETURN = "MATERIAL_RETURN", "Material Return Voucher"
        WAGE_ACCRUAL = "WAGE_ACCRUAL", "Wage Accrual Voucher"
        RETENTION_RECEIVABLE = "RETENTION_RECEIVABLE", "Retention Receivable Voucher"
        RETENTION_PAYABLE = "RETENTION_PAYABLE", "Retention Payable Voucher"
        FUEL = "FUEL", "Fuel & Vehicle Expense"

        # C. Provisional & Tally Inventory / Order Vouchers
        MEMORANDUM = "MEMORANDUM", "Memorandum Voucher (Temporary)"
        OPTIONAL = "OPTIONAL", "Optional Voucher (Scenario)"
        POST_DATED = "POST_DATED", "Post-Dated Voucher"
        REVERSING_JOURNAL = "REVERSING_JOURNAL", "Reversing Journal"
        PURCHASE_ORDER = "PURCHASE_ORDER", "Purchase Order Voucher"
        SALES_ORDER = "SALES_ORDER", "Sales Order Voucher"
        RECEIPT_NOTE = "RECEIPT_NOTE", "Receipt Note / GRN"
        DELIVERY_NOTE = "DELIVERY_NOTE", "Delivery Note"
        REJECTIONS_IN = "REJECTIONS_IN", "Rejections In (Customer Return)"
        REJECTIONS_OUT = "REJECTIONS_OUT", "Rejections Out (Supplier Return)"
        STOCK_JOURNAL = "STOCK_JOURNAL", "Stock Journal (Transfer / Adjust)"
        PHYSICAL_STOCK = "PHYSICAL_STOCK", "Physical Stock Reconciliation"
        MATERIAL_IN = "MATERIAL_IN", "Material In (Job Work)"
        MATERIAL_OUT = "MATERIAL_OUT", "Material Out (Job Work)"
        MANUFACTURING_JOURNAL = "MANUFACTURING_JOURNAL", "Manufacturing Journal"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        OPTIONAL = "OPTIONAL", "Optional (Provisional)"
        MEMORANDUM = "MEMORANDUM", "Memorandum (Temporary)"
        POST_DATED = "POST_DATED", "Post-Dated (Future)"
        SUBMITTED = "SUBMITTED", "Submitted"
        UNDER_REVIEW = "UNDER_REVIEW", "Under Review"
        APPROVED = "APPROVED", "Approved"
        POSTED = "POSTED", "Posted"
        RETURNED = "RETURNED", "Returned"
        REJECTED = "REJECTED", "Rejected"
        CANCELLED = "CANCELLED", "Cancelled"
        REVERSED = "REVERSED", "Reversed"
        ON_HOLD = "ON_HOLD", "On Hold"

    class EntryMode(models.TextChoices):
        SINGLE_ENTRY = "SINGLE_ENTRY", "Single Entry Mode"
        DOUBLE_ENTRY = "DOUBLE_ENTRY", "Double Entry Mode"
        ITEM_INVOICE = "ITEM_INVOICE", "Item Invoice Mode"
        ACCOUNTING_INVOICE = "ACCOUNTING_INVOICE", "Accounting Invoice Mode"

    class ProvisionalKind(models.TextChoices):
        REGULAR = "REGULAR", "Regular Accounting Book Entry"
        OPTIONAL = "OPTIONAL", "Optional Voucher (Scenario Only)"
        MEMORANDUM = "MEMORANDUM", "Memorandum (Unposted Temp)"
        REVERSING_JOURNAL = "REVERSING_JOURNAL", "Reversing Journal"
        POST_DATED = "POST_DATED", "Post-Dated (Future Effective)"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="vouchers")
    branch = models.ForeignKey(
        "tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True, related_name="vouchers"
    )
    fiscal_year = models.ForeignKey(
        "tenancy.FiscalYear", on_delete=models.PROTECT, related_name="vouchers"
    )
    fiscal_period = models.ForeignKey(
        "tenancy.FiscalPeriod", on_delete=models.PROTECT, related_name="vouchers"
    )
    voucher_no = models.CharField(max_length=40, null=True, blank=True, default=None, db_index=True)
    voucher_type = models.CharField(max_length=48, choices=VoucherType.choices, db_index=True)
    voucher_type_config = models.ForeignKey(
        VoucherTypeConfig, on_delete=models.SET_NULL, null=True, blank=True, related_name="vouchers"
    )
    voucher_class = models.ForeignKey(
        VoucherClass, on_delete=models.SET_NULL, null=True, blank=True, related_name="vouchers"
    )
    entry_mode = models.CharField(max_length=24, choices=EntryMode.choices, default=EntryMode.DOUBLE_ENTRY)
    provisional_kind = models.CharField(
        max_length=20, choices=ProvisionalKind.choices, default=ProvisionalKind.REGULAR, db_index=True
    )
    effective_date = models.DateField(null=True, blank=True)
    reverse_on_date = models.DateField(null=True, blank=True)
    converted_from = models.ForeignKey(
        "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="converted_vouchers"
    )
    single_entry_account = models.ForeignKey(
        Account, on_delete=models.PROTECT, null=True, blank=True, related_name="single_entry_vouchers"
    )
    bill_wise_allocations_payload = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    voucher_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    due_date = models.DateField(null=True, blank=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, related_name="vouchers"
    )
    site = models.ForeignKey(
        "projects.Site", on_delete=models.PROTECT, null=True, blank=True, related_name="vouchers"
    )
    department = models.ForeignKey(
        Department, on_delete=models.PROTECT, null=True, blank=True, related_name="vouchers"
    )
    cost_center = models.ForeignKey(
        CostCenter, on_delete=models.PROTECT, null=True, blank=True, related_name="vouchers"
    )
    party = models.ForeignKey(
        Party, on_delete=models.PROTECT, null=True, blank=True, related_name="vouchers"
    )
    party_name = models.CharField(max_length=200, blank=True)
    party_pan = models.CharField(max_length=20, blank=True)
    supplier_invoice_no = models.CharField(max_length=64, blank=True, db_index=True)
    supplier_invoice_date = models.DateField(null=True, blank=True)
    reference_no = models.CharField(max_length=64, blank=True)
    narration = models.TextField(blank=True)

    # Commercial / Construction tax & retention summaries
    gross_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    discount_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tax_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tds_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    retention_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    advance_recovery_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    net_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))

    theme_code = models.CharField(max_length=32, default="TALLY_CLASSIC")
    is_control_override = models.BooleanField(default=False)
    override_reason = models.CharField(max_length=255, blank=True)
    operational_payload = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    logic_snapshot = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)

    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT, db_index=True)
    version = models.PositiveIntegerField(default=1)
    idempotency_key = models.CharField(max_length=128, null=True, blank=True)
    reversed_from = models.ForeignKey(
        "self", on_delete=models.PROTECT, null=True, blank=True, related_name="reversals"
    )

    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_vouchers"
    )
    assigned_reviewer = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="assigned_review_vouchers",
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="approved_vouchers",
    )
    posted_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="posted_vouchers",
    )
    posted_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-voucher_date", "-created_at"]
        indexes = [
            models.Index(fields=["company", "voucher_date"], name="idx_vch_cmp_dt"),
            models.Index(fields=["company", "voucher_type", "voucher_date"], name="idx_vch_cmp_type_dt"),
            models.Index(fields=["company", "status", "voucher_date"], name="idx_vch_cmp_stat_dt"),
            models.Index(fields=["company", "party", "voucher_date"], name="idx_vch_cmp_party_dt"),
            models.Index(fields=["company", "project", "voucher_date"], name="idx_vch_cmp_proj_dt"),
            models.Index(fields=["company", "created_by"], name="idx_vch_cmp_creator"),
            models.Index(fields=["company", "approved_by"], name="idx_vch_cmp_approver"),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "voucher_no"],
                name="uniq_company_voucher_no",
            ),
            models.UniqueConstraint(
                fields=["company", "idempotency_key"],
                name="uniq_company_voucher_idempotency",
            ),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            old_status = (
                Voucher.objects.filter(pk=self.pk).values_list("status", flat=True).first()
            )
            if old_status in (self.Status.POSTED, self.Status.REVERSED):
                if not (old_status == self.Status.POSTED and self.status == self.Status.REVERSED):
                    raise ValidationError("Posted or reversed vouchers cannot be modified.")
        if self.voucher_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.voucher_date).isoformat()
        if self.party and not self.party_name:
            self.party_name = self.party.name
        if self.party and not self.party_pan:
            self.party_pan = self.party.pan_vat_no
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        if self.status in (self.Status.POSTED, self.Status.REVERSED):
            raise ValidationError("Posted or reversed vouchers cannot be deleted.")
        return super().delete(*args, **kwargs)

    def __str__(self) -> str:
        return f"{self.voucher_no or 'DRAFT'} ({self.voucher_type})"


class VoucherLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    voucher = models.ForeignKey(Voucher, on_delete=models.CASCADE, related_name="lines")
    line_no = models.PositiveSmallIntegerField(default=1)
    account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="voucher_lines")
    party = models.ForeignKey(
        Party, on_delete=models.PROTECT, null=True, blank=True, related_name="voucher_lines"
    )
    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"))

    # Construction 12-dimension job costing
    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)
    department = models.ForeignKey(Department, on_delete=models.PROTECT, null=True, blank=True)
    cost_center = models.ForeignKey(CostCenter, on_delete=models.PROTECT, null=True, blank=True)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    boq_item = models.ForeignKey(BoqItem, on_delete=models.PROTECT, null=True, blank=True)
    work_package = models.ForeignKey(WorkPackage, on_delete=models.PROTECT, null=True, blank=True)
    work_activity = models.CharField(max_length=120, blank=True)
    contractor = models.ForeignKey(
        Party, on_delete=models.PROTECT, null=True, blank=True, related_name="contractor_voucher_lines"
    )
    equipment = models.ForeignKey(EquipmentAsset, on_delete=models.PROTECT, null=True, blank=True)
    employee_ref = models.CharField(max_length=80, blank=True)
    against_voucher = models.ForeignKey(
        Voucher, on_delete=models.PROTECT, null=True, blank=True, related_name="referenced_by_lines"
    )
    advance_record = models.ForeignKey(
        "accounting.AdvanceRecord", on_delete=models.PROTECT, null=True, blank=True, related_name="voucher_lines"
    )
    payroll_liability = models.ForeignKey(
        "accounting.PayrollLiability", on_delete=models.PROTECT, null=True, blank=True, related_name="voucher_lines"
    )
    staff_loan = models.ForeignKey(
        "accounting.StaffLoan", on_delete=models.PROTECT, null=True, blank=True, related_name="voucher_lines"
    )
    expense_scope = models.CharField(max_length=16, blank=True, default="")  # HEAD_OFFICE | PROJECT

    # Itemized qty/rate & tax metadata
    quantity = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    unit = models.CharField(max_length=24, blank=True)
    unit_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    tax_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    tds_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    retention_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    bill_ref = models.CharField(max_length=64, blank=True, default="", db_default="")
    due_date = models.DateField(null=True, blank=True)
    is_auto_generated = models.BooleanField(default=False)
    description = models.CharField(max_length=255, blank=True)

    class Meta:
        ordering = ["line_no"]

    def clean(self):
        if self.debit < 0 or self.credit < 0:
            raise ValidationError("Debit and credit amounts must be non-negative.")
        if self.debit > 0 and self.credit > 0:
            raise ValidationError("A voucher line cannot have both debit and credit > 0.")
        if self.debit == 0 and self.credit == 0:
            raise ValidationError("A voucher line must have either a debit or a credit amount.")


class LedgerEntry(models.Model):
    """Append-only authoritative double-entry ledger record created exclusively by PostingService."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.PROTECT, related_name="ledger_entries"
    )
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT)
    fiscal_period = models.ForeignKey("tenancy.FiscalPeriod", on_delete=models.PROTECT)
    voucher = models.ForeignKey(Voucher, on_delete=models.PROTECT, related_name="ledger_entries")
    voucher_line = models.OneToOneField(
        VoucherLine, on_delete=models.PROTECT, related_name="ledger_entry"
    )
    account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="ledger_entries")
    party = models.ForeignKey(
        Party, on_delete=models.PROTECT, null=True, blank=True, related_name="gl_entries"
    )

    posting_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    transaction_currency = models.CharField(max_length=3, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))

    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"))
    base_debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    base_credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))

    project = models.ForeignKey(
        "projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="ledger_entries"
    )
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    department = models.ForeignKey(Department, on_delete=models.PROTECT, null=True, blank=True)
    cost_center = models.ForeignKey(CostCenter, on_delete=models.PROTECT, null=True, blank=True)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    boq_item = models.ForeignKey(BoqItem, on_delete=models.PROTECT, null=True, blank=True)
    work_package = models.ForeignKey(WorkPackage, on_delete=models.PROTECT, null=True, blank=True)
    work_activity = models.CharField(max_length=120, blank=True)
    contractor = models.ForeignKey(
        Party, on_delete=models.PROTECT, null=True, blank=True, related_name="contractor_gl_entries"
    )
    equipment = models.ForeignKey(EquipmentAsset, on_delete=models.PROTECT, null=True, blank=True)
    employee_ref = models.CharField(max_length=80, blank=True)
    narration = models.TextField(blank=True)
    posted_at = models.DateTimeField(db_index=True)

    class Meta:
        ordering = ["posting_date", "posted_at", "id"]
        indexes = [
            models.Index(fields=["company", "fiscal_year", "posting_date"], name="idx_gl_cmp_fy_dt"),
            models.Index(fields=["company", "account", "posting_date"], name="idx_gl_cmp_acc_dt"),
            models.Index(fields=["company", "project", "posting_date"], name="idx_gl_cmp_proj_dt"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            raise PermissionError("LedgerEntry records are immutable and cannot be updated.")
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        raise PermissionError("LedgerEntry records are immutable and cannot be deleted.")


class VoucherApprovalStep(models.Model):
    """Multi-stage maker-checker approval, review, return, hold, and rejection trail."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    voucher = models.ForeignKey(Voucher, on_delete=models.CASCADE, related_name="approval_steps")
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    action = models.CharField(max_length=24)  # SUBMITTED | UNDER_REVIEW | APPROVED | RETURNED | REJECTED | ON_HOLD | CANCELLED | POSTED
    comment = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "voucher_approvals"
        ordering = ["created_at"]


class VoucherAttachment(models.Model):
    """Supporting invoice/bill metadata and encrypted file reference attached to a voucher."""

    class Category(models.TextChoices):
        PDF_INVOICE = "PDF_INVOICE", "PDF Invoice"
        SUPPLIER_BILL = "SUPPLIER_BILL", "Supplier Bill"
        CUSTOMER_INVOICE = "CUSTOMER_INVOICE", "Customer Invoice"
        BANK_DEPOSIT_SLIP = "BANK_DEPOSIT_SLIP", "Bank Deposit Slip"
        CHEQUE_COPY = "CHEQUE_COPY", "Cheque Copy"
        MATERIAL_RECEIPT = "MATERIAL_RECEIPT", "Material Receipt / GRN"
        PROJECT_APPROVAL = "PROJECT_APPROVAL", "Project Approval"
        WORK_COMPLETION_CERT = "WORK_COMPLETION_CERT", "Work Completion Certificate"
        PHOTOGRAPH = "PHOTOGRAPH", "Supporting Photograph"
        OTHER = "OTHER", "Other Supporting Document"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    voucher = models.ForeignKey(Voucher, on_delete=models.CASCADE, related_name="attachments")
    category = models.CharField(max_length=28, choices=Category.choices, default=Category.OTHER)
    title = models.CharField(max_length=160)
    file_name = models.CharField(max_length=180)
    file_ref = models.CharField(max_length=255, blank=True)
    storage_key = models.CharField(max_length=255, blank=True)
    mime_type = models.CharField(max_length=120, blank=True)
    file_size_bytes = models.PositiveIntegerField(default=0)
    sha256_hash = models.CharField(max_length=64, blank=True)
    version = models.PositiveIntegerField(default=1)
    is_active = models.BooleanField(default=True)
    replaces = models.ForeignKey(
        "self",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="replaced_by_versions",
    )
    notes = 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:
        db_table = "voucher_attachments"
        ordering = ["-version", "uploaded_at"]

    def delete(self, *args, **kwargs):
        if self.voucher.status in (Voucher.Status.POSTED, Voucher.Status.REVERSED):
            raise ValidationError("Supporting files cannot be deleted from posted or reversed vouchers.")
        return super().delete(*args, **kwargs)


class VoucherThemeConfig(models.Model):
    """Configurable UI theme studio preset per company / branch / voucher_type / user."""

    class ThemeCode(models.TextChoices):
        TALLY_CLASSIC = "TALLY_CLASSIC", "Tally Classic"
        ENTERPRISE_MODERN = "ENTERPRISE_MODERN", "Enterprise Modern"
        CONSTRUCTION_SITE = "CONSTRUCTION_SITE", "Construction Site"
        MATERIAL_INVENTORY = "MATERIAL_INVENTORY", "Material & Inventory"
        CONTRACTOR_JOBWORK = "CONTRACTOR_JOBWORK", "Contractor & Job Work"
        BANKING_TREASURY = "BANKING_TREASURY", "Banking & Treasury"
        PAYROLL_HR = "PAYROLL_HR", "Payroll and HR"
        COMPACT_ENTRY = "COMPACT_ENTRY", "Compact Data Entry"
        FORMAL_PRINT = "FORMAL_PRINT", "Formal Print Theme"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="voucher_themes")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
    voucher_type = models.CharField(max_length=48, default="ALL")
    theme_code = models.CharField(max_length=32, choices=ThemeCode.choices, default=ThemeCode.TALLY_CLASSIC)
    name = models.CharField(max_length=120, default="Company Default Theme")
    accent_color = models.CharField(max_length=16, default="#0f766e")
    header_bg = models.CharField(max_length=24, default="#0f172a")
    density = models.CharField(max_length=16, default="compact")  # compact | comfortable | spacious
    border_radius = models.CharField(max_length=16, default="rounded-lg")
    font_style = models.CharField(max_length=40, default="Inter, sans-serif")
    icon_name = models.CharField(max_length=40, default="Layers")
    spacing_scale = models.CharField(max_length=16, default="normal")
    header_style = models.CharField(max_length=24, default="gradient")
    card_style = models.CharField(max_length=24, default="elevated")
    typography_config = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    color_tokens = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    visible_columns = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    visible_sections = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    default_fields = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    keyboard_shortcuts_enabled = models.BooleanField(default=True)
    is_default = models.BooleanField(default=False)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "voucher_templates"
        ordering = ["-is_default", "voucher_type"]


class VoucherReference(models.Model):
    """Stores invoice, payroll, advance, or loan references attached to a voucher for multi-bill allocation."""

    class ReferenceKind(models.TextChoices):
        SUPPLIER_INVOICE = "SUPPLIER_INVOICE", "Supplier Invoice"
        CUSTOMER_INVOICE = "CUSTOMER_INVOICE", "Customer Invoice"
        EMPLOYEE_ADVANCE = "EMPLOYEE_ADVANCE", "Employee Advance"
        SUPPLIER_ADVANCE = "SUPPLIER_ADVANCE", "Supplier Advance"
        CUSTOMER_ADVANCE = "CUSTOMER_ADVANCE", "Customer Advance"
        MOBILIZATION_ADVANCE = "MOBILIZATION_ADVANCE", "Mobilization Advance"
        PAYROLL_LIABILITY = "PAYROLL_LIABILITY", "Payroll / Wages Payable"
        STAFF_LOAN = "STAFF_LOAN", "Staff Loan"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="voucher_references")
    voucher = models.ForeignKey(Voucher, on_delete=models.CASCADE, related_name="references")
    voucher_line = models.ForeignKey(
        VoucherLine, on_delete=models.CASCADE, null=True, blank=True, related_name="references"
    )
    reference_kind = models.CharField(max_length=28, choices=ReferenceKind.choices)
    party = models.ForeignKey(Party, on_delete=models.PROTECT, null=True, blank=True)
    against_voucher = models.ForeignKey(
        Voucher, on_delete=models.PROTECT, null=True, blank=True, related_name="allocated_references"
    )
    advance_record = models.ForeignKey(
        "accounting.AdvanceRecord", on_delete=models.PROTECT, null=True, blank=True, related_name="voucher_references"
    )
    payroll_liability = models.ForeignKey(
        "accounting.PayrollLiability", on_delete=models.PROTECT, null=True, blank=True, related_name="voucher_references"
    )
    staff_loan = models.ForeignKey(
        "accounting.StaffLoan", on_delete=models.PROTECT, null=True, blank=True, related_name="voucher_references"
    )
    allocated_amount = models.DecimalField(max_digits=18, decimal_places=2)
    notes = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "voucher_references"
        ordering = ["created_at"]


class VoucherLogicSnapshot(models.Model):
    """Immutable auditable record of server-side Logic View & rule validation state at submit/post."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    voucher = models.ForeignKey(Voucher, on_delete=models.CASCADE, related_name="logic_snapshots")
    stage = models.CharField(max_length=24, default="POSTED")  # PREVIEW | SUBMITTED | POSTED
    is_balanced = models.BooleanField(default=False)
    is_valid = models.BooleanField(default=False)
    snapshot_payload = models.JSONField(default=dict, encoder=DjangoJSONEncoder)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "voucher_logic_snapshots"
        ordering = ["-created_at"]


class VoucherLineCostAllocation(models.Model):
    """Multi-project / multi-cost-centre percentage or fixed amount split attached to a VoucherLine."""

    class AllocationMode(models.TextChoices):
        PERCENTAGE = "PERCENTAGE", "Percentage Split (%)"
        AMOUNT = "AMOUNT", "Fixed Amount Split"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    voucher_line = models.ForeignKey(VoucherLine, on_delete=models.CASCADE, related_name="cost_allocations")
    cost_category = models.ForeignKey(CostCategory, on_delete=models.PROTECT, null=True, blank=True)
    cost_center = models.ForeignKey(CostCenter, on_delete=models.PROTECT, related_name="line_allocations")
    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)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    boq_item = models.ForeignKey(BoqItem, on_delete=models.PROTECT, null=True, blank=True)
    allocation_mode = models.CharField(max_length=12, choices=AllocationMode.choices, default=AllocationMode.PERCENTAGE)
    percentage = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("100.00"))
    amount = models.DecimalField(max_digits=18, decimal_places=2)

    class Meta:
        db_table = "voucher_line_cost_allocations"


class VoucherLineInventoryItem(models.Model):
    """Item Invoice / Stock Voucher inventory rows linked to a Voucher and optionally a VoucherLine."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    voucher = models.ForeignKey(Voucher, on_delete=models.CASCADE, related_name="inventory_items")
    voucher_line = models.ForeignKey(VoucherLine, on_delete=models.SET_NULL, null=True, blank=True)
    item = models.ForeignKey("inventory.ItemMaster", on_delete=models.PROTECT)
    warehouse = models.ForeignKey("inventory.Warehouse", on_delete=models.PROTECT, null=True, blank=True)
    target_warehouse = models.ForeignKey(
        "inventory.Warehouse", on_delete=models.PROTECT, null=True, blank=True, related_name="incoming_voucher_items"
    )
    quantity = models.DecimalField(max_digits=14, decimal_places=3)
    unit = models.CharField(max_length=24, blank=True)
    rate = models.DecimalField(max_digits=14, decimal_places=2)
    discount_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    tax_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    amount = models.DecimalField(max_digits=18, decimal_places=2)

    class Meta:
        db_table = "voucher_line_inventory_items"


class VoucherRevision(models.Model):
    """Modification history comparing original vs edited unposted/draft voucher payloads."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    voucher = models.ForeignKey(Voucher, on_delete=models.CASCADE, related_name="revisions")
    version = models.PositiveIntegerField(default=1)
    changed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    change_summary = models.CharField(max_length=255)
    previous_payload = models.JSONField(default=dict, encoder=DjangoJSONEncoder)
    new_payload = models.JSONField(default=dict, encoder=DjangoJSONEncoder)
    changed_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "voucher_revisions"
        ordering = ["-changed_at"]


class ScenarioDefinition(models.Model):
    """Tally-style Scenario Analysis definition combining Actuals + Provisional voucher classes."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="scenarios")
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=120)
    include_actuals = models.BooleanField(default=True)
    include_optional = models.BooleanField(default=True)
    include_memorandum = models.BooleanField(default=False)
    include_reversing = models.BooleanField(default=True)
    include_post_dated = models.BooleanField(default=False)
    as_of_date = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

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


