from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
MIGRATION = (
    ROOT / "migrations" / "versions" / "20260719_80_mcp_gateway_control_plane.py"
)


def test_v53_migration_adds_persistent_scope_canary_and_operation_state():
    source = MIGRATION.read_text(encoding="utf-8")

    assert 'revision = "20260719_80"' in source
    assert 'down_revision = "20260719_70"' in source
    assert "business_domain" in source
    assert "created_by_subject" in source
    assert "workflow_canary_evidence" in source
    assert "workflow_gateway_operations" in source
    assert "UNIQUE (action, idempotency_key)" in source
    assert "workflow_plan_audits" in source
    assert "actor_subject" in source
    assert "idempotent_replay" in source
    assert "parent_run_id" in source
    assert "run_metadata" in source


def test_v53_migration_has_a_safe_explicit_downgrade():
    source = MIGRATION.read_text(encoding="utf-8")
    downgrade = source.split("def downgrade() -> None:", 1)[1]

    assert "DROP TABLE IF EXISTS public.workflow_gateway_operations" in downgrade
    assert "DROP TABLE IF EXISTS public.workflow_canary_evidence" in downgrade
    assert "DROP COLUMN IF EXISTS business_domain" in downgrade
    assert "DROP COLUMN IF EXISTS actor_subject" in downgrade
    assert "DROP COLUMN IF EXISTS parent_run_id" in downgrade
