#!/bin/bash
# ╔══════════════════════════════════════════════════════════════╗
# ║  atomic*HR LinkedIn — Start MCP + Tunnel                    ║
# ║                                                              ║
# ║  Run this once 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, then installs launchd auto-start agents so    ║
# ║  both keep running after reboot/quit (no daily re-run).      ║
# ║                                                              ║
# ║  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
}

# ── Auto-start (launchd) ─────────────────────────────────────────
# Installs two LaunchAgents so the MCP server + tunnel run whenever this
# Mac is on (RunAtLoad + KeepAlive) — no more "tunnel offline" after a
# reboot or a closed terminal. Idempotent: safe to re-run any time
# (plists are overwritten, agents reloaded).

AGENTS_DIR="$HOME/Library/LaunchAgents"
MCP_PLIST="$AGENTS_DIR/com.atomichr.limcp.plist"
TUNNEL_PLIST="$AGENTS_DIR/com.atomichr.litunnel.plist"
TUNNEL_AGENT_SH="$MCP_DIR/tunnel-agent.sh"

install_autostart() {
  if ! command -v launchctl >/dev/null 2>&1; then
    log "⚠️  launchctl not available — skipping auto-start install"
    return 1
  fi

  # Absolute paths (launchd has no shell PATH magic).
  local cloudflared_bin
  cloudflared_bin="$(command -v cloudflared 2>/dev/null || true)"
  if [ -z "$cloudflared_bin" ] || [ ! -x "$UVX" ]; then
    log "⚠️  cloudflared/uvx path not resolved — skipping auto-start install"
    return 1
  fi

  mkdir -p "$AGENTS_DIR" "$MCP_DIR"

  # Named tunnel (permanent URL) if this Mac was provisioned with one
  # (~/.cloudflared/config.yml from the onboarding bundle); otherwise a
  # quick-tunnel wrapper that re-registers the fresh trycloudflare URL
  # with the app on every (re)start.
  local tunnel_name=""
  if [ -f "$HOME/.cloudflared/config.yml" ]; then
    tunnel_name="$(sed -n 's/^tunnel:[[:space:]]*//p' "$HOME/.cloudflared/config.yml" | head -1 | tr -d '"' | tr -d "'" || true)"
  fi

  local cert_line=""
  [ -f "$HOME/.cloudflared/cert.pem" ] && cert_line="<key>TUNNEL_ORIGIN_CERT</key><string>$HOME/.cloudflared/cert.pem</string>"

  # 1) MCP server agent
  cat > "$MCP_PLIST" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>com.atomichr.limcp</string>
  <key>ProgramArguments</key>
  <array><string>$UVX</string><string>mcp-server-linkedin@latest</string><string>--transport</string><string>streamable-http</string><string>--host</string><string>127.0.0.1</string><string>--port</string><string>$MCP_PORT</string><string>--path</string><string>/mcp</string><string>--log-level</string><string>INFO</string></array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>$LOG_FILE</string>
  <key>StandardErrorPath</key><string>$LOG_FILE</string>
  <key>EnvironmentVariables</key><dict><key>HOME</key><string>$HOME</string><key>PATH</key><string>/opt/homebrew/bin:$HOME/.local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string></dict>
</dict></plist>
PLIST

  # 2) Tunnel agent
  if [ -n "$tunnel_name" ]; then
    log "Named tunnel detected ($tunnel_name) — auto-start will run it directly."
    cat > "$TUNNEL_PLIST" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>com.atomichr.litunnel</string>
  <key>ProgramArguments</key>
  <array><string>$cloudflared_bin</string><string>tunnel</string><string>run</string><string>$tunnel_name</string></array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>$HOME/.cloudflared/run.log</string>
  <key>StandardErrorPath</key><string>$HOME/.cloudflared/run.log</string>
  <key>EnvironmentVariables</key><dict><key>HOME</key><string>$HOME</string>$cert_line</dict>
</dict></plist>
PLIST
  else
    # Quick-tunnel mode: the URL changes on every restart, so the agent runs a
    # wrapper that starts the tunnel AND re-registers the new URL with the app
    # (reads server_url/app_token from config.json at runtime).
    cat > "$TUNNEL_AGENT_SH" <<WRAP
#!/bin/bash
# Auto-generated by start-linkedin.sh — launchd quick-tunnel agent.
# Starts a Cloudflare quick tunnel and registers its fresh URL with atomic*HR.
set -u
MCP_DIR="$MCP_DIR"
MCP_PORT="$MCP_PORT"
TUNNEL_LOG="$TUNNEL_LOG"
CONFIG_FILE="$CONFIG_FILE"
CLOUDFLARED="$cloudflared_bin"
WRAP
    cat >> "$TUNNEL_AGENT_SH" <<'WRAP'
: > "$TUNNEL_LOG"
"$CLOUDFLARED" tunnel --url "http://127.0.0.1:$MCP_PORT" >> "$TUNNEL_LOG" 2>&1 &
CF_PID=$!
TUNNEL_URL=""
for i in $(seq 1 30); do
  TUNNEL_URL=$(grep -o 'https://[a-z0-9-]*\.trycloudflare\.com' "$TUNNEL_LOG" 2>/dev/null | tail -1 || echo "")
  [ -n "$TUNNEL_URL" ] && break
  sleep 1
done
if [ -n "$TUNNEL_URL" ] && [ -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 "")
  if [ -n "$SERVER_URL" ] && [ -n "$APP_TOKEN" ]; then
    curl -s -X POST "$SERVER_URL/linkedin/connect-mcp" \
      -H "x-app-token: $APP_TOKEN" -H "Content-Type: application/json" \
      -d "{\"mcp_url\":\"${TUNNEL_URL}/mcp\"}" >> "$TUNNEL_LOG" 2>&1 || true
    echo "registered ${TUNNEL_URL}/mcp" >> "$TUNNEL_LOG"
  fi
fi
# Stay attached to cloudflared so launchd's KeepAlive restarts (and
# re-registers) the tunnel if it ever dies.
wait "$CF_PID"
WRAP
    chmod +x "$TUNNEL_AGENT_SH"
    cat > "$TUNNEL_PLIST" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>com.atomichr.litunnel</string>
  <key>ProgramArguments</key>
  <array><string>/bin/bash</string><string>$TUNNEL_AGENT_SH</string></array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>$HOME/.cloudflared/run.log</string>
  <key>StandardErrorPath</key><string>$HOME/.cloudflared/run.log</string>
  <key>EnvironmentVariables</key><dict><key>HOME</key><string>$HOME</string><key>PATH</key><string>/opt/homebrew/bin:$HOME/.local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string></dict>
</dict></plist>
PLIST
  fi

  mkdir -p "$HOME/.cloudflared"

  # Hand ownership to launchd: stop the foreground copies first so the
  # agents don't fight over port $MCP_PORT.
  [ -f "$PID_FILE" ] && kill "$(cat "$PID_FILE")" 2>/dev/null || true
  [ -f "$TUNNEL_PID_FILE" ] && kill "$(cat "$TUNNEL_PID_FILE")" 2>/dev/null || true
  rm -f "$PID_FILE" "$TUNNEL_PID_FILE"

  launchctl unload "$MCP_PLIST" 2>/dev/null || true
  launchctl unload "$TUNNEL_PLIST" 2>/dev/null || true
  if ! launchctl load -w "$MCP_PLIST" || ! launchctl load -w "$TUNNEL_PLIST"; then
    log "⚠️  launchctl load failed — auto-start not active"
    return 1
  fi

  # Wait for the launchd-owned MCP server to come up.
  local up=""
  for i in $(seq 1 30); do
    if curl -sf "http://127.0.0.1:$MCP_PORT/mcp" > /dev/null 2>&1; then up=1; break; fi
    sleep 1
  done
  if [ -z "$up" ]; then
    log "⚠️  Agents loaded but MCP server not responding yet — check $LOG_FILE"
  fi

  echo ""
  echo "  ✓ auto-start installed — the tunnel now runs whenever this Mac is on"
  return 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

  # Install launchd auto-start and hand the processes over to it, so the
  # MCP server + tunnel keep running after reboot / closed terminal.
  if install_autostart; then
    echo ""
    echo "  ┌─────────────────────────────────────────────────┐"
    echo "  │  🟢 LinkedIn sending is active (background)      │"
    echo "  │                                                   │"
    echo "  │  Your campaigns will send through this machine.   │"
    echo "  │  It auto-starts on reboot — you can close this    │"
    echo "  │  terminal. To stop: ./start-linkedin.sh stop      │"
    echo "  └─────────────────────────────────────────────────┘"
    echo ""
    exit 0
  fi

  log "⚠️  Auto-start unavailable — running in foreground instead."
  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() {
  # Unload the auto-start agents first (otherwise KeepAlive restarts everything).
  if command -v launchctl >/dev/null 2>&1; then
    [ -f "$MCP_PLIST" ] && launchctl unload -w "$MCP_PLIST" 2>/dev/null && echo "  Auto-start (MCP) disabled" || true
    [ -f "$TUNNEL_PLIST" ] && launchctl unload -w "$TUNNEL_PLIST" 2>/dev/null && echo "  Auto-start (tunnel) disabled" || true
  fi
  [ -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. (Run ./start-linkedin.sh to start again — auto-start re-enables itself.)"
}

do_status() {
  echo ""
  if command -v launchctl >/dev/null 2>&1 && launchctl list 2>/dev/null | grep -q "com.atomichr.limcp"; then
    echo "  Auto-start: 🟢 installed (launchd — survives reboot)"
  elif [ -f "$MCP_PLIST" ]; then
    echo "  Auto-start: 🟡 installed but not loaded (run ./start-linkedin.sh)"
  else
    echo "  Auto-start: 🔴 not installed (run ./start-linkedin.sh)"
  fi
  if curl -sf "http://127.0.0.1:$MCP_PORT/mcp" > /dev/null 2>&1; then
    echo "  MCP server: 🟢 responding on port $MCP_PORT"
  elif [ -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 command -v launchctl >/dev/null 2>&1 && launchctl list 2>/dev/null | grep -q "com.atomichr.litunnel"; then
    TURL=$(grep -o 'https://[a-z0-9-]*\.trycloudflare\.com' "$TUNNEL_LOG" 2>/dev/null | tail -1 || echo "")
    echo "  Tunnel:     🟢 running via launchd${TURL:+ ($TURL)}"
  elif [ -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 ""
  # If the launchd agent owns the server, bounce it so it picks up the new session.
  if command -v launchctl >/dev/null 2>&1 && launchctl list 2>/dev/null | grep -q "com.atomichr.limcp"; then
    launchctl kickstart -k "gui/$(id -u)/com.atomichr.limcp" 2>/dev/null || true
    log "✅ Session refreshed. Background server restarted."
  else
    log "✅ Session refreshed. Restart with: ./start-linkedin.sh"
  fi
}

# ── 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
