"""Add context_window and max_output_tokens to llm_providers

@RATIONALE llm_providers is created at runtime by init_db() →
  Base.metadata.create_all(), not by any Alembic migration. On a fresh
  database, the table doesn't exist when migrations run. Guard with
  _table_exists() — create_all() will create the table with the model's
  columns (which already include context_window and max_output_tokens).

Revision ID: a1b2c3d4e5f6
Revises: f1a2b3c4d5e6
Create Date: 2026-06-03

Add token window configuration to LLM provider records:
- context_window: total context window in tokens (nullable)
- max_output_tokens: max output tokens limit (nullable)
Both NULL = use PROVIDER_DEFAULTS fallback from model name.
"""
from typing import Sequence, Union

from alembic import op
from sqlalchemy import inspect
import sqlalchemy as sa


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


def _table_exists(table_name: str) -> bool:
    conn = op.get_bind()
    inspector = inspect(conn)
    return inspector.has_table(table_name)


def upgrade() -> None:
    if not _table_exists("llm_providers"):
        return
    op.add_column(
        "llm_providers",
        sa.Column(
            "context_window",
            sa.Integer(),
            nullable=True,
            comment="Total context window in tokens. NULL = auto-detect from model name",
        ),
    )
    op.add_column(
        "llm_providers",
        sa.Column(
            "max_output_tokens",
            sa.Integer(),
            nullable=True,
            comment="Max output tokens limit. NULL = auto-detect from model name",
        ),
    )


def downgrade() -> None:
    if not _table_exists("llm_providers"):
        return
    op.drop_column("llm_providers", "max_output_tokens")
    op.drop_column("llm_providers", "context_window")
