#!/usr/bin/env bash
# claude-iris cli — start/stop the local mirror server.
set -euo pipefail

case "$(uname -s)" in
  MINGW*|MSYS*|CYGWIN*)
    echo "✗ claude-iris doesn't run natively on Windows — use WSL2." >&2
    echo "  Quick start:" >&2
    echo "    PowerShell (admin):  wsl --install -d Ubuntu" >&2
    echo "    Ubuntu shell:        npm i -g claude-iris && claude-iris setup" >&2
    echo "  Docs: https://github.com/ViveSieg/claude-iris#windows-via-wsl2" >&2
    exit 1
    ;;
esac

REPO="$(cd "$(dirname "$0")/.." && pwd)"
VENV="${REPO}/server/.venv"
PY="${VENV}/bin/python"
DATA_DIR="${CLAUDE_IRIS_DATA:-${HOME}/.claude-iris}"
PID_FILE="${DATA_DIR}/server.pid"
LOG_FILE="${DATA_DIR}/server.log"
PORT="${CLAUDE_IRIS_PORT:-7456}"
HOST="${CLAUDE_IRIS_HOST:-127.0.0.1}"

mkdir -p "${DATA_DIR}"

cmd_start() {
  if cmd_status_quiet; then
    echo "claude-iris already running (pid $(cat "${PID_FILE}")) on http://${HOST}:${PORT}"
    return 0
  fi
  if [ ! -x "${PY}" ]; then
    echo "venv missing — run ${REPO}/install.sh first" >&2
    exit 1
  fi
  echo "starting claude-iris on http://${HOST}:${PORT} ..."
  CLAUDE_IRIS_HOST="${HOST}" \
  CLAUDE_IRIS_PORT="${PORT}" \
  CLAUDE_IRIS_DATA="${DATA_DIR}" \
    nohup "${PY}" "${REPO}/server/main.py" >>"${LOG_FILE}" 2>&1 &
  echo $! > "${PID_FILE}"
  sleep 0.6
  if cmd_status_quiet; then
    echo "ok — http://${HOST}:${PORT}"
  else
    echo "failed to start — see ${LOG_FILE}" >&2
    exit 1
  fi
}

cmd_stop() {
  if [ -f "${PID_FILE}" ]; then
    local pid
    pid="$(cat "${PID_FILE}")"
    if kill -0 "${pid}" 2>/dev/null; then
      kill "${pid}" 2>/dev/null || true
      sleep 0.2
      kill -9 "${pid}" 2>/dev/null || true
      echo "stopped (pid ${pid})"
    else
      echo "no live process for pid ${pid}"
    fi
    rm -f "${PID_FILE}"
  else
    echo "not running"
  fi
}

cmd_status_quiet() {
  [ -f "${PID_FILE}" ] || return 1
  local pid
  pid="$(cat "${PID_FILE}")"
  kill -0 "${pid}" 2>/dev/null
}

cmd_status() {
  if cmd_status_quiet; then
    echo "running (pid $(cat "${PID_FILE}")) — http://${HOST}:${PORT}"
  else
    echo "not running"
    return 1
  fi
}

cmd_open() {
  if ! cmd_status_quiet; then
    cmd_start
  fi
  local url="http://${HOST}:${PORT}"
  local opened=0
  case "$(uname -s)" in
    Darwin)
      # If Chrome already has an iris tab open, jump to it instead of
      # spawning a new one — `open -a "Google Chrome"` would otherwise
      # add a duplicate every time the user runs /iris open.
      if [ -d "/Applications/Google Chrome.app" ] || [ -d "${HOME}/Applications/Google Chrome.app" ]; then
        if osascript <<APPLESCRIPT >/dev/null 2>&1
on run argv
  set theURL to "${url}"
  tell application "Google Chrome"
    set foundWindow to missing value
    set foundIndex to 0
    repeat with w in windows
      set i to 0
      repeat with t in tabs of w
        set i to i + 1
        if URL of t starts with theURL then
          set foundWindow to w
          set foundIndex to i
          exit repeat
        end if
      end repeat
      if foundWindow is not missing value then exit repeat
    end repeat
    if foundWindow is not missing value then
      set active tab index of foundWindow to foundIndex
      set index of foundWindow to 1
      activate
      return "reused"
    else
      open location theURL
      activate
      return "opened"
    end if
  end tell
end run
APPLESCRIPT
        then
          opened=1
        else
          # AppleScript path failed (Chrome not running, automation
          # permission missing, etc) — fall back to plain open -a.
          open -a "Google Chrome" "${url}" && opened=1
        fi
      fi
      # Other Chromium-family fallbacks if Chrome isn't installed.
      if [ "${opened}" -eq 0 ]; then
        for app in "Chromium" "Brave Browser" "Microsoft Edge"; do
          if [ -d "/Applications/${app}.app" ] || [ -d "${HOME}/Applications/${app}.app" ]; then
            open -a "${app}" "${url}" && opened=1 && break
          fi
        done
      fi
      [ "${opened}" -eq 0 ] && open "${url}" && opened=1
      ;;
    Linux)
      # WSL: vanilla Ubuntu has no Linux-side GUI browser. Hand the URL
      # to the Windows host so it opens in the user's default Windows
      # browser (typically Edge or Chrome) — without this, `claude-iris
      # open` from inside WSL prints the URL and hopes the user clicks.
      if [ -f /proc/version ] && grep -qi microsoft /proc/version 2>/dev/null; then
        if command -v wslview >/dev/null 2>&1; then
          wslview "${url}" >/dev/null 2>&1 && opened=1
        elif command -v explorer.exe >/dev/null 2>&1; then
          # explorer.exe with a URL hands off to the default Windows browser.
          explorer.exe "${url}" >/dev/null 2>&1
          # explorer.exe always exits 1 on URLs even when it succeeds; we
          # can't rely on $? — assume it worked if the binary exists.
          opened=1
        elif command -v cmd.exe >/dev/null 2>&1; then
          cmd.exe /c start "" "${url}" >/dev/null 2>&1 && opened=1
        fi
      fi
      if [ "${opened}" -eq 0 ]; then
        for bin in google-chrome google-chrome-stable chromium chromium-browser brave-browser microsoft-edge; do
          if command -v "${bin}" >/dev/null 2>&1; then
            "${bin}" "${url}" >/dev/null 2>&1 &
            opened=1
            break
          fi
        done
      fi
      [ "${opened}" -eq 0 ] && command -v xdg-open >/dev/null 2>&1 && xdg-open "${url}" && opened=1
      ;;
    *)
      command -v xdg-open >/dev/null 2>&1 && xdg-open "${url}" && opened=1
      ;;
  esac
  if [ "${opened}" -eq 0 ]; then
    echo "open ${url} in your browser"
  fi
}

cmd_listen() {
  if [ ! -x "${PY}" ]; then
    echo "venv missing — run ${REPO}/install.sh first" >&2
    exit 1
  fi
  shift  # drop the "listen" arg, pass the rest to listen.py
  exec "${PY}" "${REPO}/bin/listen.py" "$@"
}

case "${1:-}" in
  start)   cmd_start ;;
  stop)    cmd_stop ;;
  restart) cmd_stop; cmd_start ;;
  status)  cmd_status ;;
  open)    cmd_open ;;
  listen)  cmd_listen "$@" ;;
  *)
    echo "usage: claude-iris {start|stop|restart|status|open|listen [--dry-run] [--focus APP]}"
    exit 2
    ;;
esac
