"""remove pi config and state mounts from pi-agent manifest

Revision ID: 8c6d1dbd4798
Revises: 2026_06_13_make_clone_mode_nullable
Create Date: 2026-06-13 11:21:25.983178
"""

import json

from alembic import op
import sqlalchemy as sa



# revision identifiers, used by Alembic.
revision = '8c6d1dbd4798'
down_revision = '2026_06_13_make_clone_mode_nullable'
branch_labels = None
depends_on = None


def _load_manifest(manifest_json):
    return manifest_json if isinstance(manifest_json, dict) else json.loads(manifest_json)


def upgrade() -> None:
    """Remove pi_state and pi_config mounts from the pi-agent manifest."""
    conn = op.get_bind()

    result = conn.execute(
        sa.text(
            "SELECT id, manifest FROM tool_definition_manifests WHERE name = 'pi-agent'"
        )
    )
    row = result.fetchone()
    if not row:
        return

    manifest_id, manifest_json = row
    manifest = _load_manifest(manifest_json)

    mounts = manifest.get("mounts", [])
    original_count = len(mounts)

    filtered_mounts = [
        m for m in mounts if m.get("name") not in ("pi_state", "pi_config")
    ]

    if len(filtered_mounts) < original_count:
        manifest["mounts"] = filtered_mounts
        conn.execute(
            sa.text(
                "UPDATE tool_definition_manifests SET manifest = :manifest WHERE id = :id"
            ),
            {
                "manifest": json.dumps(manifest),
                "id": manifest_id,
            },
        )


def downgrade() -> None:
    """Restore pi_state and pi_config mounts to the pi-agent manifest."""
    conn = op.get_bind()

    result = conn.execute(
        sa.text(
            "SELECT id, manifest FROM tool_definition_manifests WHERE name = 'pi-agent'"
        )
    )
    row = result.fetchone()
    if not row:
        return

    manifest_id, manifest_json = row
    manifest = _load_manifest(manifest_json)

    mounts = manifest.get("mounts", [])
    existing_names = {m.get("name") for m in mounts}

    if "pi_state" not in existing_names:
        mounts.append(
            {
                "name": "pi_state",
                "target": "/tmp/.pi/agents",
                "source_type": "instance",
                "writable": True,
            }
        )

    if "pi_config" not in existing_names:
        mounts.append(
            {
                "name": "pi_config",
                "target": "/home/user/.pi",
                "source_type": "git_mount",
                "git_mount_ref": "dotfiles",
                "writable": True,
                "owner": "user",
            }
        )

    manifest["mounts"] = mounts
    conn.execute(
        sa.text(
            "UPDATE tool_definition_manifests SET manifest = :manifest WHERE id = :id"
        ),
        {
            "manifest": json.dumps(manifest),
            "id": manifest_id,
        },
    )
