import uuid
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models


class DocumentType(models.Model):
    """Central registry of every printable/exportable document across all modules."""

    class Category(models.TextChoices):
        ACCOUNTING = "ACCOUNTING", "Accounting & Finance"
        CONSTRUCTION = "CONSTRUCTION", "Construction & Job Work"
        DELIVERY = "DELIVERY", "Delivery, Inventory & Dispatch"
        BUSINESS_HR = "BUSINESS_HR", "Business, Banking & HR"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    code = models.CharField(max_length=64, unique=True, db_index=True)
    name = models.CharField(max_length=160)
    category = models.CharField(max_length=24, choices=Category.choices, db_index=True)
    module_code = models.CharField(max_length=40, default="ACCOUNTING")
    source_model = models.CharField(max_length=120, blank=True)
    supports_pdf = models.BooleanField(default=True)
    supports_excel = models.BooleanField(default=True)
    supports_csv = models.BooleanField(default=True)
    supports_thermal = models.BooleanField(default=False)
    is_sensitive = models.BooleanField(
        default=False,
        help_text="Restricts bulk exports unless explicitly permitted.",
    )
    default_prefix = models.CharField(max_length=20, default="DOC")
    default_layout_schema = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    description = models.TextField(blank=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "document_types"
        ordering = ["category", "name"]

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


class DocumentSequence(models.Model):
    """Atomic configurable numbering sequences scoped by company, branch, FY, doc type & phase."""

    class Phase(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        FINAL = "FINAL", "Final / Issued"

    class ResetPolicy(models.TextChoices):
        NEVER = "NEVER", "Continuous (Never Reset)"
        FISCAL_YEAR = "FISCAL_YEAR", "Reset Every Fiscal Year"
        CALENDAR_YEAR = "CALENDAR_YEAR", "Reset Every Calendar Year"
        MONTHLY = "MONTHLY", "Reset Monthly"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="document_sequences"
    )
    branch = models.ForeignKey(
        "tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True, related_name="document_sequences"
    )
    fiscal_year = models.ForeignKey(
        "tenancy.FiscalYear", on_delete=models.PROTECT, null=True, blank=True, related_name="document_sequences"
    )
    document_type = models.ForeignKey(
        DocumentType, on_delete=models.CASCADE, related_name="sequences"
    )
    phase = models.CharField(max_length=12, choices=Phase.choices, default=Phase.FINAL)
    prefix = models.CharField(max_length=24, default="DOC-")
    suffix = models.CharField(max_length=24, blank=True, default="")
    digit_length = models.PositiveSmallIntegerField(default=5)
    reset_policy = models.CharField(
        max_length=16, choices=ResetPolicy.choices, default=ResetPolicy.FISCAL_YEAR
    )
    last_number = models.PositiveIntegerField(default=0)
    allow_manual_override = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "document_sequences"
        unique_together = [("company", "branch", "fiscal_year", "document_type", "phase")]
        ordering = ["document_type__code", "phase"]

    def format_number(self, seq_num: int) -> str:
        fy_tag = self.fiscal_year.name.split("/")[0] if self.fiscal_year else ""
        fy_part = f"{fy_tag}-" if fy_tag and "{fy}" not in self.prefix else ""
        prefix = self.prefix.replace("{fy}", fy_tag)
        padded = str(seq_num).zfill(max(1, self.digit_length))
        if prefix.endswith("-") or not fy_part:
            return f"{prefix}{padded}{self.suffix}"
        return f"{prefix}{fy_part}{padded}{self.suffix}"


class CancelledDocumentNumber(models.Model):
    """Immutable log of cancelled or voided numbers so sequences are never silently reused."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    document_type = models.ForeignKey(DocumentType, on_delete=models.CASCADE)
    document_number = models.CharField(max_length=64)
    reason = models.CharField(max_length=255)
    cancelled_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    cancelled_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "document_cancelled_numbers"
        unique_together = [("company", "document_type", "document_number")]
        ordering = ["-cancelled_at"]
