"""Capability Model Phase 3: customer success accounts. Health is a staff-set
field, not a computed analytics engine -- that stays explicitly out of scope.

Revision ID: 155
Revises: 154
"""
from uuid import uuid4

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

revision = "155"
down_revision = "154"
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 customer_success_composition() -> dict:
    from src.domain.feature_packs.crm_authorization import staff_policy
    from src.domain.feature_packs.normalize import stamp_composition

    return stamp_composition("customer-success-accounts", {
        "function_slugs": [], "connector_actions": [], "requires": [],
        "entities": [{
            "entity_key": "customer_success_account", "name": "Customer Success Account",
            "plural_name": "Customer Success Accounts",
            "rls_enabled": False, "owner_managed": False,
            "schema": {
                "fields": [
                    {"key": "account_reference", "name": "Account reference", "type": "text", "required": True, "indexed": True},
                    {"key": "onboarding_stage", "name": "Onboarding stage", "type": "select",
                     "options": ["not_started", "in_progress", "complete"]},
                    {"key": "health", "name": "Health", "type": "select",
                     "indexed": True, "options": ["healthy", "at_risk", "critical"]},
                    {"key": "escalation_status", "name": "Escalation status", "type": "select",
                     "options": ["none", "open", "resolved"]},
                    {"key": "notes", "name": "Notes", "type": "text"},
                ],
                "access_policy": staff_policy(),
            },
        }],
    }, implementation_version="1.0.0")


def upgrade() -> None:
    op.get_bind().execute(insert(feature_packs).values(
        id=uuid4(), slug="customer-success-accounts", name="Customer Success Accounts", version="1.0.0",
        description=(
            "Staff-managed onboarding/health/escalation tracking per customer or "
            "organization. Health is staff-set/configuration-driven, not computed."
        ),
        tags=["customer_success"], status="active", composition=customer_success_composition(),
        input_schema={"type": "object", "properties": {}}, access_policy={"minimum_plan": "free"},
    ).on_conflict_do_nothing(index_elements=["slug"]))


def downgrade() -> None:
    pass
