"""Theme & layout engine aggregates — Phase 11.4 (versioned rework).

ExperienceTheme = catalog entry (mutable metadata, replaceable pack).
ExperienceThemeVersion = immutable once published (tokens / brand shell).
ExperienceLayout = catalog entry (mutable metadata, dynamic layout shell).
ExperienceLayoutVersion = immutable once published (regions / structure shell).
SiteThemeBinding = pins a published theme version onto a site (replaceable).
PageLayoutBinding = pins a published layout version onto a page (replaceable).
No page-builder / CMS / forms 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 (
    DirectionMode,
    GUID,
    LayoutKind,
    LayoutStatus,
    LayoutVersionStatus,
    ThemeStatus,
    ThemeVersionStatus,
)


class ExperienceTheme(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Replaceable theme pack catalog entry (ADR-008 compatible)."""

    __tablename__ = "experience_themes"

    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)
    status: Mapped[ThemeStatus] = mapped_column(
        default=ThemeStatus.DRAFT, nullable=False
    )
    direction_mode: Mapped[DirectionMode] = mapped_column(
        default=DirectionMode.BOTH, 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_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_themes_tenant_code",
        ),
        Index("ix_experience_themes_workspace", "tenant_id", "workspace_id"),
        Index("ix_experience_themes_status", "tenant_id", "status"),
        Index("ix_experience_themes_direction", "tenant_id", "direction_mode"),
        Index("ix_experience_themes_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperienceThemeVersion(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Immutable published revision of a theme (CSS tokens + brand shell)."""

    __tablename__ = "experience_theme_versions"

    workspace_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    theme_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    version_number: Mapped[int] = mapped_column(Integer, nullable=False)
    status: Mapped[ThemeVersionStatus] = mapped_column(
        default=ThemeVersionStatus.DRAFT, nullable=False
    )
    tokens: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    brand_shell: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    direction_mode: Mapped[DirectionMode | None] = mapped_column(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",
            "theme_id",
            "version_number",
            name="uq_experience_theme_versions_num",
        ),
        Index("ix_experience_theme_versions_theme", "tenant_id", "theme_id"),
        Index("ix_experience_theme_versions_status", "tenant_id", "status"),
        Index(
            "ix_experience_theme_versions_tenant_deleted", "tenant_id", "is_deleted"
        ),
    )


class ExperienceLayout(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Dynamic layout catalog entry — regions/slots shells, no template catalog."""

    __tablename__ = "experience_layouts"

    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)
    kind: Mapped[LayoutKind] = mapped_column(
        default=LayoutKind.PAGE_SHELL, nullable=False
    )
    status: Mapped[LayoutStatus] = mapped_column(
        default=LayoutStatus.DRAFT, nullable=False
    )
    direction_mode: Mapped[DirectionMode] = mapped_column(
        default=DirectionMode.BOTH, 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_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_layouts_tenant_code",
        ),
        Index("ix_experience_layouts_workspace", "tenant_id", "workspace_id"),
        Index("ix_experience_layouts_status", "tenant_id", "status"),
        Index("ix_experience_layouts_direction", "tenant_id", "direction_mode"),
        Index("ix_experience_layouts_kind", "tenant_id", "kind"),
        Index("ix_experience_layouts_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperienceLayoutVersion(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Immutable published revision of a layout (regions + structure shell)."""

    __tablename__ = "experience_layout_versions"

    workspace_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    layout_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    version_number: Mapped[int] = mapped_column(Integer, nullable=False)
    status: Mapped[LayoutVersionStatus] = mapped_column(
        default=LayoutVersionStatus.DRAFT, nullable=False
    )
    regions: Mapped[list | None] = mapped_column(JSON, nullable=True)
    structure_shell: 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",
            "layout_id",
            "version_number",
            name="uq_experience_layout_versions_num",
        ),
        Index("ix_experience_layout_versions_layout", "tenant_id", "layout_id"),
        Index("ix_experience_layout_versions_status", "tenant_id", "status"),
        Index(
            "ix_experience_layout_versions_tenant_deleted", "tenant_id", "is_deleted"
        ),
    )


class SiteThemeBinding(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Pin a published theme version onto a site (replaceable without rewriting pages)."""

    __tablename__ = "experience_site_theme_bindings"

    workspace_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    site_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    theme_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    theme_version_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        Index("ix_experience_site_theme_bindings_site", "tenant_id", "site_id"),
        Index("ix_experience_site_theme_bindings_theme", "tenant_id", "theme_id"),
        Index(
            "ix_experience_site_theme_bindings_version", "tenant_id", "theme_version_id"
        ),
        Index(
            "ix_experience_site_theme_bindings_tenant_deleted",
            "tenant_id",
            "is_deleted",
        ),
    )


class PageLayoutBinding(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Pin a published layout version onto a page (dynamic composition shell)."""

    __tablename__ = "experience_page_layout_bindings"

    workspace_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    site_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    page_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    layout_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    layout_version_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        Index("ix_experience_page_layout_bindings_page", "tenant_id", "page_id"),
        Index("ix_experience_page_layout_bindings_layout", "tenant_id", "layout_id"),
        Index(
            "ix_experience_page_layout_bindings_version",
            "tenant_id",
            "layout_version_id",
        ),
        Index(
            "ix_experience_page_layout_bindings_tenant_deleted",
            "tenant_id",
            "is_deleted",
        ),
    )
