"""head_auto_apply_run + earned-auto-apply settings (#114)

A graduated head can apply its tag without a human, gated by a master switch +
a support floor. head_auto_apply_run tracks each sweep / dry-run preview.

Revision ID: 0059
Revises: 0058
Create Date: 2026-06-29
"""
from typing import Sequence, Union

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

revision: str = "0059"
down_revision: Union[str, None] = "0058"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "head_auto_apply_run",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column(
            "dry_run", sa.Boolean(), nullable=False, server_default=sa.false()
        ),
        sa.Column("params", JSONB(), nullable=False),
        sa.Column(
            "status", sa.String(length=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("n_applied", sa.Integer(), nullable=True),
        sa.Column("report", JSONB(), nullable=True),
        sa.Column("error", sa.Text(), nullable=True),
        sa.Column("last_progress_at", sa.DateTime(timezone=True), nullable=True),
    )
    op.create_index(
        "ix_head_auto_apply_run_status", "head_auto_apply_run", ["status"],
    )

    op.add_column(
        "ml_settings",
        sa.Column(
            "head_auto_apply_enabled", sa.Boolean(), nullable=False,
            server_default=sa.true(),  # opt-out: on by default (operator-asked)
        ),
    )
    op.add_column(
        "ml_settings",
        sa.Column(
            "head_auto_apply_min_positives", sa.Integer(), nullable=False,
            server_default="30",
        ),
    )


def downgrade() -> None:
    op.drop_column("ml_settings", "head_auto_apply_min_positives")
    op.drop_column("ml_settings", "head_auto_apply_enabled")
    op.drop_index(
        "ix_head_auto_apply_run_status", table_name="head_auto_apply_run"
    )
    op.drop_table("head_auto_apply_run")
