"""add_tool_type_home_directory

Revision ID: 2026_06_14_104415
Revises: f3d2dc90ba3a
Create Date: 2026-06-14 10:44:15.000000

"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op
from sqlalchemy.sql import column, table

# revision identifiers, used by Alembic.
revision: str = "2026_06_14_104415"
down_revision: Union[str, Sequence[str], None] = "f3d2dc90ba3a"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


tool_types = table(
    "tool_types",
    column("id", sa.UUID),
    column("home_directory", sa.String),
    column("compose_template", sa.Text),
    column("dockerfile_template", sa.Text),
)

OLD_WORKSPACE = "/workspace"
NEW_WORKSPACE = "/home/user/{{WORKSPACE_NAME}}"


def upgrade() -> None:
    # Add the new column with a default that applies to existing rows.
    op.add_column(
        "tool_types",
        sa.Column(
            "home_directory",
            sa.String(255),
            nullable=False,
            server_default="/home/user",
        ),
    )

    # Rewrite legacy templates that mount the workspace at /workspace so they
    # use the new configurable home directory and preserve the workspace name.
    op.execute(
        sa.update(tool_types)
        .where(tool_types.c.compose_template.is_not(None))
        .values(
            compose_template=sa.func.replace(
                tool_types.c.compose_template, OLD_WORKSPACE, NEW_WORKSPACE
            )
        )
    )
    op.execute(
        sa.update(tool_types)
        .where(tool_types.c.dockerfile_template.is_not(None))
        .values(
            dockerfile_template=sa.func.replace(
                tool_types.c.dockerfile_template, OLD_WORKSPACE, NEW_WORKSPACE
            )
        )
    )


def downgrade() -> None:
    # Restore the original /workspace strings before dropping the column.
    op.execute(
        sa.update(tool_types)
        .where(tool_types.c.compose_template.is_not(None))
        .values(
            compose_template=sa.func.replace(
                tool_types.c.compose_template, NEW_WORKSPACE, OLD_WORKSPACE
            )
        )
    )
    op.execute(
        sa.update(tool_types)
        .where(tool_types.c.dockerfile_template.is_not(None))
        .values(
            dockerfile_template=sa.func.replace(
                tool_types.c.dockerfile_template, NEW_WORKSPACE, OLD_WORKSPACE
            )
        )
    )

    op.drop_column("tool_types", "home_directory")
