#!/bin/bash
# ── Recoil Workspace Launcher ──
#
# One-command startup for the Recoil Workspace POC.
#
# Usage:
#   ./workspace/start_workspace.sh [project]
#   ./workspace/start_workspace.sh tartarus
#   ./workspace/start_workspace.sh the-afterimage --port 8450
#
# Port allocation: Pre-Prod=8420, Production Console=8430, Workspace=8450
#
# What it does:
# 1. Checks Python dependencies (fastapi, uvicorn)
# 2. Starts the FastAPI workspace server
# 3. Opens the browser
# 4. Prints MCP configuration instructions
#
# The MCP server (mcp_server.py) is NOT started here — it's started by
# Claude Code via the .claude.json mcpServers configuration.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RECOIL_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PORT="8450"

# FIX (Opus C1): Proper while/shift argument parsing instead of broken
# for-loop with shift_next pattern.
PROJECT=""
PROJECT_SET=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --port=*) PORT="${1#*=}" ;;
    --port) PORT="$2"; shift ;;
    *) if [ -z "${PROJECT_SET:-}" ]; then PROJECT="$1"; PROJECT_SET=1; fi ;;
  esac
  shift
done
PROJECT="${PROJECT:-tartarus}"

echo "╔══════════════════════════════════════════╗"
echo "║        RECOIL WORKSPACE v0.1.0           ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo "  Project:  $PROJECT"
echo "  Port:     $PORT"
echo "  Recoil:   $RECOIL_ROOT"
echo ""

# ── Check dependencies ──
echo "[1/4] Checking dependencies..."
python3 -c "import fastapi" 2>/dev/null || {
  echo "  ERROR: FastAPI not installed. Run:"
  echo "    pip install fastapi uvicorn"
  exit 1
}
python3 -c "import uvicorn" 2>/dev/null || {
  echo "  ERROR: uvicorn not installed. Run:"
  echo "    pip install uvicorn"
  exit 1
}
echo "  OK: fastapi, uvicorn installed"

# ── Verify project exists ──
echo "[2/4] Verifying project..."
PROJECTS_ROOT=$(python3 -c "
import sys; sys.path.insert(0, '$(dirname "$RECOIL_ROOT")')
from recoil.core.paths import projects_root; print(projects_root())
")
if [ ! -d "$PROJECTS_ROOT/$PROJECT" ]; then
  echo "  ERROR: Project '$PROJECT' not found at $PROJECTS_ROOT/$PROJECT"
  echo "  Available projects:"
  ls "$PROJECTS_ROOT" | grep -v "^_" | sed 's/^/    /'
  exit 1
fi
echo "  OK: $PROJECTS_ROOT/$PROJECT"

# ── Check for MCP configuration ──
echo "[3/4] MCP configuration..."
MCP_CONFIG="$RECOIL_ROOT/.claude.json"
if [ -f "$MCP_CONFIG" ]; then
  if grep -q "workspace" "$MCP_CONFIG" 2>/dev/null; then
    echo "  OK: workspace MCP server configured in .claude.json"
  else
    echo "  WARN: .claude.json exists but 'workspace' MCP not configured"
    echo "  Add this to .claude.json mcpServers:"
    echo ""
    echo "    \"workspace\": {"
    echo "      \"command\": \"python3\","
    echo "      \"args\": [\"$SCRIPT_DIR/mcp_server.py\"]"
    echo "    }"
    echo ""
  fi
else
  echo "  WARN: No .claude.json found at $RECOIL_ROOT"
  echo "  Create $MCP_CONFIG with:"
  echo ""
  echo "  {"
  echo "    \"mcpServers\": {"
  echo "      \"workspace\": {"
  echo "        \"command\": \"python3\","
  echo "        \"args\": [\"$SCRIPT_DIR/mcp_server.py\"]"
  echo "      }"
  echo "    }"
  echo "  }"
  echo ""
fi

# ── Start server ──
echo "[4/4] Starting workspace server..."
echo ""
echo "  URL: http://127.0.0.1:$PORT/workspace"
echo "  API: http://127.0.0.1:$PORT/api/health"
echo ""
echo "  Press Ctrl+C to stop"
echo ""

# Open browser after a short delay
(sleep 2 && open "http://127.0.0.1:$PORT/workspace" 2>/dev/null) &

# Start the server
cd "$RECOIL_ROOT"
exec python3 -m workspace.server --project "$PROJECT" --port "$PORT"
