"""Template system aggregates — Phase 11.4.

ExperienceTemplate = catalog entry (page-type starter packs).
ExperienceTemplateVersion = immutable once published (blueprint shell).
TemplateInstantiation = audit trail of instantiate → page creation.
No forms/surveys engine in this phase.
"""
from __future__ import annotations

import uuid
from datetime import datetime

from sqlalchemy import Boolean, DateTime, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.types import JSON

from app.core.database import Base
from app.models.base import (
    ActorAuditMixin,
    OptimisticLockMixin,
    SoftDeleteMixin,
    TenantMixin,
    TimestampMixin,
    UUIDPrimaryKeyMixin,
)
from app.models.types import (
    GUID,
    TemplateInstantiationStatus,
    TemplateStatus,
    TemplateVersionStatus,
)


class ExperienceTemplate(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Reusable page-type template in the tenant catalog."""

    __tablename__ = "experience_templates"

    workspace_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    page_type: Mapped[str] = mapped_column(String(50), nullable=False)
    status: Mapped[TemplateStatus] = mapped_column(
        default=TemplateStatus.DRAFT, nullable=False
    )
    category: Mapped[str | None] = mapped_column(String(100), nullable=True)
    tags: Mapped[list | None] = mapped_column(JSON, nullable=True)
    latest_version_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    published_version_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    is_starter_pack: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    is_system: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "workspace_id",
            "code",
            name="uq_experience_templates_tenant_code",
        ),
        Index("ix_experience_templates_workspace", "tenant_id", "workspace_id"),
        Index("ix_experience_templates_page_type", "tenant_id", "page_type"),
        Index("ix_experience_templates_status", "tenant_id", "status"),
        Index("ix_experience_templates_starter", "tenant_id", "is_starter_pack"),
        Index("ix_experience_templates_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperienceTemplateVersion(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Immutable published blueprint revision of a template."""

    __tablename__ = "experience_template_versions"

    workspace_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    template_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    version_number: Mapped[int] = mapped_column(Integer, nullable=False)
    status: Mapped[TemplateVersionStatus] = mapped_column(
        default=TemplateVersionStatus.DRAFT, nullable=False
    )
    blueprint_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    changelog: Mapped[str | None] = mapped_column(Text, nullable=True)
    is_immutable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    published_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    retired_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "template_id",
            "version_number",
            name="uq_experience_template_versions_num",
        ),
        Index("ix_experience_template_versions_template", "tenant_id", "template_id"),
        Index("ix_experience_template_versions_status", "tenant_id", "status"),
        Index(
            "ix_experience_template_versions_tenant_deleted", "tenant_id", "is_deleted"
        ),
    )


class TemplateInstantiation(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Record of instantiating a published template into a site page."""

    __tablename__ = "experience_template_instantiations"

    workspace_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    template_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    template_version_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    site_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    page_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    status: Mapped[TemplateInstantiationStatus] = mapped_column(
        default=TemplateInstantiationStatus.PENDING, nullable=False
    )
    result_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
    completed_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        Index("ix_experience_template_inst_template", "tenant_id", "template_id"),
        Index("ix_experience_template_inst_site", "tenant_id", "site_id"),
        Index("ix_experience_template_inst_page", "tenant_id", "page_id"),
        Index("ix_experience_template_inst_status", "tenant_id", "status"),
        Index(
            "ix_experience_template_inst_tenant_deleted", "tenant_id", "is_deleted"
        ),
    )
