"""add pi agent tool type

Revision ID: 20260527_160017_add_pi_agent
Revises: f3d2dc90ba3a
Create Date: 2026-05-27T16:00:17

"""

import json
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
import uuid

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


PI_AGENT_ID = uuid.UUID("d07b8376-2151-4119-8c1d-27f792aae9a3")


def upgrade() -> None:
    # Check if pi-agent already exists
    conn = op.get_bind()
    result = conn.execute(
        sa.text("SELECT id FROM tool_types WHERE name = 'pi-agent'")
    ).fetchone()
    
    if result is None:
        conn.execute(
            sa.text("""
                INSERT INTO tool_types (
                    id, name, display_name, description, category,
                    interface_type, requires_port, default_port,
                    definition_type, compose_template, dockerfile_template, required_variables,
                    created_at, updated_at
                ) VALUES (
                    :id, :name, :display_name, :description, :category,
                    :interface_type, :requires_port, :default_port,
                    :definition_type, :compose_template, :dockerfile_template, :required_variables,
                    now(), now()
                )
            """),
            {
                "id": PI_AGENT_ID,
                "name": "pi-agent",
                "display_name": "Pi Agent",
                "description": "Pi coding agent terminal environment with nvim, ranger, and tmux",
                "category": "development",
                "interface_type": "terminal",
                "requires_port": False,
                "default_port": 0,
                "definition_type": "dockerfile",
                "compose_template": """services:
  app:
    build: .
    stdin_open: true
    tty: true
    volumes:
      - ${REPO_PATH}:/workspace
    working_dir: /workspace
    command: /bin/bash""",
                "dockerfile_template": """# Pi Coding Agent - Terminal-based coding harness
FROM ubuntu:24.04

ENV DEBIAN_FRONTEND=noninteractive

# Install base dependencies
RUN apt-get update && apt-get install -y \\
    curl \\
    wget \\
    git \\
    neovim \\
    ranger \\
    tmux \\
    htop \\
    tree \\
    jq \\
    ca-certificates \\
    python3 \\
    python3-pip \\
    build-essential \\
    && rm -rf /var/lib/apt/lists/*

# Install Node.js (required for Pi)
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \\
    && apt-get install -y nodejs \\
    && rm -rf /var/lib/apt/lists/*

# Install Pi Coding Agent globally
RUN npm install -g --ignore-scripts @earendil-works/pi-coding-agent

# Create non-root user
RUN useradd -m -s /bin/bash user
WORKDIR /home/user

# Set up git
RUN git config --global init.defaultBranch main \\
    && git config --global user.email "dev@headquarter.local" \\
    && git config --global user.name "Developer"

# Create default tmux config
RUN printf '%s\\n' 'set -g mouse on' 'set -g default-terminal "screen-256color"' > /home/user/.tmux.conf

# Create default ranger config
RUN mkdir -p /home/user/.config/ranger \\
    && printf '%s\\n' 'set preview_files true' 'set use_preview_script true' > /home/user/.config/ranger/rc.conf

# Set up Pi config directory
RUN mkdir -p /home/user/.pi/agent

USER user

# Default to bash (Pi is invoked manually via `pi` command)
CMD ["/bin/bash"]""",
                "required_variables": json.dumps(["REPO_PATH"]),
            }
        )


def downgrade() -> None:
    conn = op.get_bind()
    conn.execute(
        sa.text("DELETE FROM tool_types WHERE name = 'pi-agent'")
    )
