"""add missing columns policy_id provider_id is_multimodal

@ADR [LOG-003] Catch-up migration for columns added in inserted revisions.
@RATIONALE Migrations 9f8e7d6c5b4a (is_multimodal), a7b1c2d3e4f5 (provider_id),
  and b1c2d3e4f5a6 (policy_id) were inserted into the chain before the
  existing head 86c7b1d6a710. Databases already at 86c7b1d6a710 skip them
  because Alembic sees no gap between current and target revision.
  This migration adds the same columns with 86c7b1d6a710 as parent, so
  it runs on both fresh and pre-stamped databases.

Revision ID: 2df63b7ce038
Revises: 86c7b1d6a710
Create Date: 2026-05-27 11:17:26.789634

"""
from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision: str = '2df63b7ce038'
down_revision: str | Sequence[str] | None = '86c7b1d6a710'
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Upgrade schema."""
    # Use IF NOT EXISTS — this is a catch-up migration for columns that
    # may already exist (inserted by out-of-band schema changes).
    conn = op.get_bind()

    # Add is_multimodal to llm_providers (from 9f8e7d6c5b4a)
    if not _column_exists(conn, "llm_providers", "is_multimodal"):
        op.add_column("llm_providers",
            sa.Column("is_multimodal", sa.Boolean(), nullable=False, server_default="false")
        )
        op.alter_column("llm_providers", "is_multimodal", server_default=None)

    # Add provider_id to validation_policies (from a7b1c2d3e4f5)
    if not _column_exists(conn, "validation_policies", "provider_id"):
        op.add_column("validation_policies",
            sa.Column("provider_id", sa.String(), nullable=True)
        )

    # Add policy_id to llm_validation_results (from b1c2d3e4f5a6)
    if not _column_exists(conn, "llm_validation_results", "policy_id"):
        op.add_column("llm_validation_results",
            sa.Column("policy_id", sa.String(), nullable=True, index=True)
        )


def _column_exists(conn, table: str, column: str) -> bool:
    """Check if a column exists in the given table."""
    from sqlalchemy import text
    result = conn.execute(
        text(
            "SELECT 1 FROM information_schema.columns "
            "WHERE table_name = :table AND column_name = :column"
        ),
        {"table": table, "column": column},
    )
    return result.scalar() is not None


def downgrade() -> None:
    """Downgrade schema."""
    op.drop_column("llm_validation_results", "policy_id")
    op.drop_column("validation_policies", "provider_id")
    op.drop_column("llm_providers", "is_multimodal")
