#!/usr/bin/env bash
# install (scripts.install) for adom/hd-mac-bootstrap — the macOS (Lima/nspawn) platform layer.
#
# Runs as the workspace user after the dependency tree (adom/hd-bootstrap → adom/core,
# adom/adom-workspace-updater) has installed. The generic adom/hd-bootstrap layer already
# deployed the 31 platform-generic hd-* skills + the shared code-server config; THIS layer
# only adds the macOS-runtime specifics on top. Mirrors the platform-layer role of
# adom/hd-windows-bootstrap (which deploys the WSL2-runtime skills), and the config sections of
# hd-wsl2-image/image/bake-hd-setup.sh adapted for the Lima/nspawn machine.
#
# Idempotent: safe to re-run (a live `adompkg install`) — every step overwrites in place.
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILLS="$HOME/.claude/skills"

log() { printf '[hd-mac-bootstrap] %s\n' "$*"; }

# ── deploy the bundled macOS-runtime hd-* skills (flat into ~/.claude/skills/<name>/) ────────
mkdir -p "$SKILLS"
n=0
for d in "$HERE"/skills/hd-*/; do
  [ -f "${d}SKILL.md" ] || continue
  name="$(basename "$d")"
  mkdir -p "$SKILLS/$name"
  cp -f "${d}SKILL.md" "$SKILLS/$name/SKILL.md"
  n=$((n + 1))
done
log "deployed $n macOS-runtime hd-* skills -> $SKILLS"
[ "$n" -gt 0 ] || { echo "[hd-mac-bootstrap] ERROR: no skills deployed" >&2; exit 1; }

# ── code-server workbench seed (trusted domains '*' + activity-bar unpin), macOS path ────────
# The generic layer seeds the workbench; re-assert here so a mac-only re-install converges it.
# code-server's data dir is the same in the Lima/nspawn machine as on WSL2 (Linux workspace).
WB_DIR="$HOME/.local/share/code-server"
if [ -d "$WB_DIR" ]; then
  log "code-server workbench present at $WB_DIR (trusted-domains seed handled by adom/hd-bootstrap)"
else
  log "code-server not found at $WB_DIR yet — skipping workbench seed (non-fatal)"
fi

# ── the `shot` helper — token-efficient screenshots for the workspace AI ─────────────────────
# `adom-cli hydrogen screenshot` prints a ~300 KB base64 dataUrl to stdout; raw in an AI
# conversation that's ~85k wasted tokens per capture. `shot` decodes inline and prints only
# the PNG path (the AI then Reads it). See hd-self-screenshot-mac for the doctrine.
# The canonical script lives at bin/shot in the PAGE repo, but the pkg tarball only ships
# a fixed file set (no bin/) — so the same script is EMBEDDED here. Keep the two in sync.
mkdir -p "$HOME/.local/bin"
if [ -f "$HERE/bin/shot" ]; then
  install -m 755 "$HERE/bin/shot" "$HOME/.local/bin/shot"
else
  cat > "$HOME/.local/bin/shot" <<'SHOT_EOF'
#!/usr/bin/env bash
# shot — one-call HD screenshot that prints ONLY a PNG path (keeps base64 out of the
# AI's context). Installed by adom/hd-mac-bootstrap (canonical source: bin/shot there).
#
#   shot                       # whole workspace (all panels)
#   shot screen                # entire screen (desktop, other apps)
#   shot panel --name "Foo"    # one panel's content
#   shot workspace --reason "verify the flow viewer rendered"
set -euo pipefail
scope="${1:-workspace}"
[ $# -gt 0 ] && shift
out="${SHOT_OUT:-/tmp/shot-${scope}-$(date +%s).png}"
adom-cli hydrogen screenshot "$scope" "$@" 2>/dev/null | python3 -c "
import sys, json, base64
raw = sys.stdin.read()
try:
    d = json.loads(raw)
except Exception:
    sys.stderr.write('shot: unexpected CLI output: ' + raw[:300] + '\n'); sys.exit(1)
u = d.get('dataUrl') or d.get('data_url') or ''
if not u.startswith('data:image'):
    sys.stderr.write('shot: no image returned: ' + json.dumps(d)[:400] + '\n'); sys.exit(1)
open('$out', 'wb').write(base64.b64decode(u.split(',', 1)[1]))
print('$out')
"
SHOT_EOF
  chmod 755 "$HOME/.local/bin/shot"
fi
log "installed the 'shot' screenshot helper -> ~/.local/bin/shot"

# ── Claude Code statusline (Adom-branded) ────────────────────────────────────────────────────
# Model name + context-usage bar (teal/yellow/red) + 5h session % at the bottom of every
# Claude Code session in the workspace. Canonical copy: bin/statusline.sh in the page repo;
# embedded here because the pkg tarball ships no bin/ (same as shot). Non-clobbering merge:
# we only set settings.json's statusLine if the user hasn't configured one.
mkdir -p "$HOME/.claude"
if [ -f "$HERE/bin/statusline.sh" ]; then
  install -m 755 "$HERE/bin/statusline.sh" "$HOME/.claude/statusline.sh"
else
  cat > "$HOME/.claude/statusline.sh" <<'STATUSLINE_EOF'
#!/bin/sh
input=$(cat)
model=$(echo "$input" | sed -n 's/.*"display_name" *: *"\([^"]*\)".*/\1/p')
ctx=$(echo "$input" | grep -o '"used_percentage":[0-9.]*' | head -1 | grep -o '[0-9.]*')
session=$(echo "$input" | grep -o '"five_hour":{[^}]*' | grep -o '"used_percentage":[0-9.]*' | grep -o '[0-9.]*')

# Adom brand colors (truecolor)
C_TEAL=$(printf '\033[38;2;0;184;177m')
C_BLUE=$(printf '\033[38;2;100;171;255m')
C_PURPLE=$(printf '\033[38;2;140;107;247m')
C_RED=$(printf '\033[38;2;255;100;100m')
C_YELLOW=$(printf '\033[38;2;255;193;7m')
C_DIM=$(printf '\033[38;2;120;120;120m')
C_RESET=$(printf '\033[0m')

if [ -n "$model" ]; then
  printf "%s%s%s" "$C_PURPLE" "$model" "$C_RESET"
fi

if [ -n "$ctx" ]; then
  ctx_int=$(printf '%.0f' "$ctx")
  filled=$(( ctx_int / 5 ))
  empty=$(( 20 - filled ))

  if [ "$ctx_int" -ge 80 ]; then
    bar_color="$C_RED"
  elif [ "$ctx_int" -ge 50 ]; then
    bar_color="$C_YELLOW"
  else
    bar_color="$C_TEAL"
  fi

  bar=""
  i=0
  while [ $i -lt $filled ]; do
    bar="${bar}━"
    i=$(( i + 1 ))
  done
  i=0
  while [ $i -lt $empty ]; do
    bar="${bar}╌"
    i=$(( i + 1 ))
  done

  printf " %s[%s %s%%]%s" "$bar_color" "$bar" "$ctx_int" "$C_RESET"
fi

if [ -n "$session" ]; then
  session_int=$(printf '%.0f' "$session")
  if [ "$session_int" -ge 80 ]; then
    s_color="$C_RED"
  elif [ "$session_int" -ge 50 ]; then
    s_color="$C_YELLOW"
  else
    s_color="$C_BLUE"
  fi
  printf " %s%s %s%%%s" "$C_DIM" "5h:" "$s_color$session_int" "$C_RESET"
fi
STATUSLINE_EOF
  chmod 755 "$HOME/.claude/statusline.sh"
fi
# Merge statusLine into ~/.claude/settings.json ONLY if not already configured.
node -e '
const fs = require("fs"), p = process.env.HOME + "/.claude/settings.json";
let s = {}; try { s = JSON.parse(fs.readFileSync(p, "utf8")); } catch (e) {}
if (!s.statusLine) {
  s.statusLine = { type: "command", command: "~/.claude/statusline.sh" };
  fs.writeFileSync(p, JSON.stringify(s, null, 2));
  console.log("[hd-mac-bootstrap] statusLine set in settings.json");
} else {
  console.log("[hd-mac-bootstrap] statusLine already configured - left as-is");
}' 2>/dev/null || log "WARN: node unavailable - statusLine not merged into settings.json"
log "installed the Claude Code statusline -> ~/.claude/statusline.sh"

log "macOS platform layer converged."