#!/bin/bash

set -e

# Get script directory for relative imports
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Step 1: Check cursor-agent (check actual locations, not just PATH)
CURSOR_AGENT_PATH=""
if command -v cursor-agent &> /dev/null; then
    CURSOR_AGENT_PATH=$(command -v cursor-agent)
elif [ -x "$HOME/.local/bin/cursor-agent" ]; then
    CURSOR_AGENT_PATH="$HOME/.local/bin/cursor-agent"
elif [ -x "$HOME/.cursor/bin/cursor-agent" ]; then
    CURSOR_AGENT_PATH="$HOME/.cursor/bin/cursor-agent"
fi

if [ -z "$CURSOR_AGENT_PATH" ]; then
    echo "⚠️  cursor-agent not found. Installing..."
    curl https://cursor.com/install -fsS | bash
    # Check again after install
    if [ -x "$HOME/.local/bin/cursor-agent" ]; then
        CURSOR_AGENT_PATH="$HOME/.local/bin/cursor-agent"
    elif [ -x "$HOME/.cursor/bin/cursor-agent" ]; then
        CURSOR_AGENT_PATH="$HOME/.cursor/bin/cursor-agent"
    fi
fi

# Always ensure these directories are in PATH for this script
export PATH="$HOME/.cursor/bin:$HOME/.local/bin:$PATH"

# Step 2: Find Node.js absolute paths (Cursor GUI doesn't have shell PATH)
NODE_PATH=$(which node 2>/dev/null || echo "")
NPX_PATH=$(which npx 2>/dev/null || echo "")
NODE_BIN_DIR=$(dirname "$NODE_PATH" 2>/dev/null || echo "")

if [ -z "$NODE_PATH" ]; then
    echo "❌ node not found. Please install Node.js"
    exit 1
fi

echo "   Using Node: $NODE_PATH"

# Step 3: Find Zibby MCP Browser (stable IDs + event recording)
echo "Setting up Zibby MCP Browser..."

# Resolve @zibby/mcp-browser from node_modules (works in workspace, global, and npx installs)
ZIBBY_MCP_PKG=$("$NODE_PATH" -e "try{console.log(require.resolve('@zibby/mcp-browser/package.json',{paths:['$SCRIPT_DIR/..']}))}catch{}" 2>/dev/null)
if [ -n "$ZIBBY_MCP_PKG" ]; then
  ZIBBY_MCP_BIN="$(dirname "$ZIBBY_MCP_PKG")/bin/mcp-browser-zibby.js"
fi

# Fallback: try workspace path (dev only)
if [ -z "$ZIBBY_MCP_BIN" ] || [ ! -f "$ZIBBY_MCP_BIN" ]; then
  ZIBBY_MCP_DIR="$SCRIPT_DIR/../../mcps/browser"
  if [ -f "$ZIBBY_MCP_DIR/bin/mcp-browser-zibby.js" ]; then
    ZIBBY_MCP_BIN="$ZIBBY_MCP_DIR/bin/mcp-browser-zibby.js"
  fi
fi

# Final fallback: official @playwright/mcp (no stable IDs or event recording)
if [ -z "$ZIBBY_MCP_BIN" ] || [ ! -f "$ZIBBY_MCP_BIN" ]; then
  PLAYWRIGHT_MCP_PKG=$("$NODE_PATH" -e "try{console.log(require.resolve('@playwright/mcp/package.json',{paths:['$SCRIPT_DIR/..']}))}catch{}" 2>/dev/null)
  if [ -n "$PLAYWRIGHT_MCP_PKG" ]; then
    ZIBBY_MCP_BIN="$(dirname "$PLAYWRIGHT_MCP_PKG")/cli.js"
    echo "   ⚠️  Using @playwright/mcp (official) — stable IDs and event recording unavailable"
  fi
fi

if [ -z "$ZIBBY_MCP_BIN" ] || [ ! -f "$ZIBBY_MCP_BIN" ]; then
  echo "❌ No Playwright MCP found. Run: npm install @zibby/mcp-browser"
  exit 1
fi

echo "   ✅ Zibby MCP Browser ready"

# Install ffmpeg for video recording
echo "🎬 Installing ffmpeg for video recording..."
if command -v playwright &> /dev/null 2>&1; then
  playwright install ffmpeg > /dev/null 2>&1 && echo "   ✅ ffmpeg installed" || echo "   ⚠️  Could not install ffmpeg"
else
  "$NPX_PATH" --yes playwright install ffmpeg > /dev/null 2>&1 && echo "   ✅ ffmpeg installed" || echo "   ⚠️  Could not install ffmpeg (will disable video)"
fi

# Step 4: Configure MCP
echo "Configuring Zibby MCP Browser..."
mkdir -p ~/.cursor

# Default viewport size (can be overridden via env)
VIEWPORT_WIDTH="${ZIBBY_VIEWPORT_WIDTH:-1280}"
VIEWPORT_HEIGHT="${ZIBBY_VIEWPORT_HEIGHT:-720}"
VIEWPORT_SIZE="${VIEWPORT_WIDTH}x${VIEWPORT_HEIGHT}"

# Build MCP args array
# --save-video is stripped by the Zibby wrapper before forwarding to @playwright/mcp,
# but the wrapper reads the resolution from it to auto-start video recording.
MCP_ARGS="\"--save-video=${VIEWPORT_SIZE}\", \"--viewport-size=${VIEWPORT_SIZE}\", \"--output-dir=test-results\""

# Check if headless mode requested (default is headed)
if [ "$ZIBBY_HEADLESS" = "1" ]; then
  MCP_ARGS="$MCP_ARGS, \"--headless\""
  echo "   Mode: Headless (hidden browser)"
else
  echo "   Mode: Headed (visible browser)"
fi

# Check if video recording requested (default is on)
if [ "$ZIBBY_VIDEO" != "off" ]; then
  echo "   Video: Enabled (${VIEWPORT_SIZE})"
else
  MCP_ARGS="\"--viewport-size=${VIEWPORT_SIZE}\", \"--output-dir=test-results\""
  if [ "$ZIBBY_HEADLESS" = "1" ]; then
    MCP_ARGS="$MCP_ARGS, \"--headless\""
  fi
  echo "   Video: Disabled"
fi

# Cloud sync is handled by the CLI/Studio directly (old mcp-server package removed).
cat > ~/.cursor/mcp.json <<EOF
{
  "mcpServers": {
    "playwright-official": {
      "command": "$NODE_PATH",
      "args": ["$ZIBBY_MCP_BIN", $MCP_ARGS],
      "env": {
        "PATH": "$NODE_BIN_DIR:/usr/bin:/bin:/usr/sbin:/sbin"
      },
      "description": "Zibby MCP Browser - Forked Playwright MCP with stable ID support"
    }
  }
}
EOF
echo "   + Zibby MCP Browser (stable IDs + event recording)"

# Step 5: Patch cursor-agent
echo "Patching cursor-agent..."
node "$SCRIPT_DIR/patch-cursor-mcp.js" > /dev/null 2>&1 || echo "   (patch may not be needed for your version)"

# Step 6: Get approval key
echo "🔑 Getting approval key..."
APPROVAL_OUTPUT=$(cursor-agent mcp list 2>&1)

APPROVAL_KEY_LINE=$(echo "$APPROVAL_OUTPUT" | grep "🔑 APPROVAL KEY.*playwright-official" | head -1)
echo "$APPROVAL_KEY_LINE"

APPROVAL_KEY=$(echo "$APPROVAL_KEY_LINE" | sed -E 's/.*=> ([^ ]+).*/\1/' | head -1)

if [ -z "$APPROVAL_KEY" ]; then
    APPROVAL_KEY=$(echo "$APPROVAL_OUTPUT" | grep -oE 'playwright-official-[a-f0-9]+' | head -1)
fi

if [ -z "$APPROVAL_KEY" ]; then
    echo "⚠️ Could not auto-extract approval key"
    echo "   This is OK for development - approval key only needed for CI/CD"
    echo "   For CI/CD: Run 'cursor-agent mcp list' and save the key"
else
    # Step 7: Setup workspace approvals (only if we got the key)
    echo "Configuring approvals..."
    WORKSPACE_PATH="$PWD"
    WORKSPACE_ENCODED=$(echo "$WORKSPACE_PATH" | sed 's|^/||' | sed 's|/|-|g')
    APPROVAL_DIR="$HOME/.cursor/projects/$WORKSPACE_ENCODED"
    APPROVAL_FILE="$APPROVAL_DIR/mcp-approvals.json"

    mkdir -p "$APPROVAL_DIR"
    cat > "$APPROVAL_FILE" <<EOF
["$APPROVAL_KEY"]
EOF
    echo "Auto-approval configured for this workspace"
fi

echo ""
echo "Zibby MCP Browser ready!"
echo ""
