#!/bin/bash
# ╔══════════════════════════════════════════════════════════════╗
# ║  atomic*HR LinkedIn — Start MCP + Tunnel                    ║
# ║                                                              ║
# ║  Run this each day to enable LinkedIn sending from your      ║
# ║  machine. It starts the LinkedIn MCP server (headless        ║
# ║  browser) and a Cloudflare tunnel so the atomic*HR server    ║
# ║  can reach it.                                               ║
# ║                                                              ║
# ║  First time? Run: ./start-linkedin.sh setup                 ║
# ╚══════════════════════════════════════════════════════════════╝

set -euo pipefail

MCP_PORT="${MCP_PORT:-8377}"
MCP_DIR="$HOME/.linkedin-mcp"
PID_FILE="$MCP_DIR/server.pid"
TUNNEL_PID_FILE="$MCP_DIR/tunnel.pid"
LOG_FILE="$MCP_DIR/server.log"
TUNNEL_LOG="$MCP_DIR/tunnel.log"
CONFIG_FILE="$MCP_DIR/config.json"
UVX="${HOME}/.local/bin/uvx"

# ── Helpers ──────────────────────────────────────────────────────

log() { echo "  $(date '+%H:%M:%S') $1"; }

check_uv() {
  if [ ! -f "$UVX" ] && ! command -v uvx &>/dev/null; then
    echo ""
    echo "  uvx not found. Installing uv..."
    curl -LsSf https://astral.sh/uv/install.sh | sh
    echo ""
  fi
  [ -f "$UVX" ] && return
  UVX="$(command -v uvx)"
}

check_cloudflared() {
  if ! command -v cloudflared &>/dev/null; then
    echo ""
    echo "  cloudflared not found. Installing..."
    if command -v brew &>/dev/null; then
      brew install cloudflared
    else
      echo "  ❌ Please install cloudflared:"
      echo "     brew install cloudflared"
      echo "     or: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"
      exit 1
    fi
  fi
}

load_config() {
  if [ -f "$CONFIG_FILE" ]; then
    SERVER_URL=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('server_url',''))" 2>/dev/null || echo "")
    APP_TOKEN=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('app_token',''))" 2>/dev/null || echo "")
    MAILBOX_ID=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('mailbox_id',''))" 2>/dev/null || echo "")
  fi
}

save_config() {
  mkdir -p "$MCP_DIR"
  python3 -c "
import json, os
cfg = {}
if os.path.exists('$CONFIG_FILE'):
    cfg = json.load(open('$CONFIG_FILE'))
cfg['server_url'] = '$SERVER_URL'
cfg['app_token'] = '$APP_TOKEN'
cfg['mailbox_id'] = '$MAILBOX_ID'
json.dump(cfg, open('$CONFIG_FILE', 'w'), indent=2)
os.chmod('$CONFIG_FILE', 0o600)
"
}

cleanup() {
  echo ""
  log "Shutting down..."
  [ -f "$PID_FILE" ] && kill "$(cat "$PID_FILE")" 2>/dev/null && rm "$PID_FILE"
  [ -f "$TUNNEL_PID_FILE" ] && kill "$(cat "$TUNNEL_PID_FILE")" 2>/dev/null && rm "$TUNNEL_PID_FILE"
  log "Done."
  exit 0
}

# ── Commands ─────────────────────────────────────────────────────

do_setup() {
  echo ""
  echo "╔══════════════════════════════════════════════════════╗"
  echo "║   atomic*HR LinkedIn — First-Time Setup              ║"
  echo "╚══════════════════════════════════════════════════════╝"
  echo ""

  # Step 1: Install uv
  echo "  Step 1/4: Checking uv..."
  check_uv
  log "✅ uv installed"

  # Step 2: Install cloudflared
  echo ""
  echo "  Step 2/4: Checking cloudflared..."
  check_cloudflared
  log "✅ cloudflared installed"

  # Step 3: LinkedIn login
  echo ""
  echo "  Step 3/4: LinkedIn login"
  echo "  A browser will open — log in to LinkedIn normally."
  echo "  (Supports Google SSO, 2FA, etc.)"
  echo ""
  read -p "  Press Enter to open the browser..."
  "$UVX" mcp-server-linkedin@latest --login
  echo ""
  log "✅ LinkedIn session saved"

  # Step 4: Server connection
  echo ""
  echo "  Step 4/4: Connect to atomic*HR"
  load_config
  if [ -z "${SERVER_URL:-}" ]; then
    read -p "  Server URL [https://atomic-hr-candidate-search.onrender.com]: " SERVER_URL
    SERVER_URL="${SERVER_URL:-https://atomic-hr-candidate-search.onrender.com}"
  fi

  read -p "  Your email: " EMAIL
  read -s -p "  Your password: " PASSWORD
  echo ""

  # Login to get token
  RESPONSE=$(curl -s -X POST "$SERVER_URL/login" \
    -H "Content-Type: application/json" \
    -d "{\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\"}")

  TOKEN=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null || echo "")
  if [ -z "$TOKEN" ]; then
    echo "  ❌ Login failed. Check your email and password."
    exit 1
  fi
  APP_TOKEN="$TOKEN"
  log "✅ Logged in"

  MAILBOX_ID="auto"
  save_config
  echo ""
  log "✅ Setup complete! Run ./start-linkedin.sh to start."
  echo "  (Your LinkedIn mailbox will be auto-created on first run.)"
  echo ""
}

do_start() {
  load_config
  if [ -z "${APP_TOKEN:-}" ] || [ -z "${MAILBOX_ID:-}" ]; then
    echo "  Not configured yet. Running setup..."
    do_setup
    load_config
  fi

  echo ""
  echo "╔══════════════════════════════════════════════════════╗"
  echo "║   atomic*HR LinkedIn — Starting...                   ║"
  echo "╚══════════════════════════════════════════════════════╝"
  echo ""

  check_uv
  check_cloudflared
  mkdir -p "$MCP_DIR"
  trap cleanup INT TERM

  # Kill any existing processes
  [ -f "$PID_FILE" ] && kill "$(cat "$PID_FILE")" 2>/dev/null || true
  [ -f "$TUNNEL_PID_FILE" ] && kill "$(cat "$TUNNEL_PID_FILE")" 2>/dev/null || true

  # Start MCP server
  log "Starting LinkedIn MCP server on port $MCP_PORT..."
  "$UVX" mcp-server-linkedin@latest \
    --transport streamable-http \
    --host 127.0.0.1 \
    --port "$MCP_PORT" \
    --path /mcp \
    --log-level INFO \
    > "$LOG_FILE" 2>&1 &
  echo $! > "$PID_FILE"

  # Wait for server to be ready
  for i in $(seq 1 30); do
    if curl -sf "http://127.0.0.1:$MCP_PORT/mcp" > /dev/null 2>&1; then
      break
    fi
    sleep 1
  done

  if ! curl -sf "http://127.0.0.1:$MCP_PORT/mcp" > /dev/null 2>&1; then
    log "❌ MCP server didn't start. Check $LOG_FILE"
    cat "$LOG_FILE" | tail -5
    exit 1
  fi
  log "✅ MCP server running"

  # Start Cloudflare tunnel
  log "Starting tunnel..."
  cloudflared tunnel --url "http://127.0.0.1:$MCP_PORT" \
    > "$TUNNEL_LOG" 2>&1 &
  echo $! > "$TUNNEL_PID_FILE"

  # Wait for tunnel URL
  TUNNEL_URL=""
  for i in $(seq 1 20); do
    TUNNEL_URL=$(grep -o 'https://[a-z0-9-]*\.trycloudflare\.com' "$TUNNEL_LOG" 2>/dev/null | head -1 || echo "")
    if [ -n "$TUNNEL_URL" ]; then
      break
    fi
    sleep 1
  done

  if [ -z "$TUNNEL_URL" ]; then
    log "❌ Tunnel didn't start. Check $TUNNEL_LOG"
    cat "$TUNNEL_LOG" | tail -5
    exit 1
  fi
  log "✅ Tunnel: $TUNNEL_URL"

  # Register with the server — auto-creates/updates the LinkedIn mailbox
  MCP_URL="${TUNNEL_URL}/mcp"
  log "Registering with server..."
  REG_RESULT=$(curl -s -X POST "$SERVER_URL/linkedin/connect-mcp" \
    -H "x-app-token: $APP_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"mcp_url\":\"$MCP_URL\"}")

  REG_NAME=$(echo "$REG_RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('name',''))" 2>/dev/null || echo "")
  REG_OK=$(echo "$REG_RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); print('yes' if d.get('ok') else 'no')" 2>/dev/null || echo "no")

  if [ "$REG_OK" = "yes" ]; then
    log "✅ Connected as: $REG_NAME"
    # Save mailbox ID for future reference
    REG_MB=$(echo "$REG_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('mailbox_id',''))" 2>/dev/null || echo "")
    if [ -n "$REG_MB" ]; then
      MAILBOX_ID="$REG_MB"
      save_config
    fi
  else
    REG_ERR=$(echo "$REG_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','unknown'))" 2>/dev/null || echo "unknown")
    log "⚠️  Registration issue: $REG_ERR"
    log "   The tunnel is running at: $MCP_URL"
  fi

  echo ""
  echo "  ┌─────────────────────────────────────────────────┐"
  echo "  │  🟢 LinkedIn sending is active                   │"
  echo "  │                                                   │"
  echo "  │  Your campaigns will send through this machine.   │"
  echo "  │  Keep this terminal open while working.           │"
  echo "  │  Press Ctrl+C to stop.                            │"
  echo "  └─────────────────────────────────────────────────┘"
  echo ""

  # Keep running, show periodic status
  while true; do
    sleep 300
    if ! kill -0 "$(cat "$PID_FILE" 2>/dev/null)" 2>/dev/null; then
      log "⚠️  MCP server died. Restarting..."
      "$UVX" mcp-server-linkedin@latest \
        --transport streamable-http --host 127.0.0.1 --port "$MCP_PORT" --path /mcp --log-level INFO \
        > "$LOG_FILE" 2>&1 &
      echo $! > "$PID_FILE"
    fi
    if ! kill -0 "$(cat "$TUNNEL_PID_FILE" 2>/dev/null)" 2>/dev/null; then
      log "⚠️  Tunnel died. Restarting..."
      cloudflared tunnel --url "http://127.0.0.1:$MCP_PORT" > "$TUNNEL_LOG" 2>&1 &
      echo $! > "$TUNNEL_PID_FILE"
      sleep 5
      NEW_URL=$(grep -o 'https://[a-z0-9-]*\.trycloudflare\.com' "$TUNNEL_LOG" 2>/dev/null | tail -1 || echo "")
      if [ -n "$NEW_URL" ]; then
        curl -s -X POST "$SERVER_URL/linkedin/connect-mcp" \
          -H "x-app-token: $APP_TOKEN" -H "Content-Type: application/json" \
          -d "{\"mcp_url\":\"${NEW_URL}/mcp\"}" > /dev/null 2>&1
        log "✅ New tunnel: $NEW_URL"
      fi
    fi
  done
}

do_stop() {
  [ -f "$PID_FILE" ] && kill "$(cat "$PID_FILE")" 2>/dev/null && rm "$PID_FILE" && echo "  MCP server stopped"
  [ -f "$TUNNEL_PID_FILE" ] && kill "$(cat "$TUNNEL_PID_FILE")" 2>/dev/null && rm "$TUNNEL_PID_FILE" && echo "  Tunnel stopped"
  echo "  Done."
}

do_status() {
  echo ""
  if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
    echo "  MCP server: 🟢 running (PID $(cat "$PID_FILE"))"
  else
    echo "  MCP server: 🔴 stopped"
  fi
  if [ -f "$TUNNEL_PID_FILE" ] && kill -0 "$(cat "$TUNNEL_PID_FILE")" 2>/dev/null; then
    TURL=$(grep -o 'https://[a-z0-9-]*\.trycloudflare\.com' "$TUNNEL_LOG" 2>/dev/null | tail -1 || echo "unknown")
    echo "  Tunnel:     🟢 running ($TURL)"
  else
    echo "  Tunnel:     🔴 stopped"
  fi
  echo ""
  "$UVX" mcp-server-linkedin@latest --status 2>/dev/null || echo "  LinkedIn session: unknown"
  echo ""
}

do_relogin() {
  echo "  Opening browser to re-login to LinkedIn..."
  "$UVX" mcp-server-linkedin@latest --login
  echo ""
  log "✅ Session refreshed. Restart with: ./start-linkedin.sh"
}

# ── Main ─────────────────────────────────────────────────────────

case "${1:-start}" in
  setup)    do_setup ;;
  start)    do_start ;;
  stop)     do_stop ;;
  status)   do_status ;;
  relogin)  do_relogin ;;
  *)
    echo ""
    echo "  Usage: ./start-linkedin.sh [command]"
    echo ""
    echo "  Commands:"
    echo "    setup     First-time setup (install tools, login, connect)"
    echo "    start     Start LinkedIn sending (default)"
    echo "    stop      Stop LinkedIn sending"
    echo "    status    Check if everything is running"
    echo "    relogin   Re-login to LinkedIn (if session expired)"
    echo ""
    ;;
esac
