"""Complete the contact-capture pack: real notify + retry functions, not schema-only.

v1.0.0 declared a contact_submission entity with a status/notify_error design but
function_slugs: [] -- nothing ever set those fields. Wires in the two new library
functions (contact-capture-notify, contact-capture-retry, seeded via
scripts/seed_function_library.py before this migration runs), adds notify_attempts
so the retry function can bound itself to 3 attempts, and replaces the unwireable
crm_connector_action free-text field (no platform mechanism lets a deployed
function invoke an arbitrary connector action chosen at install time) with a
required notify_to_email destination address.

Revision ID: 107
Revises: 106
"""
from datetime import datetime, timezone

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = "107"
down_revision = "106"
branch_labels = None
depends_on = None

feature_packs = sa.table(
    "feature_packs",
    sa.column("slug", sa.String),
    sa.column("version", sa.String),
    sa.column("composition", postgresql.JSONB),
    sa.column("input_schema", postgresql.JSONB),
    sa.column("updated_at", sa.DateTime(timezone=True)),
)

_NOTIFY_STATIC_ENV = {"static_env_vars": {"NOTIFY_TO_EMAIL": "$config.notify_to_email"}}

_COMPOSITION = {
    "entities": [
        {
            "entity_key": "contact_submission",
            "name": "Contact Submission",
            "plural_name": "Contact Submissions",
            "schema": {
                "fields": [
                    {"key": "name", "name": "Name", "type": "text", "required": True},
                    {"key": "email", "name": "Email", "type": "text", "indexed": True, "required": True},
                    {"key": "message", "name": "Message", "type": "text", "required": True},
                    {
                        "key": "status", "name": "Status", "type": "select", "indexed": True,
                        "options": ["received", "notified", "synced", "failed"],
                    },
                    {"key": "notify_error", "name": "Notify Error", "type": "text"},
                    {"key": "notify_attempts", "name": "Notify Attempts", "type": "number", "indexed": True},
                ],
            },
        },
    ],
    "requires": [],
    "requires_connections": ["resend"],
    "connector_actions": [],
    "function_slugs": [
        {
            "library_slug": "contact-capture-notify",
            "project_slug": "contact-capture-notify",
            "trigger_config": {"event_type": "record.created", **_NOTIFY_STATIC_ENV},
        },
        {
            "library_slug": "contact-capture-retry",
            "project_slug": "contact-capture-retry",
            "trigger_config": {"cron": "0 * * * *", **_NOTIFY_STATIC_ENV},
        },
    ],
}

_INPUT_SCHEMA = {
    "type": "object",
    "required": ["notify_to_email"],
    "properties": {
        "notify_email": {
            "type": "boolean",
            "default": True,
            "description": "Send the site owner an email when a new submission arrives.",
        },
        "notify_to_email": {
            "type": "string",
            "format": "email",
            "description": "Destination address for new-submission notifications and retry recovery.",
        },
    },
}


def upgrade() -> None:
    op.execute(
        sa.update(feature_packs)
        .where(feature_packs.c.slug == "contact-capture")
        .values(
            version="1.1.0",
            composition=_COMPOSITION,
            input_schema=_INPUT_SCHEMA,
            updated_at=datetime.now(timezone.utc),
        )
    )


def downgrade() -> None:
    op.execute(
        sa.update(feature_packs)
        .where(feature_packs.c.slug == "contact-capture")
        .values(
            version="1.0.0",
            composition={
                "entities": [
                    {
                        "entity_key": "contact_submission",
                        "name": "Contact Submission",
                        "plural_name": "Contact Submissions",
                        "schema": {
                            "fields": [
                                {"key": "name", "name": "Name", "type": "text", "required": True},
                                {"key": "email", "name": "Email", "type": "text", "indexed": True, "required": True},
                                {"key": "message", "name": "Message", "type": "text", "required": True},
                                {
                                    "key": "status", "name": "Status", "type": "select", "indexed": True,
                                    "options": ["received", "notified", "synced", "failed"],
                                },
                                {"key": "notify_error", "name": "Notify Error", "type": "text"},
                            ],
                        },
                    },
                ],
                "requires": [],
                "function_slugs": [],
                "connector_actions": [],
            },
            input_schema={
                "type": "object",
                "properties": {
                    "notify_email": {"type": "boolean", "default": True},
                    "crm_connector_action": {
                        "type": "string",
                        "description": "Optional connector action to upsert the submission as a CRM lead/contact, e.g. hubspot.upsert_contact.",
                    },
                },
            },
        )
    )
