"""Remove link between v1 and v2 tasks/workflowtasks tables

Revision ID: d9a140db5d42
Revises: 5bf02391cfef
Create Date: 2024-09-09 14:15:34.415926

"""
import sqlalchemy as sa
from alembic import op

from fractal_server.migrations.naming_convention import NAMING_CONVENTION

# revision identifiers, used by Alembic.
revision = "d9a140db5d42"
down_revision = "091b01f51f88"
branch_labels = None
depends_on = None


def upgrade() -> None:
    with op.batch_alter_table("workflowtaskv2") as batch_op:
        batch_op.alter_column(
            "task_id", existing_type=sa.INTEGER(), nullable=False
        )

    # NOTE: in sqlite, this `drop_constraint` only works if
    # `batch_alter_table` has a `naming_convention` set. Ref
    # https://alembic.sqlalchemy.org/en/latest/batch.html#dropping-unnamed-or-named-foreign-key-constraints
    with op.batch_alter_table(
        "workflowtaskv2", naming_convention=NAMING_CONVENTION
    ) as batch_op:
        batch_op.drop_constraint(
            "fk_workflowtaskv2_task_legacy_id_task", type_="foreignkey"
        )

    # NOTE: in sqlite, the `drop_index` command fails if the existing table
    # has zero rows, while it succeeds if there are already some rows
    if op.get_bind().dialect.name == "sqlite":
        import sqlite3
        import logging

        logger = logging.getLogger("alembic.runtime.migration")
        logger.warning(
            f"Using sqlite, with {sqlite3.version=} and "
            f"{sqlite3.sqlite_version=}"
        )
        logger.warning("Now drop index 'idx_workflowtaskv2_task_legacy_id'")
        try:
            with op.batch_alter_table("workflowtaskv2") as batch_op:
                batch_op.drop_index("idx_workflowtaskv2_task_legacy_id")
        except sa.exc.OperationalError:
            logger.warning(
                "Could not drop index; "
                "this is expected, when the database is empty."
            )
            logger.warning("Continue.")

    with op.batch_alter_table(
        "workflowtaskv2", schema=None, naming_convention=NAMING_CONVENTION
    ) as batch_op:
        batch_op.drop_column("is_legacy_task")
        batch_op.drop_column("task_legacy_id")

    with op.batch_alter_table("task") as batch_op:
        batch_op.drop_column("is_v2_compatible")


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("task", schema=None) as batch_op:
        batch_op.add_column(
            sa.Column(
                "is_v2_compatible",
                sa.BOOLEAN(),
                server_default=sa.text("(false)"),
                nullable=False,
            )
        )
    with op.batch_alter_table("workflowtaskv2", schema=None) as batch_op:
        batch_op.add_column(
            sa.Column("task_legacy_id", sa.INTEGER(), nullable=True)
        )
        batch_op.add_column(
            sa.Column("is_legacy_task", sa.BOOLEAN(), nullable=False)
        )
        batch_op.create_foreign_key(
            "fk_workflowtaskv2_task_legacy_id_task",
            "task",
            ["task_legacy_id"],
            ["id"],
        )
        batch_op.alter_column(
            "task_id", existing_type=sa.INTEGER(), nullable=True
        )

    # ### end Alembic commands ###
