import uuid
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import models

from apps.localization.bs_calendar import ad_to_bs, nepal_fiscal_year_periods
from apps.localization.tax import validate_nepal_pan


class Company(models.Model):
    class CalendarPref(models.TextChoices):
        BS = "BS", "Bikram Sambat (BS)"
        AD = "AD", "Gregorian (AD)"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    code = models.CharField(max_length=24, unique=True)
    name = models.CharField(max_length=200)
    registration_no = models.CharField(max_length=64, blank=True)
    pan_vat_no = models.CharField(max_length=20, blank=True)
    base_currency = models.CharField(max_length=3, default="NPR")
    calendar_preference = models.CharField(
        max_length=4, choices=CalendarPref.choices, default=CalendarPref.BS
    )
    default_vat_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("13.00"))
    multi_currency_enabled = models.BooleanField(default=False)
    nfrs_enabled = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["code"]
        verbose_name_plural = "Companies"

    def clean(self):
        if self.pan_vat_no and not validate_nepal_pan(self.pan_vat_no):
            raise ValidationError({"pan_vat_no": "Nepal PAN/VAT must be a 9-digit number."})

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


class Branch(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="branches")
    code = models.CharField(max_length=24)
    name = models.CharField(max_length=150)
    address = models.CharField(max_length=255, blank=True)
    is_head_office = 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.company.code}:{self.code} — {self.name}"


class FiscalYear(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="fiscal_years")
    name = models.CharField(max_length=32)  # e.g. 2083/84
    start_date = models.DateField()
    end_date = models.DateField()
    bs_start_date = models.CharField(max_length=16, blank=True)
    bs_end_date = models.CharField(max_length=16, blank=True)
    is_current = models.BooleanField(default=False)
    is_closed = models.BooleanField(default=False)

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

    def save(self, *args, **kwargs):
        if not self.bs_start_date:
            self.bs_start_date = ad_to_bs(self.start_date).isoformat()
        if not self.bs_end_date:
            self.bs_end_date = ad_to_bs(self.end_date).isoformat()
        super().save(*args, **kwargs)

    @classmethod
    def resolve_from_bs_year(cls, *, company, bs_start_year: int, start_month: int = 4, name: str | None = None):
        from apps.localization.services import NepalFiscalYearService

        periods = NepalFiscalYearService.generate_bs_fiscal_periods(bs_start_year, start_month=start_month)
        fy_label = name or f"{bs_start_year}/{(bs_start_year + 1) % 100:02d}"
        fy, _ = cls.objects.get_or_create(
            company=company,
            name=fy_label,
            defaults={
                "start_date": periods[0]["start_date"],
                "end_date": periods[-1]["end_date"],
                "bs_start_date": periods[0]["bs_start_date"],
                "bs_end_date": periods[-1]["bs_end_date"],
            },
        )
        return fy

    def generate_nepal_periods(self, bs_start_year: int) -> list["FiscalPeriod"]:
        periods = []
        for p in nepal_fiscal_year_periods(bs_start_year):
            period, _ = FiscalPeriod.objects.get_or_create(
                fiscal_year=self,
                sequence=p["sequence"],
                defaults={
                    "name": p["name"],
                    "start_date": p["start_date"],
                    "end_date": p["end_date"],
                    "bs_start_date": p["bs_start_date"],
                    "bs_end_date": p["bs_end_date"],
                    "status": FiscalPeriod.Status.OPEN,
                },
            )
            periods.append(period)
        return periods

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


class FiscalPeriod(models.Model):
    class Status(models.TextChoices):
        OPEN = "OPEN", "Open"
        LOCKED = "LOCKED", "Locked"
        CLOSED = "CLOSED", "Closed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    fiscal_year = models.ForeignKey(FiscalYear, on_delete=models.CASCADE, related_name="periods")
    sequence = models.PositiveSmallIntegerField()
    name = models.CharField(max_length=40)
    start_date = models.DateField()
    end_date = models.DateField()
    bs_start_date = models.CharField(max_length=16, blank=True)
    bs_end_date = models.CharField(max_length=16, blank=True)
    status = models.CharField(max_length=12, choices=Status.choices, default=Status.OPEN)

    class Meta:
        unique_together = [("fiscal_year", "sequence")]
        ordering = ["fiscal_year", "sequence"]

    def __str__(self) -> str:
        return f"{self.fiscal_year.name} / {self.name} [{self.status}]"


class TaxConfig(models.Model):
    class TaxType(models.TextChoices):
        VAT = "VAT", "Value Added Tax (VAT)"
        TDS = "TDS", "Tax Deducted at Source (TDS)"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="tax_configs")
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=120)
    tax_type = models.CharField(max_length=8, choices=TaxType.choices)
    rate = models.DecimalField(max_digits=6, decimal_places=2)
    effective_from = models.DateField(null=True, blank=True)
    effective_to = models.DateField(null=True, blank=True)
    category = models.CharField(max_length=32, default="STANDARD")
    exemption_rule = models.CharField(max_length=160, blank=True)
    calculation_rule = models.CharField(max_length=255, blank=True)
    tax_ledger = models.ForeignKey(
        "accounting.Account",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="tax_configs",
    )
    is_active = models.BooleanField(default=True)

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

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

