import uuid
from decimal import Decimal
from django.db import models
from .coa import Account


class AccountingPolicy(models.Model):
    """Company-level authoritative accounting rules driving the central PostingRuleEngine."""

    class InventoryMethod(models.TextChoices):
        PERPETUAL = "PERPETUAL", "Perpetual (Purchase -> Inventory -> WIP on Issue)"
        PERIODIC = "PERIODIC", "Periodic (Purchase -> Direct Purchase Cost)"

    class RevenueRecognition(models.TextChoices):
        CERTIFIED_RA_BILL = "CERTIFIED_RA_BILL", "Certified RA Progress & Contract Milestones"
        PERCENTAGE_COMPLETION = "PERCENTAGE_COMPLETION", "Percentage of Completion (WIP Matching)"
        INVOICE_ISSUED = "INVOICE_ISSUED", "Immediate on Commercial Invoice Issuance"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.OneToOneField(
        "tenancy.Company", on_delete=models.CASCADE, related_name="accounting_policy"
    )
    inventory_method = models.CharField(
        max_length=16, choices=InventoryMethod.choices, default=InventoryMethod.PERPETUAL
    )
    revenue_recognition = models.CharField(
        max_length=28, choices=RevenueRecognition.choices, default=RevenueRecognition.CERTIFIED_RA_BILL
    )
    capitalize_borrowing_costs = models.BooleanField(default=False)
    duplicate_invoice_check = models.BooleanField(default=True)
    enforce_control_subledgers = models.BooleanField(default=True)
    auto_fx_gain_loss = models.BooleanField(default=True)
    grni_on_receipt = models.BooleanField(default=True)
    default_valuation_method = models.CharField(max_length=20, default="WEIGHTED_AVG")
    strict_budget_control = models.BooleanField(default=False)
    auto_create_open_items = models.BooleanField(default=True)
    require_explicit_bill_allocation = models.BooleanField(default=True)
    default_aging_buckets = models.JSONField(
        default=list, blank=True, help_text="Ordered overdue day breakpoints e.g. [0, 30, 60, 90, 180, 365]"
    )
    default_retention_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("5.00"))
    materiality_threshold_npr = models.DecimalField(
        max_digits=18, decimal_places=2, default=Decimal("100000.00")
    )
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "accounting_policies"


class PostingRule(models.Model):
    """Configurable double-entry posting template rules mapped to company COA accounts."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="posting_rules"
    )
    voucher_type = models.CharField(max_length=32, db_index=True)
    rule_code = models.CharField(max_length=48, default="DEFAULT")
    debit_account = models.ForeignKey(
        Account, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    credit_account = models.ForeignKey(
        Account, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    tax_account = models.ForeignKey(
        Account, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    tds_account = models.ForeignKey(
        Account, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    retention_account = models.ForeignKey(
        Account, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    advance_account = models.ForeignKey(
        Account, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    description = models.CharField(max_length=255, blank=True)
    is_active = models.BooleanField(default=True)

    class Meta:
        db_table = "posting_rules"
        unique_together = [("company", "voucher_type", "rule_code")]
        ordering = ["voucher_type", "rule_code"]

