import re
from django.core.exceptions import ValidationError
from django.utils import timezone
from apps.document_engine.models import (
    DocumentSettingHierarchy,
    DocumentSignatureConfig,
    DocumentTemplate,
    DocumentTemplateVersion,
    DocumentUserPreference,
    ExportProfile,
    PrintProfile,
)

ALLOWED_SECTION_TYPES = {
    "header",
    "meta_grid",
    "party_info",
    "line_items",
    "totals",
    "amount_words",
    "notes",
    "signatures",
    "qr_barcode",
    "appendix",
}

UNSAFE_TEMPLATE_RE = re.compile(r"(<script|{{|{%|__|javascript:|eval\()", re.IGNORECASE)

DEFAULT_LAYOUT_SCHEMA = {
    "sections": [
        {"id": "header", "type": "header", "label": "Company Branding & Document Header", "visible": True},
        {"id": "meta_grid", "type": "meta_grid", "label": "Document Number, Date (AD/BS) & Copy Badge", "visible": True},
        {"id": "party_info", "type": "party_info", "label": "Bill To / Project / Site Details", "visible": True},
        {
            "id": "line_items",
            "type": "line_items",
            "label": "Line Items / Ledger Table",
            "visible": True,
            "columns": [
                {"key": "sn", "label": "#", "width": "6%", "align": "center", "visible": True},
                {"key": "description", "label": "Description / Account", "width": "44%", "align": "left", "visible": True},
                {"key": "qty", "label": "Qty", "width": "12%", "align": "right", "visible": True},
                {"key": "rate", "label": "Rate / Debit", "width": "18%", "align": "right", "visible": True},
                {"key": "amount", "label": "Amount / Credit", "width": "20%", "align": "right", "visible": True},
            ],
        },
        {"id": "totals", "type": "totals", "label": "Subtotals, Tax / VAT & Grand Total", "visible": True},
        {"id": "amount_words", "type": "amount_words", "label": "Amount in Words", "visible": True},
        {"id": "notes", "type": "notes", "label": "Narration & Terms", "visible": True},
        {"id": "qr_barcode", "type": "qr_barcode", "label": "Verification QR & Barcode", "visible": True},
        {"id": "signatures", "type": "signatures", "label": "Prepared / Checked / Approved Signatures & Stamp", "visible": True},
    ],
    "custom_fields": [],
    "theme": {"header_bg": "#0f766e", "table_stripe": "#f8fafc", "border_color": "#cbd5e1"},
}

SYSTEM_DEFAULT_SETTINGS = {
    "legal_name": "",
    "pan_vat_no": "",
    "registration_no": "",
    "company_address": "",
    "phone": "",
    "email": "",
    "website": "",
    "currency_symbol": "NPR",
    "decimal_precision": 2,
    "date_format": "BOTH",
    "language": "BILINGUAL",
    "paper_size": "A4",
    "orientation": "PORTRAIT",
    "copy_type": "ORIGINAL",
    "watermark_mode": "AUTO_STATUS",
    "show_qr_code": True,
}


def validate_layout_schema(schema: dict) -> dict:
    """Enforce controlled safe layout AST and strip any arbitrary code or XSS payloads."""
    if not isinstance(schema, dict):
        raise ValidationError("Template layout schema must be a JSON object.")
    raw_repr = str(schema)
    if UNSAFE_TEMPLATE_RE.search(raw_repr):
        raise ValidationError("Unsafe template tags, script elements, or code expressions are not allowed.")

    sections = schema.get("sections", DEFAULT_LAYOUT_SCHEMA["sections"])
    if not isinstance(sections, list):
        raise ValidationError("layout_schema.sections must be a list.")

    cleaned_sections = []
    for sec in sections:
        if not isinstance(sec, dict) or sec.get("type") not in ALLOWED_SECTION_TYPES:
            raise ValidationError(f"Unsupported or invalid layout section: {sec}")
        cleaned_sections.append(sec)

    return {
        "sections": cleaned_sections,
        "custom_fields": schema.get("custom_fields", [])[:20],
        "theme": schema.get("theme", DEFAULT_LAYOUT_SCHEMA["theme"]),
    }


def resolve_effective_settings(*, company, document_type=None, branch=None, module_code: str = "", user=None, overrides: dict | None = None) -> dict:
    """Resolve hierarchy: SYSTEM -> COMPANY -> BRANCH -> MODULE -> DOCUMENT_TYPE -> USER while protecting locked fields."""
    resolved = dict(SYSTEM_DEFAULT_SETTINGS)
    resolved.update(
        {
            "legal_name": company.name,
            "pan_vat_no": company.pan_vat_no,
            "registration_no": company.registration_no,
            "company_address": getattr(branch, "address", "") if branch else getattr(company, "address", ""),
            "currency_symbol": company.base_currency or "NPR",
        }
    )
    locked: set[str] = {"legal_name", "pan_vat_no", "registration_no"}

    layers = [
        (DocumentSettingHierarchy.ScopeLevel.SYSTEM, {"company__isnull": True}),
        (DocumentSettingHierarchy.ScopeLevel.COMPANY, {"company": company}),
    ]
    if branch:
        layers.append((DocumentSettingHierarchy.ScopeLevel.BRANCH, {"company": company, "branch": branch}))
    if module_code:
        layers.append((DocumentSettingHierarchy.ScopeLevel.MODULE, {"company": company, "module_code": module_code}))
    if document_type:
        layers.append((DocumentSettingHierarchy.ScopeLevel.DOCUMENT_TYPE, {"company": company, "document_type": document_type}))

    for scope, q in layers:
        row = DocumentSettingHierarchy.objects.filter(scope_level=scope, **q).first()
        if row:
            for k, v in (row.settings_payload or {}).items():
                if k not in locked and v not in (None, ""):
                    resolved[k] = v
            locked.update(row.locked_fields or [])

    if user and getattr(user, "is_authenticated", False):
        pref = DocumentUserPreference.objects.filter(user=user, company=company).first()
        if pref:
            user_map = {
                "paper_size": pref.preferred_paper_size,
                "orientation": pref.preferred_orientation,
                "date_format": pref.preferred_date_format,
                "language": pref.preferred_language,
                "copy_type": pref.preferred_copy_type,
            }
            for k, v in user_map.items():
                if k not in locked and v:
                    resolved[k] = v

    if overrides:
        for k, v in overrides.items():
            if k not in locked and v not in (None, ""):
                resolved[k] = v

    resolved["locked_fields"] = sorted(locked)
    return resolved


def resolve_template_and_profiles(*, company, document_type, branch=None, user=None, template_id=None, overrides: dict | None = None) -> dict:
    """Resolve active approved template version (or default schema), print profile, export profile, and signature slots."""
    today = timezone.localdate()
    template = None
    if template_id:
        template = DocumentTemplate.objects.filter(id=template_id, company=company, document_type=document_type).first()
    if template is None and branch:
        template = DocumentTemplate.objects.filter(
            company=company, branch=branch, document_type=document_type, status=DocumentTemplate.Status.ACTIVE, is_default=True
        ).first()
    if template is None:
        template = DocumentTemplate.objects.filter(
            company=company, branch__isnull=True, document_type=document_type, status=DocumentTemplate.Status.ACTIVE, is_default=True
        ).first()

    template_version = None
    if template:
        template_version = (
            DocumentTemplateVersion.objects.filter(
                template=template, status=DocumentTemplateVersion.Status.APPROVED
            )
            .order_by("-version_number")
            .first()
        )
        if template_version and template_version.effective_from and template_version.effective_from > today:
            template_version = (
                DocumentTemplateVersion.objects.filter(
                    template=template,
                    status__in=[DocumentTemplateVersion.Status.APPROVED, DocumentTemplateVersion.Status.ARCHIVED],
                    effective_from__lte=today,
                )
                .order_by("-version_number")
                .first()
            )

    layout_schema = (
        template_version.layout_schema
        if template_version and template_version.layout_schema
        else (document_type.default_layout_schema or DEFAULT_LAYOUT_SCHEMA)
    )

    print_profile_obj = (
        PrintProfile.objects.filter(company=company, document_type=document_type).order_by("-is_default").first()
        or PrintProfile.objects.filter(company=company, document_type__isnull=True, is_default=True).first()
    )
    print_cfg = {
        "paper_size": print_profile_obj.paper_size if print_profile_obj else "A4",
        "custom_width_mm": float(print_profile_obj.custom_width_mm) if print_profile_obj else 210.0,
        "custom_height_mm": float(print_profile_obj.custom_height_mm) if print_profile_obj else 297.0,
        "orientation": print_profile_obj.orientation if print_profile_obj else "PORTRAIT",
        "margin_top_mm": float(print_profile_obj.margin_top_mm) if print_profile_obj else 12.0,
        "margin_right_mm": float(print_profile_obj.margin_right_mm) if print_profile_obj else 12.0,
        "margin_bottom_mm": float(print_profile_obj.margin_bottom_mm) if print_profile_obj else 14.0,
        "margin_left_mm": float(print_profile_obj.margin_left_mm) if print_profile_obj else 12.0,
        "show_header": print_profile_obj.show_header if print_profile_obj else True,
        "show_footer": print_profile_obj.show_footer if print_profile_obj else True,
        "show_logo": print_profile_obj.show_logo if print_profile_obj else True,
        "logo_position": print_profile_obj.logo_position if print_profile_obj else "LEFT",
        "logo_data_uri": print_profile_obj.logo_data_uri if print_profile_obj else "",
        "watermark_mode": print_profile_obj.watermark_mode if print_profile_obj else "AUTO_STATUS",
        "watermark_text": print_profile_obj.watermark_text if print_profile_obj else "",
        "show_page_number": print_profile_obj.show_page_number if print_profile_obj else True,
        "show_page_count": print_profile_obj.show_page_count if print_profile_obj else True,
        "show_border": print_profile_obj.show_border if print_profile_obj else True,
        "font_family": print_profile_obj.font_family if print_profile_obj else "Noto Sans Devanagari, Inter, sans-serif",
        "section_font_sizes": print_profile_obj.section_font_sizes if print_profile_obj else {},
        "table_style": print_profile_obj.table_style if print_profile_obj else "STANDARD",
        "row_height_px": print_profile_obj.row_height_px if print_profile_obj else 24,
        "show_qr_code": print_profile_obj.show_qr_code if print_profile_obj else True,
        "show_barcode": print_profile_obj.show_barcode if print_profile_obj else False,
        "copy_type": print_profile_obj.default_copy_type if print_profile_obj else "ORIGINAL",
        "copies": print_profile_obj.default_copies if print_profile_obj else 1,
        "color_mode": print_profile_obj.color_mode if print_profile_obj else "COLOR",
        "duplex": print_profile_obj.duplex if print_profile_obj else False,
        "language": print_profile_obj.language if print_profile_obj else "BILINGUAL",
        "date_format": print_profile_obj.date_format if print_profile_obj else "BOTH",
        "accent_color": print_profile_obj.accent_color if print_profile_obj else "#0f766e",
    }

    if template_version and template_version.pdf_profile_overrides:
        print_cfg.update({k: v for k, v in template_version.pdf_profile_overrides.items() if v not in (None, "")})

    settings_cfg = resolve_effective_settings(
        company=company,
        document_type=document_type,
        branch=branch,
        module_code=document_type.module_code,
        user=user,
        overrides=overrides,
    )
    for k in ("paper_size", "orientation", "copy_type", "language", "date_format", "watermark_mode", "watermark_text"):
        if k in settings_cfg and settings_cfg[k]:
            print_cfg[k] = settings_cfg[k]
    if overrides:
        for k in ("paper_size", "orientation", "copy_type", "language", "date_format", "copies", "color_mode", "watermark_text"):
            if k in overrides and overrides[k] not in (None, "") and k not in settings_cfg["locked_fields"]:
                print_cfg[k] = overrides[k]

    sig_cfg = (
        DocumentSignatureConfig.objects.filter(company=company, document_type=document_type).first()
        or DocumentSignatureConfig.objects.filter(company=company, document_type__isnull=True).first()
    )
    signatures = (
        sig_cfg.slots
        if sig_cfg and sig_cfg.slots
        else [
            {"role": "Prepared By", "label": "Prepared By"},
            {"role": "Checked By", "label": "Checked By"},
            {"role": "Authorized By", "label": "Authorized By"},
        ]
    )

    exp_obj = (
        ExportProfile.objects.filter(company=company, document_type=document_type).order_by("-is_default").first()
        or ExportProfile.objects.filter(company=company, document_type__isnull=True, is_default=True).first()
    )
    export_cfg = {
        "freeze_panes": exp_obj.freeze_panes if exp_obj else True,
        "auto_filter": exp_obj.auto_filter if exp_obj else True,
        "include_charts": exp_obj.include_charts if exp_obj else True,
        "include_formulas": exp_obj.include_formulas if exp_obj else True,
        "protect_formulas": exp_obj.protect_formulas if exp_obj else True,
        "numeric_precision": exp_obj.numeric_precision if exp_obj else 2,
        "include_filter_banner": exp_obj.include_filter_banner if exp_obj else True,
        "page_orientation": exp_obj.page_orientation if exp_obj else "LANDSCAPE",
    }

    return {
        "template": template,
        "template_version": template_version,
        "layout_schema": layout_schema,
        "settings": settings_cfg,
        "print_profile": print_cfg,
        "export_profile": export_cfg,
        "signatures": signatures,
        "stamp_data_uri": sig_cfg.stamp_data_uri if sig_cfg and sig_cfg.show_stamp else "",
        "digital_signature_enabled": sig_cfg.digital_signature_enabled if sig_cfg else False,
    }
