"""Drop the A6 rollback tombstones

Revision ID: 030
Revises: 029
Create Date: 2026-08-07 00:00:00.000000

Migration ``029`` kept two SystemSetting rows alive as rollback tombstones,
pinned to the values a pre-A6 process needed to behave safely. A6 is deployed
and healthy, and the provider keys are gone from the production ``.env`` — which
makes the legacy collector inert regardless of any settings row — so the
tombstones have no remaining job.

Nothing in the current codebase reads either key.
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "030"
down_revision: Union[str, None] = "029"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


# The safe values 029 pinned. Kept here so downgrade restores real protection
# rather than leaving a rolled-back process reading absent rows permissively.
_TOMBSTONES: dict[str, str] = {
    "fundamental_data_sec_dolt_cutover_enabled": "true",
    "job_fundamental_collector_enabled": "false",
}

_settings = sa.table(
    "system_settings",
    sa.column("id", sa.Integer),
    sa.column("key", sa.String),
    sa.column("value", sa.Text),
    sa.column("updated_at", sa.DateTime(timezone=True)),
)


def upgrade() -> None:
    conn = op.get_bind()
    for key in _TOMBSTONES:
        row = conn.execute(
            sa.select(_settings.c.value).where(_settings.c.key == key)
        ).fetchone()
        if row is None:
            print(f"a6_tombstone_drop {key}: absent", flush=True)
            continue
        print(f"a6_tombstone_drop {key}: {row[0]!r}", flush=True)
        conn.execute(sa.delete(_settings).where(_settings.c.key == key))


def downgrade() -> None:
    """Restore the tombstones at their safe values.

    Unlike 029's no-op downgrade, this one is meaningful: going back past this
    revision implies going back toward code that still reads these keys.
    """
    conn = op.get_bind()
    now = sa.func.now()
    for key, pinned in _TOMBSTONES.items():
        exists = conn.execute(
            sa.select(_settings.c.id).where(_settings.c.key == key)
        ).fetchone()
        if exists is None:
            conn.execute(
                sa.insert(_settings).values(key=key, value=pinned, updated_at=now)
            )
