#!/usr/bin/env bash
# Devcontainer: launch dashboard (API backend + Vite frontend).
# Usage: ui          # global mode → http://localhost:45173
#        ui -p       # project mode (~/demo-project) → http://localhost:45173
#        ui stop     # stop API + Vite
set -euo pipefail

# Uncommon ports so the devcontainer does not fight other projects for 5173/19420.
PORT=49420
VITE_PORT=45173
PIDDIR=/tmp/dev-servers
LOGDIR=/tmp
mkdir -p "$PIDDIR"

# virtiofs doesn't reliably deliver inotify events, so Vite silently misses file
# saves and HMR stops firing. Force polling-based watching (vite.config reads this).
export CHOKIDAR_USEPOLLING="${CHOKIDAR_USEPOLLING:-true}"

# Resolve pnpm
PNPM_BIN=""
if command -v pnpm >/dev/null 2>&1; then
  PNPM_BIN="$(command -v pnpm)"
elif [ -x /usr/local/share/pnpm/pnpm ]; then
  PNPM_BIN="/usr/local/share/pnpm/pnpm"
elif [ -x /usr/local/bin/pnpm ]; then
  PNPM_BIN="/usr/local/bin/pnpm"
elif [ -x /usr/local/share/nvm/current/bin/pnpm ]; then
  PNPM_BIN="/usr/local/share/nvm/current/bin/pnpm"
fi

is_port_open() {
  timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$1" 2>/dev/null
}

# Find PIDs listening on a given port via /proc/net/tcp6.
# Works without fuser/lsof/ss (often missing in containers).
pids_on_port() {
  local port="$1"
  local hex_port
  hex_port=$(printf '%04X' "$port")
  local inodes=""
  # Collect socket inodes for LISTEN (0A) entries on this port
  while read -r _ local_addr _ state _ _ _ _ _ inode _; do
    if [ "$state" = "0A" ] && [[ "$local_addr" == *":$hex_port" ]]; then
      inodes="$inodes $inode"
    fi
  done < /proc/net/tcp6 2>/dev/null
  [ -z "$inodes" ] && return
  # Map inodes to PIDs
  for pid_dir in /proc/[0-9]*/fd; do
    local pid="${pid_dir#/proc/}"
    pid="${pid%/fd}"
    for fd in "$pid_dir"/*; do
      local target
      target=$(readlink "$fd" 2>/dev/null) || continue
      for ino in $inodes; do
        if [[ "$target" == *"socket:[$ino]"* ]]; then
          echo "$pid"
        fi
      done
    done
  done 2>/dev/null | sort -u
}

# Kill all processes listening on a port (fuser replacement).
kill_port() {
  local port="$1"
  if command -v fuser &>/dev/null; then
    fuser -k "$port/tcp" 2>/dev/null || true
    return
  fi
  local pids
  pids=$(pids_on_port "$port")
  [ -z "$pids" ] && return
  for pid in $pids; do
    kill "$pid" 2>/dev/null || true
  done
  sleep 0.3
  for pid in $pids; do
    kill -9 "$pid" 2>/dev/null || true
  done
}

kill_pid_file() {
  local pf="$1"
  [ -f "$pf" ] || return 0
  local pid; pid=$(cat "$pf")
  pkill -P "$pid" 2>/dev/null || true
  kill "$pid" 2>/dev/null || true
  sleep 0.3
  kill -9 "$pid" 2>/dev/null || true
  rm -f "$pf"
}

# Parse args
MODE="global"
ACTION="start"
for arg in "$@"; do
  case "$arg" in
    -p|--project) MODE="project" ;;
    -g|--global)  MODE="global" ;;
    stop)         ACTION="stop" ;;
  esac
done

# ── stop ──
if [ "$ACTION" = "stop" ]; then
  kill_pid_file "$PIDDIR/api.pid"
  pkill -f 'skillshare.* ui' 2>/dev/null || true
  kill_port $PORT
  kill_pid_file "$PIDDIR/vite.pid"
  kill_port $VITE_PORT
  echo "  api + vite stopped"
  exit 0
fi

# ── start ──

# Stop old API: PID file → pkill pattern → port-level kill.
kill_pid_file "$PIDDIR/api.pid"
pkill -f 'skillshare.* ui' 2>/dev/null || true
kill_port $PORT
for _ in 1 2 3 4 5 6; do
  is_port_open $PORT || break
  sleep 0.5
done
if is_port_open $PORT; then
  echo "  api          FAILED: port $PORT still in use after cleanup" >&2
  pids=$(pids_on_port $PORT)
  if [ -n "$pids" ]; then
    echo "               Processes holding port: $pids" >&2
    echo "               Fix: kill -9 $pids" >&2
  fi
  exit 1
fi

# Start API via air (hot-reload).
# Air always builds from /workspace. For project mode, a launcher script
# changes the cwd before exec'ing the binary (skillshare ui -p uses os.Getwd()).
# Note: air's full_bin does NOT run through sh -c, so shell operators like
# "cd ... &&" in SKILLSHARE_UI_EXEC_PREFIX don't work. A wrapper script is required.
export SKILLSHARE_UI_HOST=0.0.0.0
MODE_FLAG="-${MODE:0:1}"
export SKILLSHARE_UI_FLAGS="${MODE_FLAG} --port ${PORT}"
if [ "$MODE" = "project" ]; then
  export SKILLSHARE_UI_PROJECT_DIR="$HOME/demo-project"
  cat > /tmp/ui-project-launcher.sh << 'LAUNCHER'
#!/bin/bash
cd "$SKILLSHARE_UI_PROJECT_DIR" || exit 1
exec "$@"
LAUNCHER
  chmod +x /tmp/ui-project-launcher.sh
  export SKILLSHARE_UI_EXEC_PREFIX="/tmp/ui-project-launcher.sh /workspace/"
fi
# Resolve air binary (go install puts it in GOPATH/bin, not GOROOT/bin).
AIR_BIN=""
for p in "$(go env GOPATH)/bin/air" /go/bin/air /usr/local/go/bin/air; do
  [ -x "$p" ] && AIR_BIN="$p" && break
done
if [ -z "$AIR_BIN" ]; then
  echo "  air          not found — installing..." >&2
  go install github.com/air-verse/air@v1.67.1  # v1.67.2+ needs go >= 1.26
  AIR_BIN="$(go env GOPATH)/bin/air"
fi

nohup "$AIR_BIN" -c /workspace/.air.toml > "$LOGDIR/api-dev.log" 2>&1 &
echo $! > "$PIDDIR/api.pid"
printf "  %-12s building..." "api"
for _ in $(seq 1 30); do
  is_port_open $PORT && break
  sleep 1
done
if is_port_open $PORT; then
  printf " ready (%s mode, hot-reload)\n" "$MODE"
else
  printf " FAILED\n" >&2
  echo "               Port $PORT not reachable after 30s." >&2
  echo "               Check log: cat $LOGDIR/api-dev.log" >&2
  echo "               Retry:     ui stop && ui ${MODE_FLAG}" >&2
fi

# Ensure Vite is running.
if is_port_open $VITE_PORT; then
  printf "  %-12s already running (port %s)\n" "vite" "$VITE_PORT"
else
  if [ -z "$PNPM_BIN" ]; then
    echo "  vite         skipped: pnpm not found" >&2
  else
    if [ ! -x /workspace/ui/node_modules/.bin/vite ]; then
      (cd /workspace/ui && "$PNPM_BIN" install --frozen-lockfile > "$LOGDIR/vite-deps.log" 2>&1) || true
    fi
    (cd /workspace/ui && nohup "$PNPM_BIN" exec vite --host 0.0.0.0 --port $VITE_PORT --strictPort > "$LOGDIR/vite-dev.log" 2>&1 &
     echo $! > "$PIDDIR/vite.pid")
    for _ in $(seq 1 20); do
      is_port_open $VITE_PORT && break
      sleep 0.5
    done
    if is_port_open $VITE_PORT; then
      printf "  %-12s started (port %s)\n" "vite" "$VITE_PORT"
    else
      printf "  %-12s failed to start (see %s/vite-dev.log)\n" "vite" "$LOGDIR" >&2
    fi
  fi
fi

echo "✓ Dashboard ($MODE): http://localhost:$VITE_PORT"
