"""Add artifact_registries table

Revision ID: ba5207c55924
Revises: 11ee5c074009
Create Date: 2025-08-26 06:29:20.265879

"""

import sqlalchemy as sa
from alembic import op

from ai.backend.manager.models.base import GUID

# revision identifiers, used by Alembic.
revision = "ba5207c55924"
down_revision = "11ee5c074009"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "artifact_registries",
        sa.Column("id", GUID(), server_default=sa.text("uuid_generate_v4()"), nullable=False),
        sa.Column("name", sa.String(), nullable=False),
        sa.Column("registry_id", GUID(), nullable=False),
        sa.Column("type", sa.String(), nullable=False),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_artifact_registries")),
        sa.UniqueConstraint("name", name=op.f("uq_artifact_registries_name")),
        sa.UniqueConstraint("registry_id", name=op.f("uq_artifact_registries_registry_id")),
    )

    conn = op.get_bind()
    inspector = sa.inspect(conn)

    # Check if huggingface_registries table exists
    if inspector.has_table("huggingface_registries"):
        columns = [col["name"] for col in inspector.get_columns("huggingface_registries")]

        # Migrate existing huggingface_registries records to artifact_registries
        result = conn.execute(
            sa.text("""
            SELECT id, name FROM huggingface_registries
            WHERE name IS NOT NULL
        """)
        )

        for row in result:
            conn.execute(
                sa.text("""
                INSERT INTO artifact_registries (name, registry_id, type)
                VALUES (:name, :registry_id, :type)
            """),
                {"name": row.name, "registry_id": row.id, "type": "huggingface"},
            )

        # Drop the name column and constraint if they exist
        if "name" in columns:
            op.drop_constraint(
                "uq_huggingface_registries_name", "huggingface_registries", type_="unique"
            )
            op.drop_column("huggingface_registries", "name")

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    inspector = sa.inspect(conn)

    # Add name column as nullable first to avoid constraint violations
    op.add_column(
        "huggingface_registries",
        sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=True),
    )

    # Check if artifact_registries table exists and migrate data back
    if inspector.has_table("artifact_registries"):
        # Migrate data back from artifact_registries to huggingface_registries
        result = conn.execute(
            sa.text("""
            SELECT name, registry_id FROM artifact_registries
            WHERE type = 'huggingface'
        """)
        )

        for row in result:
            conn.execute(
                sa.text("""
                UPDATE huggingface_registries
                SET name = :name
                WHERE id = :registry_id
            """),
                {"name": row.name, "registry_id": row.registry_id},
            )

    # Now make the name column NOT NULL after populating data
    op.alter_column(
        "huggingface_registries",
        "name",
        existing_type=sa.VARCHAR(),
        nullable=False,
    )

    # Create the unique constraint after ensuring no null values
    op.create_unique_constraint(
        "uq_huggingface_registries_name", "huggingface_registries", ["name"]
    )
    op.drop_table("artifact_registries")
    # ### end Alembic commands ###
