"""content-ingest: first consumer of the external.entity_ingest primitive
(verified webhook -> bounded payload mapping -> idempotent entity upsert).
Provisions a default content_item entity; provides/events/webhook_bindings/
entity_ingest_bindings/security/planner come from the catalog_v2.py overlay
via stamp_composition, same as contract-management (156).

Revision ID: 187
Revises: 186
"""
from uuid import uuid4

from alembic import op
from sqlalchemy.dialects.postgresql import JSONB, UUID, insert
import sqlalchemy as sa

revision = "187"
down_revision = "186"
branch_labels = None
depends_on = None

feature_packs = sa.table("feature_packs",
    sa.column("id", UUID(as_uuid=True)), sa.column("slug", sa.String),
    sa.column("name", sa.String), sa.column("description", sa.Text),
    sa.column("version", sa.String),
    sa.column("tags", JSONB),
    sa.column("status", sa.String),
    sa.column("composition", JSONB),
    sa.column("input_schema", JSONB),
    sa.column("access_policy", JSONB),
)


def content_ingest_composition() -> dict:
    from src.domain.feature_packs.normalize import stamp_composition

    return stamp_composition("content-ingest", {
        "function_slugs": [], "connector_actions": [], "requires": [],
        "entities": [{
            "entity_key": "content_item", "name": "Content Item", "plural_name": "Content Items",
            # No access_policy.roles here, same as contact-capture (099): a
            # public_create-ownership entity's authorization comes from the
            # overlay's `security` block, not a per-role access_policy grant.
            "schema": {
                "fields": [
                    {"key": "title", "name": "Title", "type": "text", "required": True},
                    {"key": "slug", "name": "Slug", "type": "text", "indexed": True},
                    {"key": "body", "name": "Body", "type": "text"},
                    {"key": "excerpt", "name": "Excerpt", "type": "text"},
                    {"key": "cover_image_file_id", "name": "Cover image", "type": "text"},
                    {"key": "published_at", "name": "Published at", "type": "date"},
                    {"key": "external_id", "name": "External ID", "type": "text",
                     "required": True, "indexed": True},
                    {"key": "source", "name": "Source", "type": "text",
                     "required": True, "indexed": True},
                    {"key": "status", "name": "Status", "type": "select",
                     "options": ["draft", "published"], "indexed": True},
                    {"key": "ingest_error", "name": "Ingest error", "type": "text"},
                ],
            },
        }],
    }, implementation_version="1.0.0")


def upgrade() -> None:
    op.get_bind().execute(insert(feature_packs).values(
        id=uuid4(), slug="content-ingest", name="Content Ingest", version="1.0.0",
        description=(
            "Receive content records from an external automation (Make, n8n, a "
            "customer's own backend, ...) through a governed webhook and upsert "
            "them into a content_item entity, identified by source+external_id. "
            "Pair with the content.collection App Block to present them."
        ),
        tags=["content", "webhook", "ingest"], status="active",
        composition=content_ingest_composition(),
        input_schema={"type": "object", "properties": {}},
        access_policy={"minimum_plan": "free"},
    ).on_conflict_do_nothing(index_elements=["slug"]))


def downgrade() -> None:
    pass
