"""add immutable risk disposition response snapshots

Revision ID: 20260716_0012
Revises: 20260716_0011
Create Date: 2026-07-16 17:10:00
"""

from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "20260716_0012"
down_revision: str | None = "20260716_0011"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def _require_postgresql() -> None:
    dialect_name = op.get_bind().dialect.name
    if dialect_name != "postgresql":
        raise RuntimeError(
            "20260716_0012 only supports PostgreSQL; "
            f"refusing to mutate {dialect_name} without transactional JSON DDL"
        )


def _require_empty_response_snapshots_for_downgrade() -> None:
    snapshot_count = int(
        op.get_bind().scalar(
            sa.text("SELECT COUNT(*) FROM risk_disposition_events WHERE response_json IS NOT NULL")
        )
        or 0
    )
    if snapshot_count:
        raise RuntimeError(
            "cannot downgrade risk disposition response snapshots: "
            f"risk_disposition_events contains {snapshot_count} immutable snapshot(s)"
        )


def upgrade() -> None:
    _require_postgresql()
    op.add_column(
        "risk_disposition_events",
        sa.Column("response_json", sa.JSON(), nullable=True),
    )


def downgrade() -> None:
    _require_postgresql()
    # 已写入事件快照受 append-only 触发器保护；降级不能静默删除审计响应。
    _require_empty_response_snapshots_for_downgrade()
    op.drop_column("risk_disposition_events", "response_json")
