"""add user model configs

Revision ID: e9b1b3d7a4c9
Revises: d4c2a9e8b731
Create Date: 2026-05-16 00:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "e9b1b3d7a4c9"
down_revision: Union[str, None] = "d4c2a9e8b731"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    table_name = "user_model_configs"

    if table_name not in inspector.get_table_names():
        op.create_table(
            table_name,
            sa.Column("id", sa.Integer(), nullable=False),
            sa.Column("user_id", sa.Integer(), nullable=False),
            sa.Column("name", sa.String(length=255), nullable=False),
            sa.Column("provider", sa.String(length=64), nullable=False),
            sa.Column("api_key", sa.Text(), nullable=False),
            sa.Column("api_base", sa.String(length=512), nullable=True),
            sa.Column("chat_model", sa.String(length=128), nullable=False),
            sa.Column("embedding_model", sa.String(length=128), nullable=False),
            sa.Column("is_active", sa.Boolean(), nullable=False),
            sa.Column("last_used_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column("created_at", sa.DateTime(), nullable=False),
            sa.Column("updated_at", sa.DateTime(), nullable=False),
            sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
            sa.PrimaryKeyConstraint("id"),
        )

    existing_indexes = {item["name"] for item in inspector.get_indexes(table_name)}
    for index_name, columns in {
        op.f("ix_user_model_configs_id"): ["id"],
        op.f("ix_user_model_configs_is_active"): ["is_active"],
        op.f("ix_user_model_configs_user_id"): ["user_id"],
    }.items():
        if index_name not in existing_indexes:
            op.create_index(index_name, table_name, columns, unique=False)


def downgrade() -> None:
    table_name = "user_model_configs"
    inspector = sa.inspect(op.get_bind())
    if table_name not in inspector.get_table_names():
        return
    existing_indexes = {item["name"] for item in inspector.get_indexes(table_name)}
    for index_name in [
        op.f("ix_user_model_configs_user_id"),
        op.f("ix_user_model_configs_is_active"),
        op.f("ix_user_model_configs_id"),
    ]:
        if index_name in existing_indexes:
            op.drop_index(index_name, table_name=table_name)
    op.drop_table(table_name)
