"""Experience foundation aggregates — Phase 11.0.

Independent aggregates use UUID references within experience_db only.
No SQLAlchemy relationship graphs between aggregates.
No dispatch/routing/tracking engines — shells and contracts only.
"""
from __future__ import annotations

import uuid

from sqlalchemy import Index, 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 (
    AuditAction,
    GUID,
    LifecycleStatus,
    ProviderKind,
    ProviderStatus,
    RenderEngineStatus,
)


class ExperienceWorkspace(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Root delivery organization / fleet operator shell for a tenant (Torbat Pages)."""

    __tablename__ = "experience_workspaces"

    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[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.DRAFT, nullable=False
    )
    legal_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
    timezone: Mapped[str] = mapped_column(String(64), default="Asia/Tehran", nullable=False)
    language: Mapped[str] = mapped_column(String(16), default="fa", nullable=False)
    currency_code: Mapped[str] = mapped_column(String(3), default="IRR", nullable=False)
    settings: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_experience_workspaces_tenant_code"),
        Index("ix_experience_workspaces_tenant_status", "tenant_id", "status"),
        Index("ix_experience_workspaces_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperienceLocaleProfile(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Locale / directionality profile under an experience workspace."""

    __tablename__ = "experience_locale_profiles"

    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[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.ACTIVE, nullable=False
    )
    language: Mapped[str] = mapped_column(String(16), default="fa", nullable=False)
    text_direction: Mapped[str] = mapped_column(String(3), default="rtl", nullable=False)
    timezone: Mapped[str | None] = mapped_column(String(64), nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "workspace_id", "code", name="uq_experience_locale_profiles_tenant_code"
        ),
        Index("ix_experience_locale_profiles_org", "tenant_id", "workspace_id"),
        Index("ix_experience_locale_profiles_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperienceRole(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Local experience RBAC role catalog shell."""

    __tablename__ = "experience_roles"

    workspace_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    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[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.ACTIVE, nullable=False
    )

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_experience_roles_tenant_code"),
        Index("ix_experience_roles_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperiencePermission(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Local delivery permission catalog shell (complements platform experience.* tree)."""

    __tablename__ = "experience_permissions"

    role_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(100), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_experience_permissions_tenant_code"),
        Index("ix_experience_permissions_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExternalProviderConfig(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """External theme/CDN/component provider registration shell — credentials stay here."""

    __tablename__ = "external_provider_configs"

    workspace_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    provider_kind: Mapped[ProviderKind] = mapped_column(
        default=ProviderKind.CUSTOM, nullable=False
    )
    adapter_key: Mapped[str] = mapped_column(String(100), nullable=False)
    status: Mapped[ProviderStatus] = mapped_column(
        default=ProviderStatus.REGISTERED, nullable=False
    )
    priority: Mapped[int] = mapped_column(default=100, nullable=False)
    credentials_ref: Mapped[str | None] = mapped_column(String(255), nullable=True)
    config: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    capabilities: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "code", name="uq_external_provider_configs_tenant_code"
        ),
        Index("ix_external_provider_configs_kind", "tenant_id", "provider_kind"),
        Index("ix_external_provider_configs_tenant_deleted", "tenant_id", "is_deleted"),
    )


class RenderEngineRegistration(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Future render/SSG engine registration — adapter ready, no engine implementation."""

    __tablename__ = "render_engine_registrations"

    workspace_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    adapter_key: Mapped[str] = mapped_column(String(100), nullable=False)
    status: Mapped[RenderEngineStatus] = mapped_column(
        default=RenderEngineStatus.REGISTERED, nullable=False
    )
    is_default: Mapped[bool] = mapped_column(default=False, nullable=False)
    config: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    capabilities: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "code", name="uq_render_engine_registrations_tenant_code"
        ),
        Index("ix_render_engine_registrations_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperienceConfiguration(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Tenant experience configuration — publish/SEO/analytics policy shells."""

    __tablename__ = "experience_configurations"

    workspace_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    locale_profile_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    working_hours: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    publish_policies: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    seo_policies: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    analytics_policies: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    custom_fields: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    timezone: Mapped[str] = mapped_column(String(64), default="Asia/Tehran", nullable=False)
    language: Mapped[str] = mapped_column(String(16), default="fa", nullable=False)
    currency_code: Mapped[str] = mapped_column(String(3), default="IRR", nullable=False)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "workspace_id",
            "code",
            name="uq_experience_configurations_tenant_code",
        ),
        Index("ix_experience_configurations_org", "tenant_id", "workspace_id"),
        Index("ix_experience_configurations_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperienceSetting(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Key/value experience settings shell."""

    __tablename__ = "experience_settings"

    workspace_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    locale_profile_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    key: Mapped[str] = mapped_column(String(100), nullable=False)
    value: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "workspace_id",
            "locale_profile_id",
            "key",
            name="uq_experience_settings_tenant_key",
        ),
        Index("ix_experience_settings_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExperienceAuditLog(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    """Append-only experience audit trail."""

    __tablename__ = "experience_audit_logs"

    entity_type: Mapped[str] = mapped_column(String(50), nullable=False)
    entity_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    action: Mapped[AuditAction] = mapped_column(nullable=False)
    actor_user_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
    changes: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    message: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        Index(
            "ix_experience_audit_entity",
            "tenant_id",
            "entity_type",
            "entity_id",
        ),
    )
