"""head_metric + head_metrics_snapshot: auto-apply observability (#114)

Running misfire/under-fire counters per concept (captured at correction time,
since image_tag.source is lost on delete) + a daily per-concept time-series so
the operator can tune the precision target + support floor from real data.

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

import sqlalchemy as sa
from alembic import op

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


def upgrade() -> None:
    op.create_table(
        "head_metric",
        sa.Column(
            "tag_id", sa.Integer(),
            sa.ForeignKey("tag.id", ondelete="CASCADE"), primary_key=True,
        ),
        sa.Column("n_misfires", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("n_underfires", sa.Integer(), nullable=False, server_default="0"),
        sa.Column(
            "updated_at", sa.DateTime(timezone=True), nullable=False,
            server_default=sa.func.now(),
        ),
    )

    op.create_table(
        "head_metrics_snapshot",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column(
            "tag_id", sa.Integer(),
            sa.ForeignKey("tag.id", ondelete="CASCADE"),
        ),
        sa.Column("name", sa.String(length=255), nullable=False),
        sa.Column(
            "snapshot_at", sa.DateTime(timezone=True), nullable=False,
            server_default=sa.func.now(),
        ),
        sa.Column("n_auto_applied", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("n_misfires", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("n_underfires", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("ap", sa.Float(), nullable=True),
        sa.Column("precision_cv", sa.Float(), nullable=True),
        sa.Column("recall", sa.Float(), nullable=True),
        sa.Column("n_pos", sa.Integer(), nullable=True),
    )
    op.create_index(
        "ix_head_metrics_snapshot_tag_id", "head_metrics_snapshot", ["tag_id"],
    )
    op.create_index(
        "ix_head_metrics_snapshot_snapshot_at", "head_metrics_snapshot",
        ["snapshot_at"],
    )


def downgrade() -> None:
    op.drop_index(
        "ix_head_metrics_snapshot_snapshot_at", table_name="head_metrics_snapshot"
    )
    op.drop_index(
        "ix_head_metrics_snapshot_tag_id", table_name="head_metrics_snapshot"
    )
    op.drop_table("head_metrics_snapshot")
    op.drop_table("head_metric")
