"""add campaigns table and eval_runs.campaign_id

Revision ID: e6c3d1a2f809
Revises: d5b8c2e4f617
Create Date: 2026-07-29
"""

from typing import Sequence, Union

import sqlalchemy as sa
import sqlmodel  # noqa: F401
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "e6c3d1a2f809"
down_revision: Union[str, Sequence[str], None] = "d5b8c2e4f617"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "campaigns",
        sa.Column("id", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
        sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
        sa.Column("target_id", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
        sa.Column("window_seconds", sa.Integer(), nullable=False),
        sa.Column("time_scale", sa.Float(), nullable=False),
        sa.Column("plan", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
        sa.Column("status", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
        sa.Column("started_at", sa.DateTime(), nullable=True),
        sa.Column("completed_at", sa.DateTime(), nullable=True),
        sa.Column("created_at", sa.DateTime(), nullable=True),
        sa.Column("summary", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
        sa.ForeignKeyConstraint(["target_id"], ["eval_targets.id"]),
        sa.PrimaryKeyConstraint("id"),
    )
    with op.batch_alter_table("eval_runs") as batch_op:
        batch_op.add_column(sa.Column("campaign_id", sqlmodel.sql.sqltypes.AutoString(), nullable=True))
        batch_op.create_foreign_key("fk_eval_runs_campaign_id", "campaigns", ["campaign_id"], ["id"])


def downgrade() -> None:
    """Remove Campaign storage without relying on SQLite foreign-key names."""
    with op.batch_alter_table("eval_runs") as batch_op:
        batch_op.drop_column("campaign_id")
    op.drop_table("campaigns")
