#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PACKAGE_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

PROFILE_NAME=""
OPENCLAW_HOME_CLI=""

usage() {
  echo "Usage: ./scripts/install-ui-whatsynaptor.sh [--profile NAME] [--state-dir PATH]"
}

require_value() {
  local flag="$1"
  local value="${2-}"
  if [ -z "$value" ]; then
    echo "Error: missing value for $flag" >&2
    usage >&2
    exit 1
  fi
}

while [ $# -gt 0 ]; do
  case "$1" in
    --profile)
      require_value "$1" "${2-}"
      PROFILE_NAME="$2"
      shift 2
      ;;
    --state-dir)
      require_value "$1" "${2-}"
      OPENCLAW_HOME_CLI="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

resolve_openclaw_home() {
  [ -n "$OPENCLAW_HOME_CLI" ] && { echo "$OPENCLAW_HOME_CLI"; return; }
  [ -n "${OPENCLAW_STATE_DIR:-}" ] && { echo "$OPENCLAW_STATE_DIR"; return; }
  [ -n "${OPENCLAW_HOME:-}" ] && { echo "$OPENCLAW_HOME"; return; }
  [ -n "$PROFILE_NAME" ] && { echo "$HOME/.openclaw-$PROFILE_NAME"; return; }
  [ -d "$HOME/.openclaw" ] && { echo "$HOME/.openclaw"; return; }
  [ -d "/data/.openclaw" ] && { echo "/data/.openclaw"; return; }
  echo "$HOME/.openclaw"
}

need_cmd() {
  command -v "$1" >/dev/null 2>&1
}

run_with_privilege() {
  if [ "$(id -u)" -eq 0 ]; then "$@"
  elif need_cmd sudo; then sudo "$@"
  else
    echo "Error: need root or sudo" >&2
    exit 1
  fi
}

install_jq() {
  need_cmd jq && return 0
  echo "Installing jq..."
  if need_cmd apt-get; then
    run_with_privilege apt-get update
    run_with_privilege apt-get install -y jq
  elif need_cmd dnf; then
    run_with_privilege dnf install -y jq
  elif need_cmd yum; then
    run_with_privilege yum install -y jq
  elif need_cmd apk; then
    run_with_privilege apk add --no-cache jq
  elif need_cmd brew; then
    brew install jq
  else
    echo "Error: install jq manually." >&2
    exit 1
  fi
}

OPENCLAW_HOME="$(resolve_openclaw_home)"
OPENCLAW_CONFIG="${OPENCLAW_CONFIG_PATH:-${OPENCLAW_CONFIG:-$OPENCLAW_HOME/openclaw.json}}"
TARGET_DIR="$OPENCLAW_HOME/extensions/ui-whatsynaptor"
CONTROL_UI_INDEX=""

detect_control_ui_index() {
  local candidates=(
    "/opt/openclaw/app/dist/control-ui/index.html"
    "/usr/lib/node_modules/openclaw/dist/control-ui/index.html"
    "/usr/local/lib/node_modules/openclaw/dist/control-ui/index.html"
  )

  if [ -n "${N_PREFIX:-}" ]; then
    candidates+=("$N_PREFIX/lib/node_modules/openclaw/dist/control-ui/index.html")
  fi

  candidates+=(
    "$HOME/n/lib/node_modules/openclaw/dist/control-ui/index.html"
    "$HOME/.nvm/versions/node/$(node -p 'process.version' 2>/dev/null || true)/lib/node_modules/openclaw/dist/control-ui/index.html"
  )

  local candidate
  for candidate in "${candidates[@]}"; do
    if [ -f "$candidate" ]; then
      echo "$candidate"
      return 0
    fi
  done
}

quote_cmd() {
  printf "%q" "$1"
}

ensure_control_ui_index_writable() {
  [ -n "$CONTROL_UI_INDEX" ] || return 0
  [ -f "$CONTROL_UI_INDEX" ] || return 0
  [ -w "$CONTROL_UI_INDEX" ] && return 0

  local chmod_cmd
  chmod_cmd="sudo chmod a+rw $(quote_cmd "$CONTROL_UI_INDEX")"

  while [ ! -w "$CONTROL_UI_INDEX" ]; do
    cat <<EOF

Control UI index is read-only for the current user:
  $CONTROL_UI_INDEX

ui-whatsynaptor needs write access to inject the branding assets.

Choose one:
  y - run chmod now with sudo
  r - I ran this in another terminal; retry the check
  s - skip Control UI patching
  q - abort install

Command for another terminal:
  $chmod_cmd
EOF

    printf "Selection [y/r/s/q]: "
    read -r answer
    case "$answer" in
      y|Y|yes|YES)
        run_with_privilege chmod a+rw "$CONTROL_UI_INDEX"
        ;;
      r|R|retry|RETRY)
        ;;
      s|S|skip|SKIP)
        echo "Skipping Control UI index patch. The plugin files and config will still be installed."
        return 1
        ;;
      q|Q|quit|QUIT)
        echo "Aborting install." >&2
        exit 1
        ;;
      *)
        echo "Please enter y, r, s, or q."
        ;;
    esac
  done
}

install_plugin_files() {
  echo "Installing ui-whatsynaptor into: $TARGET_DIR"
  if [ "$(realpath -m "$PACKAGE_ROOT")" = "$(realpath -m "$TARGET_DIR")" ]; then
    echo "Source and target are the same directory; leaving plugin files in place."
    return 0
  fi

  mkdir -p "$TARGET_DIR"
  rm -rf "$TARGET_DIR"
  mkdir -p "$TARGET_DIR"
  cp -a "$PACKAGE_ROOT/." "$TARGET_DIR/"
}

patch_control_ui_index() {
  CONTROL_UI_INDEX="$(detect_control_ui_index || true)"
  if [ -z "$CONTROL_UI_INDEX" ]; then
    echo "Control UI index not found; skipping direct index patch."
    return 0
  fi

  [ -f "$CONTROL_UI_INDEX" ] || return 0
  ensure_control_ui_index_writable || return 0

  local tmp
  tmp="$(mktemp)"

  cat >"$tmp" <<'EOF'
<!-- ui-whatsynaptor-branding:start -->
    <script>window.__UI_PATCHER_BRAND__ = {"appName":"OpenClaw Custom","browserTitle":"OpenClaw Custom Control","sidebarTitle":"OpenClaw Custom","sidebarEyebrow":"Control","logoUrl":"/plugins/ui-whatsynaptor/assets/brand-logo-uBqNKeuY.gif","faviconUrl":"/plugins/ui-whatsynaptor/assets/brand-logo-uBqNKeuY.gif","topbarVideoUrl":"","startupVideoUrl":"","replaceWordmark":true};</script>
    <link rel="stylesheet" href="/plugins/ui-whatsynaptor/assets/brand.css" />
    <script type="module" src="/plugins/ui-whatsynaptor/assets/brand.js"></script>
    <!-- ui-whatsynaptor-branding:end -->
EOF

  INJECT_BLOCK="$(cat "$tmp")"

  node - <<'NODE' "$CONTROL_UI_INDEX" "$tmp"
const fs = require("fs");
const indexPath = process.argv[2];
const blockPath = process.argv[3];
const start = "<!-- ui-whatsynaptor-branding:start -->";
const end = "<!-- ui-whatsynaptor-branding:end -->";
let html = fs.readFileSync(indexPath, "utf8");
const block = fs.readFileSync(blockPath, "utf8").trimEnd();
const rx = new RegExp(`${start.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${end.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\n?`, "g");
html = html.replace(rx, "");
if (html.includes("</head>")) {
  html = html.replace("</head>", `${block}\n  </head>`);
} else {
  html += `\n${block}\n`;
}
fs.writeFileSync(indexPath, html, "utf8");
NODE

  rm -f "$tmp"
  echo "Patched Control UI index: $CONTROL_UI_INDEX"
}

enable_plugin_config() {
  mkdir -p "$OPENCLAW_HOME"
  [ ! -f "$OPENCLAW_CONFIG" ] && echo '{}' >"$OPENCLAW_CONFIG"

  local tmp
  tmp="$(mktemp)"
  jq '
    .plugins = (.plugins // {}) |
    .plugins.entries = (.plugins.entries // {}) |
    .plugins.entries["ui-whatsynaptor"] = (
      (.plugins.entries["ui-whatsynaptor"] // {}) +
      {
        enabled: true,
        config: (
          (.plugins.entries["ui-whatsynaptor"].config // {}) +
          {
            enabled: true,
            appName: "OpenClaw Custom",
            browserTitle: "OpenClaw Custom Control",
            sidebarTitle: "OpenClaw Custom",
            sidebarEyebrow: "Control",
            logoUrl: "/plugins/ui-whatsynaptor/assets/brand-logo-uBqNKeuY.gif",
            topbarVideoUrl: "",
            startupVideoUrl: "",
            accentColor: "#5da78b",
            accentHover: "#74b89d",
            accentGlow: "rgba(93, 167, 139, 0.26)",
            fontBody: "\"Manrope\", -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif",
            fontDisplay: "\"Saira\", \"Manrope\", sans-serif",
            replaceWordmark: true
          }
        )
      }
    )
  ' "$OPENCLAW_CONFIG" >"$tmp"
  mv "$tmp" "$OPENCLAW_CONFIG"
  chmod 600 "$OPENCLAW_CONFIG" 2>/dev/null || true
  echo "Enabled ui-whatsynaptor in: $OPENCLAW_CONFIG"
}

install_jq
install_plugin_files
enable_plugin_config
patch_control_ui_index

echo
echo "Installed non-destructive Control UI branding plugin."
echo "Restart to apply: openclaw gateway restart"
