"""fc-cleanup: library_audit_run table for async transparency/single_color audits

Revision ID: 0020
Revises: 0019
Create Date: 2026-05-26

The table backs the async audit lifecycle: rule + params snapshot, status
state machine ('running' → 'ready' → 'applied'/'cancelled'/'error'), and
the matched_ids JSONB array that the apply step deletes. Capped at 50k IDs
per row by the scan task (oversize = rule too aggressive, operator narrows
before re-running).
"""
from typing import Sequence, Union

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

revision: str = "0020"
down_revision: Union[str, None] = "0019"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "library_audit_run",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("rule", sa.String(32), nullable=False),
        sa.Column("params", postgresql.JSONB(astext_type=sa.Text()), nullable=False),
        sa.Column(
            "status", sa.String(16),
            nullable=False, server_default="running",
        ),
        sa.Column(
            "started_at", sa.DateTime(timezone=True),
            nullable=False, server_default=sa.func.now(),
        ),
        sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column(
            "scanned_count", sa.Integer(),
            nullable=False, server_default="0",
        ),
        sa.Column(
            "matched_count", sa.Integer(),
            nullable=False, server_default="0",
        ),
        sa.Column(
            "matched_ids", postgresql.JSONB(astext_type=sa.Text()),
            nullable=False, server_default=sa.text("'[]'::jsonb"),
        ),
        sa.Column("error", sa.Text(), nullable=True),
    )
    op.create_index(
        "ix_library_audit_run_rule", "library_audit_run", ["rule"],
    )
    op.create_index(
        "ix_library_audit_run_status", "library_audit_run", ["status"],
    )


def downgrade() -> None:
    op.drop_index("ix_library_audit_run_status", table_name="library_audit_run")
    op.drop_index("ix_library_audit_run_rule", table_name="library_audit_run")
    op.drop_table("library_audit_run")
