"""serialize organization memory mutations and persist idempotency fingerprints

Revision ID: 20260716_0009
Revises: 20260716_0008
Create Date: 2026-07-16 14:20:00
"""

from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "20260716_0009"
down_revision: str | None = "20260716_0008"
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_0009 only supports PostgreSQL; "
            f"refusing to mutate {dialect_name} without transactional constraint DDL"
        )


def _require_unique_active_organization_scopes() -> None:
    duplicate_count = int(
        op.get_bind().scalar(
            sa.text(
                "SELECT COUNT(*) FROM ("
                "SELECT 1 FROM memory_entries "
                "WHERE status = 'active' "
                "AND scope_type IN ('department', 'enterprise') "
                "GROUP BY tenant_id, scope_type, scope_id, scene, field_key "
                "HAVING COUNT(*) > 1"
                ") AS duplicate_active_organization_scopes"
            )
        )
        or 0
    )
    if duplicate_count:
        raise RuntimeError(
            "cannot upgrade organization memory idempotency: "
            f"found {duplicate_count} organization scope(s) with duplicate active memories"
        )


def upgrade() -> None:
    _require_postgresql()
    # 必须在添加列或约束前完成数据预检，避免失败后留下半迁移结构。
    _require_unique_active_organization_scopes()
    op.add_column(
        "memory_entries",
        sa.Column("management_request_id", sa.String(length=120), nullable=True),
    )
    op.add_column(
        "memory_entries",
        sa.Column("management_payload_fingerprint", sa.String(length=80), nullable=True),
    )
    op.add_column(
        "memory_entries",
        sa.Column("revoke_request_id", sa.String(length=120), nullable=True),
    )
    op.add_column(
        "memory_entries",
        sa.Column("revoke_payload_fingerprint", sa.String(length=80), nullable=True),
    )
    op.create_check_constraint(
        "ck_memory_entries_management_idempotency_pair",
        "memory_entries",
        "(management_request_id IS NULL AND management_payload_fingerprint IS NULL) OR "
        "(management_request_id IS NOT NULL "
        "AND management_payload_fingerprint IS NOT NULL)",
    )
    op.create_check_constraint(
        "ck_memory_entries_revoke_idempotency_pair",
        "memory_entries",
        "(revoke_request_id IS NULL AND revoke_payload_fingerprint IS NULL) OR "
        "(revoke_request_id IS NOT NULL AND revoke_payload_fingerprint IS NOT NULL)",
    )
    op.create_index(
        "uq_memory_entries_management_request",
        "memory_entries",
        ["tenant_id", "management_request_id"],
        unique=True,
    )
    op.create_index(
        "uq_memory_entries_revoke_request",
        "memory_entries",
        ["tenant_id", "revoke_request_id"],
        unique=True,
    )
    op.create_index(
        "uq_memory_entries_active_scope",
        "memory_entries",
        ["tenant_id", "scope_type", "scope_id", "scene", "field_key"],
        unique=True,
        postgresql_where=sa.text(
            "status = 'active' AND scope_type IN ('department', 'enterprise')"
        ),
    )


def downgrade() -> None:
    _require_postgresql()
    op.drop_index("uq_memory_entries_active_scope", table_name="memory_entries")
    op.drop_index("uq_memory_entries_revoke_request", table_name="memory_entries")
    op.drop_index("uq_memory_entries_management_request", table_name="memory_entries")
    op.drop_constraint(
        "ck_memory_entries_revoke_idempotency_pair",
        "memory_entries",
        type_="check",
    )
    op.drop_constraint(
        "ck_memory_entries_management_idempotency_pair",
        "memory_entries",
        type_="check",
    )
    op.drop_column("memory_entries", "revoke_payload_fingerprint")
    op.drop_column("memory_entries", "revoke_request_id")
    op.drop_column("memory_entries", "management_payload_fingerprint")
    op.drop_column("memory_entries", "management_request_id")
