#!/usr/bin/env bash
# FlexUI CDP Inspector — fetch DOM tree and CSS styles via Chrome DevTools Protocol.
# Requires a running debug server and an app with a connected debug target.
#
# Usage:
#   ./scripts/get-inspector.sh                  # first page target, depth=3
#   ./scripts/get-inspector.sh --depth 5        # deeper tree
#   ./scripts/get-inspector.sh --output dom.json # save to file
#   ./scripts/get-inspector.sh --port 38990     # custom port
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$SCRIPT_DIR/_config.sh"

DEBUG_PORT="${DEBUG_PORT:-38989}"
DEPTH=50  # deep enough to capture full FlexUI component tree
OUTPUT=""

usage() {
  echo "Usage: $0 [options]"
  echo ""
  echo "Fetch DOM + CSS from a connected FlexUI debug target via CDP."
  echo "Requires debug server running (./build.sh debug-server start)."
  echo ""
  echo "Options:"
  echo "  --port <port>     Debug server port (default: 38989)"
  echo "  --depth <n>       DOM tree depth (default: 3)"
  echo "  --output <file>   Save JSON output to file"
  echo "  --client-id <id>  Target specific client ID"
  echo "  -h, --help        Show this help"
  exit "${1:-0}"
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --port)       DEBUG_PORT="$2"; shift 2 ;;
    --depth)      DEPTH="$2"; shift 2 ;;
    --output)     OUTPUT="$2"; shift 2 ;;
    --client-id)  CDP_CLIENT_ID="$2"; shift 2 ;;
    -h|--help)    usage ;;
    *)            err "Unknown option: $1"; usage 1 ;;
  esac
done

# Check server is running
if ! curl -s -o /dev/null "http://localhost:${DEBUG_PORT}/json/version" 2>/dev/null; then
  err "Debug server not running on port ${DEBUG_PORT}."
  err "Start it with: ./build.sh debug-server start"
  exit 1
fi

log "Fetching DOM+CSS via CDP (port=${DEBUG_PORT}, depth=${DEPTH})..."

# Run the CDP inspector helper
export CDP_PORT="$DEBUG_PORT"
export CDP_DEPTH="$DEPTH"
export CDP_CLIENT_ID="${CDP_CLIENT_ID:-}"
export CDP_TIMEOUT="${CDP_TIMEOUT:-15000}"

NODE_PATH="$REPO_ROOT/toolkit/flexui-devtools/packages/flexui-devserver/node_modules"
export NODE_PATH

if [ -n "$OUTPUT" ]; then
  node "$SCRIPT_DIR/_cdp-inspector.js" 2>&1 > "$OUTPUT"
  log "Result saved to: $OUTPUT"
else
  node "$SCRIPT_DIR/_cdp-inspector.js"
fi