"""Seed task-management: staff-managed task tracking, deliberately NOT reusing
the pre-Phase-9 task-create/task-list function-library's "task" entity_key.
Phase 11B2.

Revision ID: 137
Revises: 136
"""
from datetime import datetime, timezone
from uuid import uuid4

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

revision = "137"
down_revision = "136"
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),
)

# entity_key is "platform_task", not "task" -- seeds/function_library/task-create.yaml
# already creates an ungoverned "task" entity (no access_policy, no schema.workflow)
# on any project where approval-workflow's function_slugs ran. create_project_entity
# is create-only and its reconcile step only patches rls_enabled/owner_managed/
# owner_singleton (service.py) -- reusing "task" would mean this pack's
# access_policy/workflow silently never applies on any project where the legacy
# function already created the bare entity. See docs/audits/TASK_MANAGEMENT_11B2.md.
_PLATFORM_TASK_ENTITY = {
    "entity_key": "platform_task",
    "name": "Task",
    "plural_name": "Tasks",
    "schema": {
        "fields": [
            {"key": "title", "name": "Title", "type": "text", "required": True},
            {"key": "description", "name": "Description", "type": "text"},
            {
                "key": "status", "name": "Status", "type": "select",
                "required": True, "indexed": True,
                "options": ["todo", "in_progress", "done"],
            },
            {"key": "due_date", "name": "Due Date", "type": "date"},
            {
                "key": "subject_entity_key", "name": "Subject Entity", "type": "text",
                "indexed": True,
            },
            {
                "key": "subject_record_id", "name": "Subject Record", "type": "text",
                "indexed": True,
            },
        ],
    },
}


def upgrade() -> None:
    from src.domain.feature_packs.normalize import stamp_composition

    now = datetime.now(timezone.utc)
    raw_composition = {
        "function_slugs": [],
        "entities": [_PLATFORM_TASK_ENTITY],
        "connector_actions": [],
        "requires": ["workflow.transition"],
    }
    op.bulk_insert(
        feature_packs,
        [
            {
                "id": uuid4(),
                "slug": "task-management",
                "name": "Task Management",
                "description": (
                    "Staff-managed task tracking with an enforced status graph. "
                    "Optional subject reference (subject_entity_key/subject_record_id) "
                    "so a task may relate to any other record; assignment composes "
                    "with the assignment-tracking pack rather than an assignee field "
                    "here. Not the legacy task-create/task-list function library -- "
                    "that entity_key ('task') is a separate, ungoverned, contained-"
                    "compatibility mechanism this pack does not touch or reuse."
                ),
                "version": "1.0.0",
                "tags": ["workflow", "tasks", "operations"],
                "status": "active",
                "composition": stamp_composition("task-management", raw_composition),
                "input_schema": {"type": "object", "properties": {}},
                "access_policy": {"minimum_plan": "free"},
                "created_at": now,
                "updated_at": now,
            },
        ],
    )


def downgrade() -> None:
    op.execute("DELETE FROM feature_packs WHERE slug = 'task-management'")
