#!/usr/bin/env bash
# Human01 installer for Claude Code (macOS / Linux).
# Adds the Human01 Anthropic-Messages endpoint and the current Claude model
# mappings to ~/.claude/settings.json. Existing settings and other env vars are
# preserved and the file is backed up first. The API key is taken from
# HUMAN01_API_KEY or entered with hidden input. It then offers the Human01 plugin for Claude Code
# (pinned notes, session warnings, status line); skip it with --no-plugin or HUMAN01_NO_PLUGIN=1.
set -euo pipefail

INSTALL_PLUGIN=1
for arg in "$@"; do case "$arg" in --no-plugin) INSTALL_PLUGIN=0 ;; esac; done
if [ "${HUMAN01_NO_PLUGIN:-}" = "1" ]; then INSTALL_PLUGIN=0; fi

# --- 1. Detect Claude Code -------------------------------------------------
if ! command -v claude >/dev/null 2>&1; then
  echo "Claude Code was not found on PATH. Install it (https://docs.anthropic.com/en/docs/claude-code/quickstart), open a new terminal, and run this installer again. No config changes were made." >&2
  exit 127
fi
claude_version="$(claude --version 2>/dev/null | head -n1)" || true
claude_version="${claude_version:-(installed)}"
printf 'Detected Claude Code: %s\n' "$claude_version"

# --- 2. Require python3 (safe JSON merge) --------------------------------
if ! command -v python3 >/dev/null 2>&1; then
  echo "Python 3 is required to safely merge Claude Code's settings.json. No config changes were made." >&2
  exit 127
fi

# --- 3. Locate config -------------------------------------------------------
SETTINGS_FILE="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/settings.json"

# --- 4. Merge (python) --------------------------------------------------------
python3 - "$SETTINGS_FILE" <<'PY'
import getpass, json, os, shutil, subprocess, sys, urllib.request
from datetime import datetime, timezone


def fetch_json(url):
    # urllib can fail TLS handshakes in some shells; curl is the fallback.
    req = urllib.request.Request(url, method="GET")
    req.add_header("User-Agent", "curl/8.0")
    try:
        with urllib.request.urlopen(req, timeout=20) as response:
            return json.load(response)
    except Exception:
        raw = subprocess.run(["curl", "-fsSL", "--max-time", "20", url], capture_output=True, check=True).stdout
        return json.loads(raw)

path = sys.argv[1]
BASE = "https://llm.human01.xyz"

# Load the live Human01 model catalog and pick the current Claude
# opus/sonnet/haiku IDs for the ANTHROPIC_DEFAULT_*_MODEL mappings.
def _pick(claude_models, family):
    """Return the newest available model id for a family (opus/sonnet/haiku)."""
    fam = [m for m in claude_models if m.startswith(family)]
    if not fam:
        return None
    # Sort by the numeric version suffix descending (e.g. 5-5 > 4-5).
    def _ver(mid):
        tail = mid.split(family)[-1]
        nums = []
        for chunk in tail.replace("-", ".").split("."):
            try:
                nums.append(int(chunk))
            except ValueError:
                pass
        return tuple(nums)
    fam.sort(key=_ver, reverse=True)
    return fam[0]

catalog_ids = set()
claude_models = []
try:
    catalog = fetch_json(BASE + "/v1/models").get("data", [])
    for m in catalog:
        if isinstance(m, dict) and isinstance(m.get("id"), str):
            catalog_ids.add(m["id"])
            if m["id"].startswith(("claude-opus-", "claude-sonnet-", "claude-haiku-")):
                claude_models.append(m["id"])
except Exception as exc:
    print(f"Could not load Human01 models: {exc}. No changes were made.", file=sys.stderr)
    sys.exit(1)

opus = _pick(claude_models, "claude-opus-") or "claude-opus-5-5"
sonnet = _pick(claude_models, "claude-sonnet-") or "claude-sonnet-5-5"
haiku = _pick(claude_models, "claude-haiku-") or "claude-haiku-5-5"

# Load existing settings.json (preserve everything).
config = {}
if os.path.exists(path):
    try:
        # utf-8-sig strips a BOM if present (harmless if not), so a BOM'd
        # settings.json still parses instead of failing the merge.
        with open(path, encoding="utf-8-sig") as f:
            config = json.load(f)
    except Exception as exc:
        print(f"Could not safely parse {path}: {exc}", file=sys.stderr)
        print("No changes were made. If the file uses comments (JSONC), add the Human01 env block manually.", file=sys.stderr)
        sys.exit(1)
if not isinstance(config, dict):
    print("Expected a JSON object; no changes were made.", file=sys.stderr)
    sys.exit(1)

# Merge the Human01 env vars into the existing env block.
env = config.get("env")
if env is None:
    env = {}
elif not isinstance(env, dict):
    print("The existing 'env' setting is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)

# Determine the API key: env var, or prompt.
api_key = os.environ.get("HUMAN01_API_KEY")
if not api_key:
    api_key = getpass.getpass("Human01 API key (input hidden; saved in Claude Code settings.json): ").strip()
if not api_key:
    print("No API key provided. No changes were made.", file=sys.stderr)
    sys.exit(1)

# Only override the Human01-owned env keys if they are unset or already
# point at Human01 (so we don't clobber a user's own Anthropic setup).
def _is_human01(val):
    return isinstance(val, str) and BASE in val

# The installer's clear intent is "put Claude Code on Human01", so it takes over
# the Human01-owned slots (base URL + credential + model mappings + traffic
# flag) while preserving unrelated env vars (e.g. NODE_OPTIONS) and other
# settings (theme, permissions). It records what it changed so it can report
# a clear summary (and the old values are recoverable from the backup).
human01_env = {
    "ANTHROPIC_AUTH_TOKEN": api_key,
    "ANTHROPIC_BASE_URL": BASE,
    "ANTHROPIC_DEFAULT_OPUS_MODEL": opus,
    "ANTHROPIC_DEFAULT_SONNET_MODEL": sonnet,
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": haiku,
    "ANTHROPIC_SMALL_FAST_MODEL": haiku,
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
}
changes = []
for k, v in human01_env.items():
    cur = env.get(k)
    if cur != v:
        # Mask the credential in the summary so it isn't echoed in full.
        shown_cur = (cur[:12] + "...") if (k == "ANTHROPIC_AUTH_TOKEN" and isinstance(cur, str) and len(cur) > 12) else cur
        shown_new = (v[:12] + "...") if (k == "ANTHROPIC_AUTH_TOKEN" and isinstance(v, str) and len(v) > 12) else v
        changes.append(f"{k}: {shown_cur!r} -> {shown_new!r}")
    env[k] = v

# Compact long sessions at 400K tokens instead of near the 1M window: every turn re-reads the whole
# context, so late compaction makes long sessions the bulk of spend. Only set when the user has not
# chosen a value; /autocompact or this setting changes it.
if "CLAUDE_CODE_AUTO_COMPACT_WINDOW" not in env:
    env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = "400000"
    changes.append("CLAUDE_CODE_AUTO_COMPACT_WINDOW: (unset) -> '400000'")

config["env"] = env
# Mark onboarding complete so Claude Code doesn't prompt again.
config.setdefault("hasCompletedOnboarding", True)

# Backup + atomic write.
os.makedirs(os.path.dirname(path), exist_ok=True)
if os.path.exists(path):
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
    backup = path + ".backup-" + stamp
    shutil.copy2(path, backup)
    print(f"Backup: {backup}")
tmp = path + ".human01-tmp"
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
    json.dump(config, f, indent=2, ensure_ascii=False)
    f.write("\n")
os.replace(tmp, path)
print(f"Human01 endpoint and Claude models (opus={opus}, sonnet={sonnet}, haiku={haiku}) added to {path}")
if changes:
    print("Changed settings:")
    for c in changes:
        print(f"  {c}")
    print("(Previous values are preserved in the backup file above.)")
print("Start Claude Code and it will use Human01. Switch models inside a session with /model.")
PY

# --- 5. Human01 plugin for Claude Code (optional) ------------------------------
# Installed from the gateway into a local plugin folder (no git, no account). Running this installer again
# updates it. It sends Human01 the session ID and token counts, never prompts, code or files.
BASE_URL="${HUMAN01_BASE_URL:-https://llm.human01.xyz}"
PLUGIN_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/human01-plugin"
PLUGIN_FILES="plugin.json marketplace.json hooks/hooks.json scripts/human01.mjs commands/pin.md commands/pins.md commands/unpin.md commands/statusline.md"
install_human01_plugin() {
  if [ "$INSTALL_PLUGIN" != "1" ]; then echo "Skipped the Human01 plugin (--no-plugin)."; return 0; fi
  if ! command -v node >/dev/null 2>&1; then
    echo "Skipped the Human01 plugin: it needs Node.js. Install Node.js and run this installer again to add it."; return 0
  fi
  if ! command -v curl >/dev/null 2>&1; then echo "Skipped the Human01 plugin: curl was not found."; return 0; fi
  # Ask only when a terminal is attached; a piped, unattended run installs it.
  if [ -t 1 ] && (exec </dev/tty) 2>/dev/null; then
    printf '\n%s\n%s ' "Install the Human01 plugin for Claude Code? It keeps your pinned notes through compaction, shows spend-cap and session warnings, and adds a status line with cache, spend and context. It sends Human01 your session ID and token counts, never prompts, code or files." "Install it? [Y/n]" >/dev/tty
    local answer=""
    read -r answer </dev/tty || answer=""
    case "$answer" in [nN]*) echo "Skipped the Human01 plugin. Run this installer again to add it later."; return 0 ;; esac
  fi
  local tmp f
  tmp="$(mktemp -d)" || { echo "Skipped the Human01 plugin: no temporary folder."; return 0; }
  for f in $PLUGIN_FILES; do
    mkdir -p "$tmp/$(dirname "$f")"
    if ! curl -fsSL "$BASE_URL/claude-code-plugin/$f" -o "$tmp/$f"; then
      echo "Skipped the Human01 plugin: could not download $f."; rm -rf "$tmp"; return 0
    fi
  done
  mkdir -p "$tmp/.claude-plugin"
  mv "$tmp/plugin.json" "$tmp/marketplace.json" "$tmp/.claude-plugin/"
  rm -rf "$PLUGIN_DIR"
  mkdir -p "$(dirname "$PLUGIN_DIR")"
  mv "$tmp" "$PLUGIN_DIR"
  claude plugin marketplace add "$PLUGIN_DIR" --scope user >/dev/null 2>&1 || true # already added: files were updated in place
  if claude plugin install human01@human01 --scope user -y >/dev/null 2>&1; then
    echo "Installed the Human01 plugin for Claude Code (skip it next time with --no-plugin)."
  elif claude plugin list 2>/dev/null | grep -q "human01@human01"; then
    echo "Updated the Human01 plugin for Claude Code."
  else
    echo "Could not install the Human01 plugin automatically. In Claude Code, run /plugin marketplace add $PLUGIN_DIR and then /plugin install human01@human01."
    return 0
  fi
  local status=0
  node "$PLUGIN_DIR/scripts/human01.mjs" install-statusline >/dev/null 2>&1 || status=$?
  case "$status" in
    0) echo "Added the Human01 status line to Claude Code." ;;
    2) echo "Kept your existing Claude Code status line. To use Human01's instead, run /statusline in Claude Code." ;;
    *) echo "Could not add the Human01 status line; run /statusline in Claude Code to try again." ;;
  esac
}
install_human01_plugin
