import uuid
from decimal import Decimal
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from .document_types import DocumentType


class DocumentSettingHierarchy(models.Model):
    """Controlled settings inheritance: System -> Company -> Branch -> Module -> DocType -> User."""

    class ScopeLevel(models.TextChoices):
        SYSTEM = "SYSTEM", "System Default"
        COMPANY = "COMPANY", "Company Level"
        BRANCH = "BRANCH", "Branch Level"
        MODULE = "MODULE", "Module Level"
        DOCUMENT_TYPE = "DOCUMENT_TYPE", "Document Type Level"
        USER = "USER", "Authorized User Preference"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, null=True, blank=True, related_name="document_settings"
    )
    branch = models.ForeignKey(
        "tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True
    )
    document_type = models.ForeignKey(
        DocumentType, on_delete=models.CASCADE, null=True, blank=True
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True
    )
    module_code = models.CharField(max_length=40, blank=True)
    scope_level = models.CharField(max_length=20, choices=ScopeLevel.choices, db_index=True)
    locked_fields = models.JSONField(
        default=list,
        blank=True,
        encoder=DjangoJSONEncoder,
        help_text="Keys that lower inheritance levels cannot override (e.g. company_pan, legal_name).",
    )
    settings_payload = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "document_setting_hierarchy"
        ordering = ["scope_level"]


class PrintProfile(models.Model):
    """Page size, margins, watermark, font, border, copy type, and print controls."""

    class PaperSize(models.TextChoices):
        A4 = "A4", "A4 (210 x 297 mm)"
        A5 = "A5", "A5 (148 x 210 mm)"
        A3 = "A3", "A3 (297 x 420 mm)"
        LETTER = "LETTER", "US Letter (8.5 x 11 in)"
        LEGAL = "LEGAL", "US Legal (8.5 x 14 in)"
        THERMAL_80 = "THERMAL_80", "Thermal 80mm Receipt"
        THERMAL_58 = "THERMAL_58", "Thermal 58mm Receipt"
        CUSTOM = "CUSTOM", "Custom Dimensions"

    class Orientation(models.TextChoices):
        PORTRAIT = "PORTRAIT", "Portrait"
        LANDSCAPE = "LANDSCAPE", "Landscape"

    class TableStyle(models.TextChoices):
        COMPACT = "COMPACT", "Compact"
        STANDARD = "STANDARD", "Standard"
        DETAILED = "DETAILED", "Detailed"

    class CopyType(models.TextChoices):
        ORIGINAL = "ORIGINAL", "Original"
        DUPLICATE = "DUPLICATE", "Duplicate"
        TRIPLICATE = "TRIPLICATE", "Triplicate"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="print_profiles"
    )
    branch = models.ForeignKey(
        "tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True
    )
    document_type = models.ForeignKey(
        DocumentType, on_delete=models.CASCADE, null=True, blank=True, related_name="print_profiles"
    )
    name = models.CharField(max_length=120, default="Standard A4 Profile")
    is_default = models.BooleanField(default=False)

    paper_size = models.CharField(max_length=16, choices=PaperSize.choices, default=PaperSize.A4)
    custom_width_mm = models.DecimalField(max_digits=7, decimal_places=2, default=Decimal("210.00"))
    custom_height_mm = models.DecimalField(max_digits=7, decimal_places=2, default=Decimal("297.00"))
    orientation = models.CharField(max_length=12, choices=Orientation.choices, default=Orientation.PORTRAIT)

    margin_top_mm = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("12.00"))
    margin_right_mm = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("12.00"))
    margin_bottom_mm = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("14.00"))
    margin_left_mm = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("12.00"))

    show_header = models.BooleanField(default=True)
    show_footer = models.BooleanField(default=True)
    show_logo = models.BooleanField(default=True)
    logo_position = models.CharField(max_length=16, default="LEFT")  # LEFT | CENTER | RIGHT
    logo_data_uri = models.TextField(blank=True)

    watermark_mode = models.CharField(max_length=16, default="AUTO_STATUS")  # NONE | AUTO_STATUS | CUSTOM
    watermark_text = models.CharField(max_length=64, blank=True)

    show_page_number = models.BooleanField(default=True)
    show_page_count = models.BooleanField(default=True)
    show_border = models.BooleanField(default=True)
    font_family = models.CharField(max_length=80, default="Noto Sans Devanagari, Inter, sans-serif")
    section_font_sizes = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    table_style = models.CharField(max_length=16, choices=TableStyle.choices, default=TableStyle.STANDARD)
    row_height_px = models.PositiveSmallIntegerField(default=24)
    column_widths = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)

    show_qr_code = models.BooleanField(default=True)
    show_barcode = models.BooleanField(default=False)
    default_copy_type = models.CharField(max_length=16, choices=CopyType.choices, default=CopyType.ORIGINAL)
    default_copies = models.PositiveSmallIntegerField(default=1)
    color_mode = models.CharField(max_length=12, default="COLOR")  # COLOR | GRAYSCALE
    duplex = models.BooleanField(default=False)
    language = models.CharField(max_length=12, default="BILINGUAL")  # EN | NE | BILINGUAL
    date_format = models.CharField(max_length=12, default="BOTH")  # AD | BS | BOTH
    accent_color = models.CharField(max_length=16, default="#0f766e")

    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "print_profiles"
        ordering = ["-is_default", "name"]


class DocumentSignatureConfig(models.Model):
    """Configurable signature lines, stamps, and authorization blocks."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="signature_configs"
    )
    branch = models.ForeignKey(
        "tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True
    )
    document_type = models.ForeignKey(
        DocumentType, on_delete=models.CASCADE, null=True, blank=True, related_name="signature_configs"
    )
    slots = models.JSONField(default=list, encoder=DjangoJSONEncoder)
    show_stamp = models.BooleanField(default=True)
    stamp_position = models.CharField(max_length=16, default="RIGHT")
    stamp_data_uri = models.TextField(blank=True)
    digital_signature_enabled = models.BooleanField(default=False)
    show_on_last_page_only = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "document_signatures"


class DocumentUserPreference(models.Model):
    """Authorized user personal print/export preferences (never overrides locked fields)."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="document_preferences"
    )
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="user_document_preferences"
    )
    preferred_paper_size = models.CharField(max_length=16, default="A4")
    preferred_orientation = models.CharField(max_length=12, default="PORTRAIT")
    preferred_date_format = models.CharField(max_length=12, default="BOTH")
    preferred_language = models.CharField(max_length=12, default="BILINGUAL")
    preferred_copy_type = models.CharField(max_length=16, default="ORIGINAL")
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "document_user_preferences"
        unique_together = [("user", "company")]

