"""feature_packs domain — SQLAlchemy models.

A feature pack composes existing function-library slugs, record-engine entity
schemas, and connector actions into one installable unit, analogous to how
``FunctionLibrary``/``ProjectFunction`` (src/domain/edge_functions/models.py)
track a single deployable function and its per-project deployment state.
"""
from __future__ import annotations

from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4

from sqlalchemy import ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql import func
from sqlalchemy.types import DateTime

from src.core.database import Base


class FeaturePack(Base):
    """Platform feature-pack catalog.

    status: active | deprecated
    scope: catalog (human-curated, default; offered to codegen as a reusable option) |
           project_local (synthesized by Level 1 composition -- install-only, never
           listed as a catalog choice until an explicit future promotion step; see
           src/domain/feature_packs/composer.py)
    """

    __tablename__ = "feature_packs"

    id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid4)
    slug: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
    name: Mapped[str] = mapped_column(String(120), nullable=False)
    description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    version: Mapped[str] = mapped_column(String(20), nullable=False, default="1.0.0")
    tags: Mapped[Optional[list]] = mapped_column(JSONB, nullable=True)
    status: Mapped[str] = mapped_column(Text, nullable=False, default="active")
    scope: Mapped[str] = mapped_column(Text, nullable=False, default="catalog", server_default="catalog")
    # Owning project for scope="project_local" rows only; NULL for catalog rows (which
    # are shared/global by design). Required so the requirement_fingerprint dedup hook
    # below can never match a row across two different projects -- see the unique index
    # in migration 131 and compose_and_register_pack's lookup in composer.py.
    project_id: Mapped[Optional[UUID]] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("projects.id", ondelete="CASCADE"), nullable=True
    )
    # Dedup hook for synthesized rows only -- a normalized hash of the requirements that
    # produced this pack, so a repeat/near-duplicate compose request reuses the same row
    # instead of creating quote-request-01/quote-request-02. NULL for catalog rows.
    # Always paired with project_id -- see the note above.
    requirement_fingerprint: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    # Operational blob plus Feature Pack contract V2 keys. Architectural
    # ``requires`` are typed {kind, id} refs; providers live in
    # ``provider_bindings``. See src/domain/feature_packs/contract.py.
    composition: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)
    input_schema: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)
    access_policy: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )


class ProjectFeaturePack(Base):
    """Install state of one feature pack for one project.

    status progresses supported -> enabled -> installed -> configured -> deployed -> verified,
    or blocked (see ``blocker`` for the owner-facing setup action still needed).

    ``configuration_required`` is distinct from ``blocked``: the pack's entities,
    functions and code were built successfully, but a provider connection (or webhook
    signing secret) is still missing -- a runtime dependency, not a build failure. See
    ``blocker.pending_connections`` / ``blocker.webhooks_pending_setup``. Only
    ``blocked`` means the capability itself could not be built.
    """

    __tablename__ = "project_feature_packs"

    id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid4)
    project_id: Mapped[UUID] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("projects.id", ondelete="CASCADE"), nullable=False
    )
    pack_id: Mapped[UUID] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("feature_packs.id", ondelete="RESTRICT"), nullable=False
    )
    # Denormalized for manifest reads without a join, mirroring ProjectFunction.slug.
    pack_slug: Mapped[str] = mapped_column(String(64), nullable=False)
    pack_version: Mapped[str] = mapped_column(String(20), nullable=False)
    status: Mapped[str] = mapped_column(Text, nullable=False, default="installed")
    config: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)
    blocker: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)
    installed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    verified_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )

    __table_args__ = (
        UniqueConstraint("project_id", "pack_slug", name="uq_project_feature_pack_project_slug"),
    )


class ProjectCapabilityReconciliation(Base):
    """Durable one-time policy reconciliation state for an existing project.

    This ledger records the platform contract snapshot Core applied to Cloud.
    It deliberately does not claim that generated application source was
    rewritten; a stale installed pack is surfaced as ``upgrade_available``.
    """

    __tablename__ = "project_capability_reconciliations"

    project_id: Mapped[UUID] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("projects.id", ondelete="CASCADE"), primary_key=True
    )
    desired_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False)
    desired_snapshot: Mapped[dict] = mapped_column(JSONB, nullable=False, server_default="{}")
    status: Mapped[str] = mapped_column(
        String(40), nullable=False, server_default="pending"
    )
    required_action: Mapped[Optional[str]] = mapped_column(String(80), nullable=True)
    attempt_count: Mapped[int] = mapped_column(Integer, nullable=False, server_default="0")
    last_error: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    applied_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )
