"""Seed feature packs round 3: approval-workflow, support-inbox, ai-knowledge-assistant.

Revision ID: 103
Revises: 102
"""
from datetime import datetime, timezone
from uuid import uuid4

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

revision = "103"
down_revision = "102"
branch_labels = None
depends_on = None

feature_packs = sa.table(
    "feature_packs",
    sa.column("id", postgresql.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", postgresql.JSONB),
    sa.column("status", sa.String),
    sa.column("composition", postgresql.JSONB),
    sa.column("input_schema", postgresql.JSONB),
    sa.column("access_policy", postgresql.JSONB),
)

_APPROVAL_REQUEST_ENTITY = {
    "entity_key": "approval_request",
    "name": "Approval Request",
    "plural_name": "Approval Requests",
    "schema": {
        "fields": [
            {"key": "title", "name": "Title", "type": "text", "required": True},
            {"key": "requested_by", "name": "Requested By", "type": "text", "required": True, "indexed": True},
            {"key": "approver_role", "name": "Approver Role", "type": "text", "required": True, "indexed": True},
            {"key": "status", "name": "Status", "type": "select",
             "options": ["pending", "approved", "rejected", "escalated"], "required": True, "indexed": True},
            {"key": "due_at", "name": "Due At", "type": "date"},
            {"key": "notes", "name": "Notes", "type": "text"},
        ],
    },
}

_SUPPORT_TICKET_ENTITY = {
    "entity_key": "support_ticket",
    "name": "Support Ticket",
    "plural_name": "Support Tickets",
    "schema": {
        "fields": [
            {"key": "subject", "name": "Subject", "type": "text", "required": True},
            {"key": "requester_email", "name": "Requester Email", "type": "text", "required": True, "indexed": True},
            {"key": "status", "name": "Status", "type": "select",
             "options": ["open", "pending", "resolved", "closed"], "required": True, "indexed": True},
            {"key": "priority", "name": "Priority", "type": "select",
             "options": ["low", "normal", "high"], "indexed": True},
            {"key": "assigned_to", "name": "Assigned To", "type": "text", "indexed": True},
        ],
    },
}

_SUPPORT_MESSAGE_ENTITY = {
    "entity_key": "support_message",
    "name": "Support Message",
    "plural_name": "Support Messages",
    "schema": {
        "fields": [
            {"key": "ticket_record_id", "name": "Ticket", "type": "relation",
             "relation_entity_key": "support_ticket", "required": True, "indexed": True},
            {"key": "sender_type", "name": "Sender Type", "type": "select",
             "options": ["owner", "customer"], "required": True, "indexed": True},
            {"key": "body", "name": "Body", "type": "text", "required": True},
        ],
    },
}

_ASSISTANT_THREAD_ENTITY = {
    "entity_key": "assistant_thread",
    "name": "Assistant Thread",
    "plural_name": "Assistant Threads",
    "schema": {
        "fields": [
            {"key": "title", "name": "Title", "type": "text"},
            {"key": "created_by", "name": "Created By", "type": "text", "indexed": True},
        ],
    },
}

_ASSISTANT_MESSAGE_ENTITY = {
    "entity_key": "assistant_message",
    "name": "Assistant Message",
    "plural_name": "Assistant Messages",
    "schema": {
        "fields": [
            {"key": "thread_record_id", "name": "Thread", "type": "relation",
             "relation_entity_key": "assistant_thread", "required": True, "indexed": True},
            {"key": "role", "name": "Role", "type": "select",
             "options": ["user", "assistant"], "required": True, "indexed": True},
            {"key": "content", "name": "Content", "type": "text", "required": True},
        ],
    },
}


def _pack(*, slug, name, description, tags, composition, input_schema, minimum_plan="free"):
    now = datetime.now(timezone.utc)
    return {
        "id": uuid4(),
        "slug": slug,
        "name": name,
        "description": description,
        "version": "1.0.0",
        "tags": tags,
        "status": "active",
        "composition": composition,
        "input_schema": input_schema,
        "access_policy": {"minimum_plan": minimum_plan},
        "created_at": now,
        "updated_at": now,
    }


def upgrade() -> None:
    op.bulk_insert(
        feature_packs,
        [
            _pack(
                slug="approval-workflow",
                name="Approval Workflow",
                description=(
                    "Requests routed to a role-scoped approver with a fixed pending/approved/"
                    "rejected/escalated state machine and a task-based audit trail — instead of "
                    "unconstrained record PATCHes that let any status jump to any other."
                ),
                tags=["operations", "approvals", "internal"],
                composition={
                    "function_slugs": ["task-create", "task-list"],
                    "entities": [_APPROVAL_REQUEST_ENTITY],
                    "connector_actions": [],
                    "requires": [],
                },
                input_schema={
                    "type": "object",
                    "properties": {
                        "approver_roles": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Platform auth custom_roles allowed to approve/reject, e.g. ['manager', 'admin'].",
                        },
                        "escalation_hours": {
                            "type": "number",
                            "description": "Hours a request may stay pending before it is flagged for escalation.",
                        },
                    },
                    "required": ["approver_roles"],
                },
            ),
            _pack(
                slug="support-inbox",
                name="Support Inbox",
                description=(
                    "A ticket + threaded-message inbox with live updates via the platform realtime "
                    "channel — for a real help-desk widget, distinct from a one-shot contact form."
                ),
                tags=["support", "helpdesk", "realtime"],
                composition={
                    "function_slugs": [],
                    "entities": [_SUPPORT_TICKET_ENTITY, _SUPPORT_MESSAGE_ENTITY],
                    "connector_actions": [],
                    "requires": [],
                },
                input_schema={
                    "type": "object",
                    "properties": {
                        "notify_email": {"type": "boolean", "default": True},
                        "enable_ai_suggested_replies": {
                            "type": "boolean",
                            "default": False,
                            "description": "Use the livechat.message capability (if enabled for this project) to draft suggested owner replies.",
                        },
                    },
                },
            ),
            _pack(
                slug="ai-knowledge-assistant",
                name="AI Knowledge Assistant",
                description=(
                    "A threaded chat assistant backed by the app owner's own OpenAI API key via "
                    "the openai connector (BYOK) — never P2HS's own managed AI credits/wallet."
                ),
                tags=["ai", "assistant", "chat"],
                composition={
                    "function_slugs": [],
                    "entities": [_ASSISTANT_THREAD_ENTITY, _ASSISTANT_MESSAGE_ENTITY],
                    "connector_actions": ["openai.chat_complete"],
                    "requires": ["openai"],
                },
                input_schema={
                    "type": "object",
                    "properties": {
                        "system_prompt": {
                            "type": "string",
                            "description": "Instructions establishing the assistant's role/scope for this app.",
                        },
                        "model": {"type": "string", "default": "gpt-4o-mini"},
                        "knowledge_base_enabled": {
                            "type": "boolean",
                            "default": False,
                            "description": "Ground responses in the manifest's knowledge_base entries when available.",
                        },
                    },
                    "required": ["system_prompt"],
                },
            ),
        ],
    )


def downgrade() -> None:
    op.execute(
        "DELETE FROM feature_packs WHERE slug IN "
        "('approval-workflow', 'support-inbox', 'ai-knowledge-assistant')"
    )
