# -*- coding: utf-8 -*-
"""Location: ./mcpgateway/alembic/versions/8a16a77260f0_adding_original_description_column_to_.py
Copyright 2026
SPDX-License-Identifier: Apache-2.0
Authors: Mihai Criveti

adding original_description column to tools table

Revision ID: 8a16a77260f0
Revises: ba202ac1665f
Create Date: 2026-02-09 19:44:36.365036
"""

# Standard
from typing import Sequence, Union

# Third-Party
from alembic import op
import sqlalchemy as sa

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


def upgrade() -> None:
    """Upgrade schema."""
    inspector = sa.inspect(op.get_bind())

    # Skip if table doesn't exist (fresh DB uses db.py models directly)
    if "tools" not in inspector.get_table_names():
        return

    # Skip if column already exists
    columns = [col["name"] for col in inspector.get_columns("tools")]
    if "original_description" in columns:
        return

    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("tools", sa.Column("original_description", sa.Text(), nullable=True))
    # ### end Alembic commands ###

    # Copy data from description to original_description
    connection = op.get_bind()
    connection.execute(sa.text("UPDATE tools SET original_description = description WHERE description IS NOT NULL"))


def downgrade() -> None:
    """Downgrade schema."""

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

    if "tools" not in inspector.get_table_names():
        return

    columns = [col["name"] for col in inspector.get_columns("tools")]
    if "original_description" in columns:
        op.drop_column("tools", "original_description")

    # ### end Alembic commands ###
