"""remove pi agent workspace symlink

Revision ID: 2026_06_19_113000
Revises: 2026_06_15_090500
Create Date: 2026-06-19 11:30:00.000000

"""

from collections.abc import Sequence

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

# revision identifiers, used by Alembic.
revision: str = "2026_06_19_113000"
down_revision: str | Sequence[str] | None = "2026_06_15_090500"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

tool_definition_manifests = table(
    "tool_definition_manifests",
    column("id", sa.UUID),
    column("name", sa.String),
    column("manifest", sa.JSON),
)


def _find_pi_agent_manifest(
    conn: sa.Connection,
) -> tuple[str | None, dict | None]:
    result = conn.execute(
        sa.select(
            tool_definition_manifests.c.id, tool_definition_manifests.c.manifest
        ).where(tool_definition_manifests.c.name == "pi-agent")
    ).fetchone()
    if result is None:
        return None, None
    return result.id, dict(result.manifest)


def _update_manifest(conn: sa.Connection, manifest_id: str, manifest: dict) -> None:
    conn.execute(
        sa.update(tool_definition_manifests)
        .where(tool_definition_manifests.c.id == manifest_id)
        .values(manifest=manifest)
    )


def upgrade() -> None:
    conn = op.get_bind()
    manifest_id, manifest = _find_pi_agent_manifest(conn)
    if not manifest_id or not manifest:
        return

    runtime = manifest.setdefault("runtime", {})
    # The /workspace compatibility symlink is no longer created by the
    # compiler/entrypoint. Leaving working_dir set to /workspace causes the
    # container to start in an empty directory. Let compile_compose default
    # to /home/user/{workspace_name} instead.
    if runtime.get("working_dir") == "/workspace":
        del runtime["working_dir"]

    scripts = manifest.setdefault("scripts", {})
    # Update the startup script to operate on the real repo-named directory.
    scripts["startup"] = [
        'if [ -n "$WORKSPACE_NAME" ]; then sudo chown -R user:user "$HOME/$WORKSPACE_NAME" 2>/dev/null || true; fi',
    ]

    _update_manifest(conn, manifest_id, manifest)


def downgrade() -> None:
    conn = op.get_bind()
    manifest_id, manifest = _find_pi_agent_manifest(conn)
    if not manifest_id or not manifest:
        return

    runtime = manifest.setdefault("runtime", {})
    runtime["working_dir"] = "/workspace"

    scripts = manifest.setdefault("scripts", {})
    scripts["startup"] = [
        "if [ -d /workspace ]; then sudo chown -R user:user /workspace 2>/dev/null || true; fi",
    ]

    _update_manifest(conn, manifest_id, manifest)
