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

BUNDLE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALL_SCOPE="${KIWI_CONTROL_INSTALL_SCOPE:-user}"
RESULT_PATH="${KIWI_CONTROL_RESULT_PATH:-}"

resolve_user_global_home() {
  if [[ -n "${KIWI_CONTROL_HOME:-}" ]]; then
    printf '%s\n' "$KIWI_CONTROL_HOME"
    return
  fi

  printf '%s\n' "$HOME/.kiwi-control"
}

resolve_machine_global_home() {
  if [[ -n "${KIWI_CONTROL_INSTALL_ROOT:-}" ]]; then
    printf '%s\n' "$KIWI_CONTROL_INSTALL_ROOT"
    return
  fi

  printf '%s\n' "/Library/Application Support/Kiwi Control"
}

if [[ "$INSTALL_SCOPE" == "machine" ]]; then
  GLOBAL_HOME="$(resolve_machine_global_home)"
  PATH_BIN="${KIWI_CONTROL_PATH_BIN:-/usr/local/bin}"
  INSTALL_ROOT="$GLOBAL_HOME/cli/kiwi-control-0.2.0-beta.16"
else
  GLOBAL_HOME="$(resolve_user_global_home)"
  PATH_BIN="${KIWI_CONTROL_PATH_BIN:-$HOME/.local/bin}"
  INSTALL_ROOT="$GLOBAL_HOME/releases/kiwi-control-0.2.0-beta.16"
fi
PREFERRED_NODE="${KIWI_CONTROL_NODE_ABSOLUTE:-${KIWI_CONTROL_NODE:-${SHREY_JUNIOR_NODE:-}}}"
PATH_CHANGED=false
DETAIL=""

if [[ -z "$PREFERRED_NODE" ]] && ! command -v node >/dev/null 2>&1; then
  echo "Kiwi Control CLI install error: Node.js 22+ is required for the beta CLI bundle." >&2
  exit 1
fi

mkdir -p "$(dirname "$INSTALL_ROOT")" "$PATH_BIN"
rm -rf "$INSTALL_ROOT"
cp -R "$BUNDLE_ROOT" "$INSTALL_ROOT"

chmod +x "$INSTALL_ROOT/bin/kiwi-control" "$INSTALL_ROOT/bin/kc"

is_path_dir_on_path() {
  case ":$PATH:" in
    *":$PATH_BIN:"*)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

resolve_shell_profile() {
  local shell_name="${KIWI_CONTROL_SHELL:-${SHELL##*/}}"
  case "$shell_name" in
    zsh)
      printf '%s\n' "$HOME/.zshrc"
      ;;
    bash)
      if [[ "${OSTYPE:-}" == darwin* ]]; then
        printf '%s\n' "$HOME/.bash_profile"
      else
        printf '%s\n' "$HOME/.bashrc"
      fi
      ;;
    *)
      printf '%s\n' "$HOME/.profile"
      ;;
  esac
}

upsert_path_profile() {
  local profile_path="$1"
  local begin_marker="# >>> Kiwi Control PATH >>>"
  local end_marker="# <<< Kiwi Control PATH <<<"
  local block_body="export PATH=\"$PATH_BIN:\$PATH\""

  mkdir -p "$(dirname "$profile_path")"
  if [[ ! -f "$profile_path" ]]; then
    : > "$profile_path"
  fi

  python3 - "$profile_path" "$begin_marker" "$end_marker" "$block_body" <<'PY'
from pathlib import Path
import sys

profile_path = Path(sys.argv[1])
begin_marker = sys.argv[2]
end_marker = sys.argv[3]
block_body = sys.argv[4]

block = f"{begin_marker}\n{block_body}\n{end_marker}"
content = profile_path.read_text(encoding="utf-8")

if begin_marker in content and end_marker in content:
    start = content.index(begin_marker)
    end = content.index(end_marker, start) + len(end_marker)
    updated = f"{content[:start].rstrip()}\n{block}\n{content[end:].lstrip()}"
else:
    separator = "\n" if content and not content.endswith("\n") else ""
    updated = f"{content}{separator}{block}\n"

profile_path.write_text(updated, encoding="utf-8")
PY
}

write_wrapper() {
  local wrapper_path="$1"
  cat >"$wrapper_path" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

resolve_node_binary() {
  local preferred_node="__KIWI_CONTROL_PREFERRED_NODE__"
  if [[ -n "$preferred_node" && -x "$preferred_node" ]]; then
    printf '%s\n' "$preferred_node"
    return
  fi

  if [[ -n "${KIWI_CONTROL_NODE:-}" && -x "${KIWI_CONTROL_NODE}" ]]; then
    printf '%s\n' "$KIWI_CONTROL_NODE"
    return
  fi

  if [[ -n "${SHREY_JUNIOR_NODE:-}" && -x "${SHREY_JUNIOR_NODE}" ]]; then
    printf '%s\n' "$SHREY_JUNIOR_NODE"
    return
  fi

  local candidate=""
  if candidate="$(command -v node 2>/dev/null)"; then
    printf '%s\n' "$candidate"
    return
  fi

  for candidate in /opt/homebrew/bin/node /usr/local/bin/node /usr/bin/node; do
    if [[ -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return
    fi
  done

  printf '%s\n' "Kiwi Control requires Node.js 22+ to run." >&2
  exit 1
}

NODE_BIN="$(resolve_node_binary)"
exec "$NODE_BIN" "__KIWI_CONTROL_INSTALL_ROOT__/lib/cli.js" "$@"
EOF
  python3 - "$wrapper_path" "$PREFERRED_NODE" "$INSTALL_ROOT" <<'PY'
from pathlib import Path
import json
import sys

wrapper_path = Path(sys.argv[1])
preferred_node = json.dumps(sys.argv[2])[1:-1]
install_root = json.dumps(sys.argv[3])[1:-1]
content = wrapper_path.read_text(encoding="utf-8")
content = content.replace("__KIWI_CONTROL_PREFERRED_NODE__", preferred_node)
content = content.replace("__KIWI_CONTROL_INSTALL_ROOT__", install_root)
wrapper_path.write_text(content, encoding="utf-8")
PY
  chmod +x "$wrapper_path"
}

write_wrapper "$PATH_BIN/kiwi-control"
write_wrapper "$PATH_BIN/kc"

if [[ "$INSTALL_SCOPE" == "machine" ]]; then
  DETAIL="Kiwi Control terminal commands installed system-wide."
  printf '%s\n' "$DETAIL"
  printf '%s\n' "Primary command: $PATH_BIN/kiwi-control"
  printf '%s\n' "Short alias: $PATH_BIN/kc"
  printf '%s\n' "Shared PATH location: $PATH_BIN"
else
  printf '%s\n' "Kiwi Control CLI installed."
  printf '%s\n' "Primary command: $PATH_BIN/kiwi-control"
  printf '%s\n' "Short alias: $PATH_BIN/kc"
  if is_path_dir_on_path; then
    DETAIL="PATH already includes $PATH_BIN"
    printf '%s\n' "$DETAIL"
  else
    PROFILE_PATH="$(resolve_shell_profile)"
    upsert_path_profile "$PROFILE_PATH"
    PATH_CHANGED=true
    DETAIL="PATH updated in $PROFILE_PATH"
    printf '%s\n' "$DETAIL"
    printf '%s\n' "Next step: open a new terminal window."
  fi
fi

if [[ -n "$RESULT_PATH" ]]; then
  python3 - "$RESULT_PATH" "$INSTALL_SCOPE" "$INSTALL_ROOT" "$PATH_BIN" "$PATH_CHANGED" "$DETAIL" "$PATH_BIN/kiwi-control" "$PATH_BIN/kc" <<'PY'
from pathlib import Path
import json
import sys

result_path = Path(sys.argv[1])
payload = {
    "installScope": sys.argv[2],
    "installRoot": sys.argv[3],
    "installBinDir": sys.argv[4],
    "pathChanged": sys.argv[5].lower() == "true",
    "detail": sys.argv[6],
    "primaryCommandPath": sys.argv[7],
    "shortCommandPath": sys.argv[8],
}
result_path.parent.mkdir(parents=True, exist_ok=True)
result_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
PY
fi
