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


class ARControlPolicy(models.Model):
    """Company-wide Sundry Debtors & Accounts Receivable governance & configuration policy."""

    class DSOMethod(models.TextChoices):
        AVG_RECEIVABLES = "AVG_RECEIVABLES", "Average Trade Receivables / Credit Sales × Period Days"
        CLOSING_AR = "CLOSING_AR", "Closing Trade Receivables / Credit Sales × Period Days"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.OneToOneField("tenancy.Company", on_delete=models.CASCADE, related_name="ar_control_policy")
    default_control_account = models.ForeignKey(
        "accounting.Account", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_policy_controls"
    )
    default_advance_account = models.ForeignKey(
        "accounting.Account", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_policy_advances"
    )
    default_retention_account = models.ForeignKey(
        "accounting.Account", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_policy_retentions"
    )
    default_tds_receivable_account = models.ForeignKey(
        "accounting.Account", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_policy_tds"
    )
    default_revenue_account = models.ForeignKey(
        "accounting.Account", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_policy_revenue"
    )
    default_vat_output_account = models.ForeignKey(
        "accounting.Account", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_policy_vat"
    )
    default_credit_days = models.PositiveSmallIntegerField(default=30)
    default_retention_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("5.00"))
    default_advance_recovery_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("10.00"))
    dso_method = models.CharField(max_length=24, choices=DSOMethod.choices, default=DSOMethod.AVG_RECEIVABLES)
    aging_buckets_json = models.JSONField(
        default=list,
        encoder=DjangoJSONEncoder,
        help_text="Ordered bucket boundaries, e.g. [0, 30, 60, 90, 180, 365]",
    )
    enforce_maker_checker_ra = models.BooleanField(default=True)
    block_over_credit_limit = models.BooleanField(default=True)
    include_unbilled_in_credit_exposure = models.BooleanField(default=False)
    auto_reminders_enabled = models.BooleanField(default=False)
    require_client_certification_before_posting = models.BooleanField(default=True)
    small_writeoff_threshold = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("5000.00"))
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "ar_control_policies"


class CustomerCreditOverride(models.Model):
    """Authorized temporary or capped credit-limit / hold override for a customer."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="credit_overrides")
    customer = models.ForeignKey("party_hub.CustomerProfile", on_delete=models.CASCADE, related_name="credit_overrides")
    override_limit = models.DecimalField(max_digits=18, decimal_places=2)
    reason = models.CharField(max_length=255)
    valid_until = models.DateField(null=True, blank=True)
    is_active = models.BooleanField(default=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="approved_credit_overrides")
    approved_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "ar_customer_credit_overrides"
        ordering = ["-approved_at"]


class CustomerCreditHoldLog(models.Model):
    """Immutable log of credit-hold placements, releases, and credit-limit changes."""

    class Action(models.TextChoices):
        HOLD_PLACED = "HOLD_PLACED", "Credit Hold Placed"
        HOLD_RELEASED = "HOLD_RELEASED", "Credit Hold Released"
        LIMIT_UPDATED = "LIMIT_UPDATED", "Credit Limit Updated"
        OVERRIDE_GRANTED = "OVERRIDE_GRANTED", "Temporary Credit Override Granted"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="credit_hold_logs")
    customer = models.ForeignKey("party_hub.CustomerProfile", on_delete=models.CASCADE, related_name="credit_hold_logs")
    action = models.CharField(max_length=24, choices=Action.choices)
    previous_value = models.CharField(max_length=120, blank=True)
    new_value = models.CharField(max_length=120, blank=True)
    reason = models.CharField(max_length=255)
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

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


class SalesInvoice(models.Model):
    """Pre-posting & Commercial Sales / Tax / Service / Milestone / Debit / Credit Note document."""

    class DocType(models.TextChoices):
        TAX_INVOICE = "TAX_INVOICE", "Tax Invoice (VAT)"
        COMMERCIAL_INVOICE = "COMMERCIAL_INVOICE", "Commercial / General Sales Invoice"
        SERVICE_INVOICE = "SERVICE_INVOICE", "Service / Consultancy Invoice"
        MILESTONE_INVOICE = "MILESTONE_INVOICE", "Contract Milestone Invoice"
        DEBIT_NOTE = "DEBIT_NOTE", "Customer Debit Note"
        CREDIT_NOTE = "CREDIT_NOTE", "Customer Credit Note"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        SUBMITTED = "SUBMITTED", "Submitted for Approval"
        APPROVED = "APPROVED", "Approved (Ready to Post)"
        POSTED = "POSTED", "Posted to GL & AR"
        PARTIAL = "PARTIAL", "Partially Paid"
        SETTLED = "SETTLED", "Settled / Closed"
        DISPUTED = "DISPUTED", "Disputed"
        CANCELLED = "CANCELLED", "Cancelled"
        REVERSED = "REVERSED", "Reversed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ar_sales_invoices")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT, null=True, blank=True)
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="ar_sales_invoices")
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="ar_sales_invoices")
    contract = models.ForeignKey("projects.ProjectContract", on_delete=models.PROTECT, null=True, blank=True, related_name="ar_sales_invoices")
    doc_type = models.CharField(max_length=24, choices=DocType.choices, default=DocType.TAX_INVOICE, db_index=True)
    invoice_no = models.CharField(max_length=48)
    invoice_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    due_date = models.DateField(db_index=True)
    currency_code = models.CharField(max_length=8, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))
    subtotal_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"))
    taxable_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    vat_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tds_withholding_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    revenue_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="ar_invoice_revenues")
    reference_invoice = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="adjustment_notes")
    voucher = models.OneToOneField("accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="ar_sales_invoice")
    open_item = models.OneToOneField("party_hub.OpenItem", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_sales_invoice")
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT, db_index=True)
    narration = models.TextField(blank=True)
    version = models.PositiveIntegerField(default=1)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_ar_invoices")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="approved_ar_invoices")
    posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="posted_ar_invoices")
    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:
        db_table = "ar_sales_invoices"
        unique_together = [("company", "invoice_no")]
        ordering = ["-invoice_date", "-created_at"]

    def save(self, *args, **kwargs):
        if self.invoice_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.invoice_date).isoformat()
        super().save(*args, **kwargs)


class SalesInvoiceLine(models.Model):
    """Line item for commercial sales, milestone, service, debit/credit note."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    invoice = models.ForeignKey(SalesInvoice, on_delete=models.CASCADE, related_name="lines")
    line_no = models.PositiveSmallIntegerField(default=1)
    item_code = models.CharField(max_length=40, blank=True)
    description = models.CharField(max_length=255)
    unit = models.CharField(max_length=24, default="Unit")
    quantity = models.DecimalField(max_digits=16, decimal_places=3, default=Decimal("1.000"))
    unit_rate = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    discount_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    tax_rate_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("13.00"))
    line_subtotal = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    vat_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    line_total = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    revenue_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, null=True, blank=True)
    cost_center = models.ForeignKey("accounting.CostCenter", on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "ar_sales_invoice_lines"
        ordering = ["line_no"]


class RABill(models.Model):
    """
    Construction Running Account (RA) Progress Bill.
    Remains outside GL & posted Trade Debtors until client certification & authorized AR posting.
    """

    class BillCategory(models.TextChoices):
        PROGRESS_RA = "PROGRESS_RA", "Running Account (RA) Progress Bill"
        INTERIM_VALUATION = "INTERIM_VALUATION", "Interim Payment Certificate (IPC)"
        VARIATION_CLAIM = "VARIATION_CLAIM", "Variation / Extra Work Claim"
        FINAL_BILL = "FINAL_BILL", "Final Contract Settlement Bill"

    class WorkflowStatus(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        MEASUREMENT_VERIFIED = "MEASUREMENT_VERIFIED", "Measurement Verified"
        ENGINEER_APPROVED = "ENGINEER_APPROVED", "Site Engineer Approved"
        PM_REVIEWED = "PM_REVIEWED", "Project Manager Reviewed"
        ACCOUNTS_REVIEWED = "ACCOUNTS_REVIEWED", "Accounts Reviewed"
        AUTHORIZED = "AUTHORIZED", "Authorized for Submission"
        SUBMITTED_TO_CLIENT = "SUBMITTED_TO_CLIENT", "Submitted to Client (Pending Certification)"
        PARTIALLY_CERTIFIED = "PARTIALLY_CERTIFIED", "Partially Certified by Client"
        CLIENT_CERTIFIED = "CLIENT_CERTIFIED", "Client Certified (Ready to Post)"
        POSTED = "POSTED", "Posted to AR & GL"
        PARTIALLY_RECEIVED = "PARTIALLY_RECEIVED", "Partially Received"
        SETTLED = "SETTLED", "Settled / Closed"
        DISPUTED = "DISPUTED", "Disputed"
        RETURNED = "RETURNED", "Returned for Revision"
        REJECTED = "REJECTED", "Rejected"
        SUPERSEDED = "SUPERSEDED", "Superseded"
        CANCELLED = "CANCELLED", "Cancelled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ra_bills")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT, null=True, blank=True)
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="ra_bills")
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, related_name="ra_bills")
    contract = models.ForeignKey("projects.ProjectContract", on_delete=models.PROTECT, related_name="ra_bills")
    boq_header = models.ForeignKey("projects.ProjectBoqHeader", on_delete=models.PROTECT, null=True, blank=True, related_name="ra_bills")
    previous_ra_bill = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="next_ra_bills")
    measurement_book = models.ForeignKey(
        "construction_ops.OperationalDocument", on_delete=models.SET_NULL, null=True, blank=True, related_name="linked_ra_bills"
    )
    bill_category = models.CharField(max_length=24, choices=BillCategory.choices, default=BillCategory.PROGRESS_RA)
    ra_number = models.CharField(max_length=48)
    ra_sequence_no = models.PositiveIntegerField(default=1)
    bill_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    period_from = models.DateField(null=True, blank=True)
    period_to = models.DateField(null=True, blank=True)
    due_date = models.DateField(db_index=True)
    currency_code = models.CharField(max_length=8, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))

    # Monetary figures (Submitted vs Certified)
    previous_cumulative_gross = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    current_gross_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    cumulative_gross_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    vat_rate_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("13.00"))
    vat_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    gross_with_vat = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_deductions = 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"))
    tds_deduction_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    other_deductions_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    net_receivable_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    certified_gross_amount = models.DecimalField(max_digits=18, decimal_places=2, null=True, blank=True)
    certified_net_amount = models.DecimalField(max_digits=18, decimal_places=2, null=True, blank=True)

    status = models.CharField(max_length=24, choices=WorkflowStatus.choices, default=WorkflowStatus.DRAFT, db_index=True)
    remarks = models.TextField(blank=True)
    return_reason = models.CharField(max_length=255, blank=True)
    version = models.PositiveIntegerField(default=1)

    # Maker-checker stage actors & timestamps
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_ra_bills")
    verified_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="verified_ra_bills")
    engineer_approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="engineer_ra_bills")
    pm_reviewed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="pm_ra_bills")
    accounts_reviewed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="accounts_ra_bills")
    authorized_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="authorized_ra_bills")
    posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="posted_ra_bills")
    posted_at = models.DateTimeField(null=True, blank=True)

    # Centralized accounting linkages (populated ONLY on post_to_ar)
    voucher = models.OneToOneField("accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="ra_bill")
    open_item = models.OneToOneField("party_hub.OpenItem", on_delete=models.SET_NULL, null=True, blank=True, related_name="ra_bill")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "ar_ra_bills"
        unique_together = [("company", "ra_number")]
        ordering = ["-bill_date", "-ra_sequence_no"]

    def save(self, *args, **kwargs):
        if self.bill_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.bill_date).isoformat()
        super().save(*args, **kwargs)


class RABillLine(models.Model):
    """BOQ-linked running account quantity & value progression line."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ra_bill = models.ForeignKey(RABill, on_delete=models.CASCADE, related_name="lines")
    boq_line = models.ForeignKey("projects.ProjectBoqLine", on_delete=models.PROTECT, null=True, blank=True, related_name="ra_bill_lines")
    variation_order = models.ForeignKey("projects.ProjectVariationOrder", on_delete=models.PROTECT, null=True, blank=True, related_name="ra_bill_lines")
    line_no = models.PositiveSmallIntegerField(default=1)
    item_code = models.CharField(max_length=40)
    description = models.CharField(max_length=255)
    unit = models.CharField(max_length=24, default="Cum")
    contract_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    contract_rate = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    previous_cumulative_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    current_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    cumulative_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    remaining_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    previous_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    current_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    cumulative_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    balance_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    is_variation_excess = models.BooleanField(default=False)
    measurement_ref = models.CharField(max_length=120, blank=True)

    class Meta:
        db_table = "ar_ra_bill_lines"
        ordering = ["line_no", "item_code"]


class RABillDeduction(models.Model):
    """Structured statutory & contractual deductions on an RA Bill."""

    class DeductionType(models.TextChoices):
        ADVANCE_RECOVERY = "ADVANCE_RECOVERY", "Mobilization Advance Recovery"
        RETENTION = "RETENTION", "Contract Retention Deduction"
        CLIENT_TDS = "CLIENT_TDS", "Client Withholding Tax (TDS)"
        MATERIAL_RECOVERY = "MATERIAL_RECOVERY", "Client-Supplied Material Recovery"
        PENALTY = "PENALTY", "Delay Penalty"
        LIQUIDATED_DAMAGES = "LIQUIDATED_DAMAGES", "Liquidated Damages (LD)"
        PERFORMANCE_DEDUCTION = "PERFORMANCE_DEDUCTION", "Performance / Quality Deduction"
        OTHER = "OTHER", "Other Contractual Deduction"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ra_bill = models.ForeignKey(RABill, on_delete=models.CASCADE, related_name="deductions")
    deduction_type = models.CharField(max_length=28, choices=DeductionType.choices)
    description = models.CharField(max_length=180, blank=True)
    base_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    rate_pct = models.DecimalField(max_digits=6, decimal_places=3, default=Decimal("0.000"))
    amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    gl_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, null=True, blank=True)
    advance_record = models.ForeignKey("accounting.AdvanceRecord", on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "ar_ra_bill_deductions"


class RABillCertification(models.Model):
    """Official client / engineer payment certificate details tied to an RA Bill."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ra_bill = models.ForeignKey(RABill, on_delete=models.CASCADE, related_name="certifications")
    certificate_no = models.CharField(max_length=64)
    certified_date = models.DateField()
    bs_certified_date = models.CharField(max_length=16, blank=True)
    certified_gross_amount = models.DecimalField(max_digits=18, decimal_places=2)
    certified_deductions_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    certified_net_amount = models.DecimalField(max_digits=18, decimal_places=2)
    certified_by_client_officer = models.CharField(max_length=120, blank=True)
    remarks = models.TextField(blank=True)
    supporting_doc_ref = models.CharField(max_length=255, blank=True)
    recorded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    recorded_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "ar_ra_bill_certifications"
        ordering = ["-certified_date", "-recorded_at"]

    def save(self, *args, **kwargs):
        if self.certified_date and not self.bs_certified_date:
            self.bs_certified_date = ad_to_bs(self.certified_date).isoformat()
        super().save(*args, **kwargs)


class MeasurementReference(models.Model):
    """Links an RA Bill / line back to Construction Measurement Book documents to prevent duplicate billing."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ar_measurement_refs")
    ra_bill = models.ForeignKey(RABill, on_delete=models.CASCADE, related_name="measurement_references")
    measurement_doc = models.ForeignKey("construction_ops.OperationalDocument", on_delete=models.PROTECT, related_name="ra_bill_references")
    mb_page_no = models.CharField(max_length=40, blank=True)
    verified_qty = models.DecimalField(max_digits=18, decimal_places=3, default=Decimal("0.000"))
    notes = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = "ar_measurement_references"
        unique_together = [("ra_bill", "measurement_doc")]


class CustomerReceipt(models.Model):
    """
    Commercial Customer Receipt wrapper over posted Receipt Voucher & OpenItem.
    Supports Cash, Bank Transfer, Two-Step Cheque Receipt (1035->1036), Online/QR, TDS Certificate, and Retention Release.
    """

    class ReceiptMode(models.TextChoices):
        CASH = "CASH", "Cash Receipt"
        BANK_TRANSFER = "BANK_TRANSFER", "Bank Transfer / IPS / ConnectIPS"
        CHEQUE = "CHEQUE", "Customer Cheque (Two-Step Clearing)"
        ONLINE = "ONLINE", "Electronic / Gateway Receipt"
        TDS_CERTIFICATE = "TDS_CERTIFICATE", "Withholding Tax (TDS) Certificate"
        ADVANCE = "ADVANCE", "Customer Mobilization / Advance Receipt"
        RETENTION_RELEASE = "RETENTION_RELEASE", "Retention Release Receipt"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        POSTED = "POSTED", "Posted (Open / Unallocated)"
        PARTIALLY_ALLOCATED = "PARTIALLY_ALLOCATED", "Partially Allocated"
        FULLY_ALLOCATED = "FULLY_ALLOCATED", "Fully Allocated"
        BOUNCED = "BOUNCED", "Cheque Bounced / Returned"
        REVERSED = "REVERSED", "Reversed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ar_customer_receipts")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True)
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="ar_receipts")
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_receipts")
    receipt_no = models.CharField(max_length=48)
    receipt_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    receipt_mode = models.CharField(max_length=24, choices=ReceiptMode.choices, default=ReceiptMode.BANK_TRANSFER, db_index=True)
    deposit_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="ar_receipt_deposits")
    bank_account = models.ForeignKey("banking.BankAccount", on_delete=models.SET_NULL, null=True, blank=True)
    cheque_leaf = models.ForeignKey("banking.ChequeLeaf", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_receipts")
    cheque_number = models.CharField(max_length=40, blank=True)
    cheque_date = models.DateField(null=True, blank=True)
    drawee_bank = models.CharField(max_length=120, blank=True)
    tds_certificate_no = models.CharField(max_length=64, blank=True)
    tds_tax_period = models.CharField(max_length=32, blank=True)
    currency_code = models.CharField(max_length=8, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    bank_charges_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)
    voucher = models.OneToOneField("accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="ar_customer_receipt")
    open_item = models.OneToOneField("party_hub.OpenItem", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_customer_receipt")
    advance_record = models.ForeignKey("accounting.AdvanceRecord", on_delete=models.SET_NULL, null=True, blank=True, related_name="ar_receipts")
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.POSTED, db_index=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_ar_receipts")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "ar_customer_receipts"
        unique_together = [("company", "receipt_no")]
        ordering = ["-receipt_date", "-created_at"]

    def save(self, *args, **kwargs):
        if self.receipt_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.receipt_date).isoformat()
        super().save(*args, **kwargs)


class ReceiptAllocationReversal(models.Model):
    """Immutable log when an explicit receipt-to-bill allocation is reversed without silent deletion."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ar_allocation_reversals")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="ar_allocation_reversals")
    allocation_id_ref = models.UUIDField(db_index=True)
    invoice_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="reversed_ar_invoice_allocations")
    receipt_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="reversed_ar_receipt_allocations")
    reversed_amount = models.DecimalField(max_digits=18, decimal_places=2)
    reason = models.CharField(max_length=255)
    reversed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    reversed_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "ar_receipt_allocation_reversals"
        ordering = ["-reversed_at"]


class CustomerAdvanceContractRule(models.Model):
    """Recovery schedule rule linking Customer Advance / Mobilization Advance to a Project Contract."""

    class RecoveryMethod(models.TextChoices):
        PCT_CERTIFIED = "PCT_CERTIFIED", "Percentage of Certified RA Gross"
        FIXED_PER_BILL = "FIXED_PER_BILL", "Fixed Amount per RA Bill"
        MILESTONE = "MILESTONE", "Milestone Based"
        MANUAL = "MANUAL", "Manual Adjustment"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="advance_contract_rules")
    advance_record = models.OneToOneField("accounting.AdvanceRecord", on_delete=models.CASCADE, related_name="contract_rule")
    contract = models.ForeignKey("projects.ProjectContract", on_delete=models.PROTECT, related_name="advance_recovery_rules")
    recovery_method = models.CharField(max_length=20, choices=RecoveryMethod.choices, default=RecoveryMethod.PCT_CERTIFIED)
    recovery_rate_pct = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("10.00"))
    fixed_recovery_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    min_recovery_per_bill = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    max_recovery_per_bill = models.DecimalField(max_digits=18, decimal_places=2, null=True, blank=True)
    start_recovery_date = models.DateField(null=True, blank=True)
    agreement_ref = models.CharField(max_length=120, blank=True)
    bank_guarantee_ref = models.CharField(max_length=120, blank=True)

    class Meta:
        db_table = "ar_customer_advance_rules"


class PaymentCommitment(models.Model):
    """Tracked Customer Promise-to-Pay commitment tied to Collection Follow-ups & Risk Scoring."""

    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending Due Date"
        FULFILLED = "FULFILLED", "Fulfilled / Paid"
        PARTIAL = "PARTIAL", "Partially Fulfilled"
        BROKEN = "BROKEN", "Broken / Missed"
        CANCELLED = "CANCELLED", "Cancelled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ar_payment_commitments")
    party = models.ForeignKey("accounting.Party", on_delete=models.CASCADE, related_name="ar_payment_commitments")
    open_item = models.ForeignKey("party_hub.OpenItem", on_delete=models.SET_NULL, null=True, blank=True, related_name="commitments")
    collection_activity = models.ForeignKey(
        "party_hub.CollectionActivity", on_delete=models.SET_NULL, null=True, blank=True, related_name="commitments"
    )
    promised_date = models.DateField(db_index=True)
    bs_promised_date = models.CharField(max_length=16, blank=True)
    promised_amount = models.DecimalField(max_digits=18, decimal_places=2)
    fulfilled_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    contact_person = models.CharField(max_length=120, blank=True)
    remarks = models.CharField(max_length=255, blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING, db_index=True)
    recorded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "ar_payment_commitments"
        ordering = ["promised_date", "-created_at"]

    def save(self, *args, **kwargs):
        if self.promised_date and not self.bs_promised_date:
            self.bs_promised_date = ad_to_bs(self.promised_date).isoformat()
        super().save(*args, **kwargs)


class StatementReconciliation(models.Model):
    """Imported external customer statement matching workspace (never auto-adjusts GL)."""

    class Status(models.TextChoices):
        IMPORTED = "IMPORTED", "Imported"
        MATCHED = "MATCHED", "Matching Completed"
        EXCEPTIONS_PENDING = "EXCEPTIONS_PENDING", "Exceptions Require Action"
        SUBMITTED = "SUBMITTED", "Submitted for Approval"
        CONFIRMED = "CONFIRMED", "Reconciled & Confirmed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ar_statement_recons")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="ar_statement_recons")
    recon_no = models.CharField(max_length=48)
    statement_from = models.DateField(null=True, blank=True)
    statement_to = models.DateField()
    source_filename = models.CharField(max_length=255, blank=True)
    company_closing_balance = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    customer_closing_balance = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    variance_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.IMPORTED, db_index=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_ar_recons")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="approved_ar_recons")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "ar_statement_reconciliations"
        unique_together = [("company", "recon_no")]
        ordering = ["-created_at"]


class StatementReconciliationLine(models.Model):
    """Line-by-line imported customer statement transaction matched against ERP OpenItem / Voucher."""

    class MatchState(models.TextChoices):
        MATCHED = "MATCHED", "Exact Match"
        MISSING_IN_COMPANY = "MISSING_IN_COMPANY", "Missing in Company Books"
        MISSING_IN_CUSTOMER = "MISSING_IN_CUSTOMER", "Missing in Customer Statement"
        AMOUNT_MISMATCH = "AMOUNT_MISMATCH", "Amount Mismatch"
        DATE_MISMATCH = "DATE_MISMATCH", "Date Mismatch"
        UNRECOGNIZED_DEDUCTION = "UNRECOGNIZED_DEDUCTION", "Unrecognized Client Deduction"
        DISPUTED = "DISPUTED", "Flagged as Disputed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    reconciliation = models.ForeignKey(StatementReconciliation, on_delete=models.CASCADE, related_name="lines")
    line_no = models.PositiveIntegerField(default=1)
    ext_date = models.DateField(null=True, blank=True)
    ext_reference = models.CharField(max_length=80, blank=True)
    ext_description = models.CharField(max_length=255, blank=True)
    ext_debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    ext_credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    ext_net_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    matched_open_item = models.ForeignKey("party_hub.OpenItem", on_delete=models.SET_NULL, null=True, blank=True)
    matched_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    match_state = models.CharField(max_length=28, choices=MatchState.choices, default=MatchState.MISSING_IN_COMPANY, db_index=True)
    variance_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    resolution_action = models.CharField(max_length=64, blank=True)
    resolution_notes = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = "ar_statement_reconciliation_lines"
        ordering = ["line_no"]


class ARAuditEvent(models.Model):
    """Immutable AR module action timeline supporting drill-down Audit tab inside Transaction Drawer."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ar_audit_events")
    entity_type = models.CharField(max_length=40, db_index=True)
    entity_id = models.CharField(max_length=64, db_index=True)
    action = models.CharField(max_length=64)
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
    details = models.JSONField(default=dict, encoder=DjangoJSONEncoder)
    created_at = models.DateTimeField(auto_now_add=True)

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

