"""Component library aggregates — Phase 11.2.

ExperienceComponent = mutable catalog entry.
ExperienceComponentVersion = immutable once published.
PageComponentPlacement = composition shell pinning a version onto a page.
No theme/layout engines 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 (
    ComponentKind,
    ComponentStatus,
    ComponentVersionStatus,
    GUID,
)


class ExperienceComponent(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Reusable component definition in the tenant library."""

    __tablename__ = "experience_components"

    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[ComponentKind] = mapped_column(
        default=ComponentKind.CONTENT, nullable=False
    )
    status: Mapped[ComponentStatus] = mapped_column(
        default=ComponentStatus.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_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_components_tenant_code",
        ),
        Index("ix_experience_components_workspace", "tenant_id", "workspace_id"),
        Index("ix_experience_components_kind", "tenant_id", "kind"),
        Index("ix_experience_components_status", "tenant_id", "status"),
        Index("ix_experience_components_category", "tenant_id", "category"),
        Index("ix_experience_components_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperienceComponentVersion(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Immutable published revision of a component."""

    __tablename__ = "experience_component_versions"

    workspace_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    component_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    version_number: Mapped[int] = mapped_column(Integer, nullable=False)
    status: Mapped[ComponentVersionStatus] = mapped_column(
        default=ComponentVersionStatus.DRAFT, nullable=False
    )
    definition_schema: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    props_defaults: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    render_hint: 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",
            "component_id",
            "version_number",
            name="uq_experience_component_versions_num",
        ),
        Index("ix_experience_component_versions_component", "tenant_id", "component_id"),
        Index("ix_experience_component_versions_status", "tenant_id", "status"),
        Index(
            "ix_experience_component_versions_tenant_deleted", "tenant_id", "is_deleted"
        ),
    )


class PageComponentPlacement(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Composition shell: pin a component version onto a page (no layout engine)."""

    __tablename__ = "experience_page_component_placements"

    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)
    component_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    component_version_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    slot_key: Mapped[str] = mapped_column(String(100), nullable=False)
    sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    props_override: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    is_visible: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "page_id",
            "slot_key",
            name="uq_experience_page_component_placements_slot",
        ),
        Index("ix_experience_page_placements_page", "tenant_id", "page_id"),
        Index("ix_experience_page_placements_component", "tenant_id", "component_id"),
        Index(
            "ix_experience_page_placements_tenant_deleted", "tenant_id", "is_deleted"
        ),
    )
