"""add_adapter_path_to_fine_tuned_models

Revision ID: 533e97f2b74c
Revises: 06f6460f4c0e
Create Date: 2025-10-18 09:18:09.553152

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import sqlite

# revision identifiers, used by Alembic.
revision: str = "533e97f2b74c"
down_revision: Union[str, None] = "06f6460f4c0e"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # NOTE: This migration is now a no-op because migration 810df6adb9db already
    # creates the fine_tuned_models table with adapter_path column and unique constraint.
    # The original batch_alter_table operations caused circular dependency errors.
    # Keeping this migration file to maintain migration history continuity.

    # Check if table exists
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    if "fine_tuned_models" not in inspector.get_table_names():
        # Table doesn't exist yet, skip
        return

    # Clean up any leftover temporary table from previous failed migration attempts
    connection.execute(
        sa.text("DROP TABLE IF EXISTS _alembic_tmp_fine_tuned_models")
    )

    # Handle duplicate names by appending numbers (in case table was created elsewhere)
    # This cleanup is necessary because:
    # 1. Migration 810df6adb9db creates the table without unique constraint
    # 2. This migration adds the unique constraint but needs to ensure no duplicates exist first
    # 3. If duplicates exist (from manual entries or previous issues), rename them to prevent constraint violation
    result = connection.execute(
        sa.text(
            """
            SELECT name, COUNT(*) as count 
            FROM fine_tuned_models 
            GROUP BY name 
            HAVING count > 1
        """
        )
    )

    duplicates = result.fetchall()
    for name, count in duplicates:
        # Get all records with this name
        records = connection.execute(
            sa.text(
                "SELECT id FROM fine_tuned_models WHERE name = :name ORDER BY id"
            ),
            {"name": name},
        ).fetchall()

        # Keep first one, rename others
        for i, (record_id,) in enumerate(records[1:], start=2):
            new_name = f"{name}_{i}"
            connection.execute(
                sa.text(
                    "UPDATE fine_tuned_models SET name = :new_name WHERE id = :id"
                ),
                {"new_name": new_name, "id": record_id},
            )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # Remove adapter_path column and unique constraint
    with op.batch_alter_table("fine_tuned_models", schema=None) as batch_op:
        batch_op.drop_constraint("uq_fine_tuned_models_name", type_="unique")
        batch_op.drop_column("adapter_path")
    # ### end Alembic commands ###
