#!/usr/bin/env bash
# install.sh — wire the music skill into Claude Code.
#
# Three operations:
#   1. UserPromptSubmit hook → music-hook.sh appended to ~/.claude/settings.json
#   2. Statusline option     → ~/.claude/statuslines/music.sh wrapper installed
#   3. Discovery pointer     → ~/.claude/CLAUDE.md gets the play-history line
#
# Idempotent: rerunning is safe.

set -euo pipefail

REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BIN_DIR="$REPO_DIR/bin"
COMMANDS_DIR="$REPO_DIR/commands"
SETTINGS="$HOME/.claude/settings.json"
STATUSLINES_DIR="$HOME/.claude/statuslines"
COMMANDS_USER_DIR="$HOME/.claude/commands"
CLAUDE_MD="$HOME/.claude/CLAUDE.md"
HISTORY_DIR="$HOME/.cache/music"
SUPPORT_DIR="$HOME/Library/Application Support/music"
PLIST="$HOME/Library/LaunchAgents/supply.music.poll.plist"
PLIST_LABEL="supply.music.poll"

# Hook and statusline run from copies in SUPPORT_DIR, never from BIN_DIR.
# BIN_DIR is wherever the package happens to sit, and for `npx` users that
# is a content-hashed cache path (~/.npm/_npx/<hash>/…) that changes with
# every version — a hard-coded reference there breaks on the next upgrade
# and is silently pruned by `npm cache clean`. The daemon already runs
# from copies for the same class of reason (launchd TCC).
RUN_DIR="$SUPPORT_DIR"
HOOK_CMD="bash \"$RUN_DIR/music-hook.sh\""
# Match on filename, not full path: the mark has to recognize entries
# written by ANY earlier version, whose absolute paths we cannot predict.
# Without this, each upgrade appends a duplicate hook pointing at a dead
# npx directory, and uninstall leaves the old ones behind.
HOOK_MARK="music-hook.sh"
CLAUDE_MD_LINE='- Music context (managed by music skill, not auto-injected): current track snapshot at `~/.cache/music/now-playing.txt`, full listening log at `~/.cache/music/play_history.md`. Read when the user asks about what they are listening to, when matching tone to current music makes sense, or when they ask about listening patterns / vibe drift.'

say() { printf '\033[36m[music]\033[0m %s\n' "$*"; }
fail() { printf '\033[31m[music]\033[0m %s\n' "$*" >&2; exit 1; }

# ── 1. dependency check ─────────────────────────────────────────────
say "checking dependencies"
for bin in nowplaying-cli jq curl python3; do
  command -v "$bin" >/dev/null 2>&1 || fail "missing dependency: $bin (try: brew install $bin)"
done

# ── 2. ensure dirs ──────────────────────────────────────────────────
mkdir -p "$STATUSLINES_DIR" "$HISTORY_DIR" "$(dirname "$SETTINGS")" "$SUPPORT_DIR" "$(dirname "$PLIST")" "$COMMANDS_USER_DIR"

# ── 3. patch settings.json (append hook, don't clobber) ─────────────
say "registering UserPromptSubmit hook"
[[ -f "$SETTINGS" ]] || echo '{}' > "$SETTINGS"

# Drop every entry of ours — any version, any path — then add exactly one
# pointing at RUN_DIR. Rewriting rather than skipping is what repairs an
# install that already carries a stale npx path; skipping would preserve it.
STALE_HOOKS="$(jq -r --arg m "$HOOK_MARK" '
  [.hooks.UserPromptSubmit // [] | .[].hooks // [] | .[].command // ""]
  | map(select(contains($m) and (contains($m) and (test("Application Support/music") | not))))
  | length
' "$SETTINGS" 2>/dev/null || echo 0)"

tmp="$(mktemp)"
jq --arg m "$HOOK_MARK" --arg cmd "$HOOK_CMD" '
  .hooks //= {} |
  .hooks.UserPromptSubmit //= [] |
  # Strip our own entries, keeping any unrelated hooks the user added.
  .hooks.UserPromptSubmit |= map(
    .hooks = ((.hooks // []) | map(select((.command // "") | contains($m) | not)))
  ) |
  # An entry whose hooks list is now empty was purely ours — drop it, but
  # never drop one that still holds someone else'"'"'s hook.
  .hooks.UserPromptSubmit |= map(select((.hooks // []) | length > 0)) |
  .hooks.UserPromptSubmit += [{
    hooks: [{
      type: "command",
      command: $cmd,
      timeout: 5
    }]
  }]
' "$SETTINGS" > "$tmp"
mv -f "$tmp" "$SETTINGS"
if [[ "${STALE_HOOKS:-0}" -gt 0 ]]; then
  say "  replaced $STALE_HOOKS stale hook entr$([[ "$STALE_HOOKS" == 1 ]] && echo y || echo ies)"
else
  say "  registered"
fi

# ── 4. install statusline vibe option ───────────────────────────────
# music is a composing vibe: it runs the user's existing base vibe
# (default "pomodoro") first, then appends the 🎧 line so context bar /
# weather / etc. stay visible. Override base with VIBE_BASE env var.
say "installing statusline option at $STATUSLINES_DIR/music.sh"
cat > "$STATUSLINES_DIR/music.sh" <<EOF
#!/usr/bin/env bash
# Auto-generated by music install.sh
input="\$(cat)"
BASE="\${VIBE_BASE:-pomodoro}"
BASE_SCRIPT="\$HOME/.claude/statuslines/\${BASE}.sh"
if [[ -x "\$BASE_SCRIPT" && "\$BASE" != "music" ]]; then
  printf '%s' "\$input" | bash "\$BASE_SCRIPT" || true
fi
printf '%s' "\$input" | bash "$RUN_DIR/music-statusline.sh" || true
EOF
chmod +x "$STATUSLINES_DIR/music.sh"

# ── 5. background polling daemon ────────────────────────────────────
# Claude Code's statusline timer is unreliable in current versions and
# nothing else triggers music-poll.sh between user messages. A launchd
# KeepAlive job runs a loop with `sleep 2` so the cache stays fresh and
# the 30s history-append threshold fires regardless of user activity.
# Source files must live outside ~/Documents because launchd-spawned
# processes lack TCC access there.
say "installing background poll daemon"
cp "$BIN_DIR/music-poll.sh"          "$SUPPORT_DIR/poll.sh"
cp "$BIN_DIR/music-enrich.sh"        "$SUPPORT_DIR/music-enrich.sh"
cp "$BIN_DIR/music-spotify-auth.sh"  "$SUPPORT_DIR/music-spotify-auth.sh"
cp "$BIN_DIR/music-player-state.sh"  "$SUPPORT_DIR/music-player-state.sh"
# The daemon periodically refreshes the Liked cache via this script, so it
# must live beside its helpers (it sources music-spotify-auth.sh).
cp "$BIN_DIR/music-history-sync.sh"  "$SUPPORT_DIR/music-history-sync.sh"
# Hook and statusline also run from here (see RUN_DIR above). Both locate
# their helpers as siblings via SCRIPT_DIR, so music-poll.sh must exist
# under its own name too — poll.sh is the daemon's copy, a different name.
cp "$BIN_DIR/music-hook.sh"          "$SUPPORT_DIR/music-hook.sh"
cp "$BIN_DIR/music-statusline.sh"    "$SUPPORT_DIR/music-statusline.sh"
cp "$BIN_DIR/music-poll.sh"          "$SUPPORT_DIR/music-poll.sh"
chmod +x "$SUPPORT_DIR/poll.sh" "$SUPPORT_DIR/music-enrich.sh" "$SUPPORT_DIR/music-player-state.sh" \
         "$SUPPORT_DIR/music-hook.sh" "$SUPPORT_DIR/music-statusline.sh" "$SUPPORT_DIR/music-poll.sh" \
         "$SUPPORT_DIR/music-history-sync.sh"
cat > "$SUPPORT_DIR/daemon.sh" <<EOF
#!/bin/bash
# Long-running poll loop. macOS throttles short StartInterval values,
# so we use one persistent process kept alive by launchd instead.
# Each poll is hard-bounded so a hung curl or wedged nowplaying-cli
# call can't pin the daemon and stale the cache.
#
# Prefers GNU timeout (gtimeout from coreutils, or 'timeout' on Linux);
# falls back to a pure-bash watchdog when neither is on PATH (macOS
# ships without coreutils). The fallback enables job control (set -m)
# so the poll runs in its own process group, then sends SIGKILL to the
# whole group — otherwise hung curl/nowplaying-cli children survive as
# orphans and accumulate over time.
INTERVAL=2
POLL_TIMEOUT=15
POLL="$SUPPORT_DIR/poll.sh"
# Liked cache refresh. /me/tracks/contains is dead for new Spotify apps,
# so liked status is judged against a local snapshot that only this sync
# refreshes. Nothing else triggers it, so fold it into the poll loop:
# once every SYNC_EVERY iterations (900 × 2s ≈ 30min). Bounded by its own
# timeout so a slow Spotify call can't stall polling; failure is ignored.
SYNC="$SUPPORT_DIR/music-history-sync.sh"
SYNC_EVERY=900
SYNC_TIMEOUT=20
_sync_ticks=0

run_sync() {
  [[ -f "\$SYNC" ]] || return
  local bin=""
  command -v gtimeout >/dev/null 2>&1 && bin="gtimeout"
  [[ -z "\$bin" ]] && command -v timeout >/dev/null 2>&1 && bin="timeout"
  if [[ -n "\$bin" ]]; then
    "\$bin" -k 2 "\$SYNC_TIMEOUT" /bin/bash "\$SYNC" library >/dev/null 2>>/tmp/music-sync.err || true
  else
    /bin/bash "\$SYNC" library >/dev/null 2>>/tmp/music-sync.err &
    local sp=\$!
    ( sleep "\$SYNC_TIMEOUT"; kill -KILL "\$sp" 2>/dev/null ) &
    local swd=\$!
    wait "\$sp" 2>/dev/null || true
    kill -KILL "\$swd" 2>/dev/null
    wait "\$swd" 2>/dev/null
  fi
}

run_poll() {
  local bin=""
  command -v gtimeout >/dev/null 2>&1 && bin="gtimeout"
  [[ -z "\$bin" ]] && command -v timeout >/dev/null 2>&1 && bin="timeout"
  if [[ -n "\$bin" ]]; then
    # -k 2: if SIGTERM doesn't take in 2s, follow with SIGKILL.
    "\$bin" -k 2 "\$POLL_TIMEOUT" /bin/bash "\$POLL" 2>>/tmp/music-poll.err
    return
  fi
  # Pure-bash fallback. set -m makes each backgrounded command a
  # process group leader; "kill -- -PID" then signals the whole group.
  set -m
  /bin/bash "\$POLL" 2>>/tmp/music-poll.err &
  local pid=\$!
  (
    sleep "\$POLL_TIMEOUT"
    kill -TERM -- "-\$pid" 2>/dev/null
    sleep 1
    kill -KILL -- "-\$pid" 2>/dev/null
  ) &
  local wd=\$!
  wait "\$pid" 2>/dev/null
  kill -KILL "\$wd" 2>/dev/null
  wait "\$wd" 2>/dev/null
  set +m
}

while true; do
  run_poll
  # Refresh the Liked cache on the first iteration and every SYNC_EVERY
  # thereafter (first run seeds it immediately after a daemon restart).
  if (( _sync_ticks % SYNC_EVERY == 0 )); then
    run_sync
  fi
  _sync_ticks=\$(( _sync_ticks + 1 ))
  sleep "\$INTERVAL"
done
EOF
chmod +x "$SUPPORT_DIR/daemon.sh"

cat > "$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>$PLIST_LABEL</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>$SUPPORT_DIR/daemon.sh</string>
    </array>
    <key>KeepAlive</key>
    <true/>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/dev/null</string>
    <key>StandardErrorPath</key>
    <string>/tmp/music-poll.err</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
    </dict>
</dict>
</plist>
EOF

# Reload (unload then load) so changes to plist or scripts take effect.
launchctl unload "$PLIST" 2>/dev/null || true
launchctl load "$PLIST"
say "  daemon loaded ($PLIST_LABEL)"

# ── 6. slash commands: symlink skills/music/commands/*.md into
#       ~/.claude/commands/ so users can invoke /vibe etc. directly.
#       Symlink (not copy) so repo edits pick up immediately and users
#       can't end up with stale copies after a git pull.
say "installing slash commands into $COMMANDS_USER_DIR"
if [[ -d "$COMMANDS_DIR" ]]; then
  while IFS= read -r -d '' cmd_file; do
    base="$(basename "$cmd_file")"
    target="$COMMANDS_USER_DIR/$base"
    if [[ -L "$target" ]]; then
      # Our symlink (or someone else's) — overwrite ours only.
      existing="$(readlink "$target")"
      if [[ "$existing" == "$cmd_file" ]]; then
        say "  /${base%.md} already linked — skipping"
        continue
      fi
      rm -f "$target"
      ln -s "$cmd_file" "$target"
      say "  /${base%.md} relinked"
    elif [[ -e "$target" ]]; then
      # Real file — user has a same-named command. Don't clobber.
      say "  /${base%.md} exists as a regular file — skipping to avoid clobber"
    else
      ln -s "$cmd_file" "$target"
      say "  /${base%.md} linked"
    fi
  done < <(find "$COMMANDS_DIR" -maxdepth 1 -type f -name '*.md' -print0)
fi

# ── 7. CLAUDE.md pointer (idempotent) ───────────────────────────────
# The pointer tells Claude where the snapshot + history files live so
# they're discoverable from any cwd (we no longer auto-inject context).
# If an older version of this skill left a pointer in CLAUDE.md, strip
# it before appending the canonical one.
say "ensuring music pointer in $CLAUDE_MD"
touch "$CLAUDE_MD"
if grep -qF "music/now-playing.txt" "$CLAUDE_MD"; then
  say "  pointer already present — skipping"
else
  if grep -qF "music/play_history.md" "$CLAUDE_MD"; then
    # Older single-line pointer present — remove it, we'll append the new one.
    tmp="$(mktemp)"
    grep -vF "music/play_history.md" "$CLAUDE_MD" > "$tmp" || true
    mv -f "$tmp" "$CLAUDE_MD"
    say "  upgraded older pointer"
  fi
  printf '\n%s\n' "$CLAUDE_MD_LINE" >> "$CLAUDE_MD"
  say "  appended"
fi

say "done."
cat <<'INSTRUCT'

Next steps:
  1. The hook is now active for any NEW Claude Code session. Existing
     sessions won't see it until you /clear or restart.

  2. The launchd daemon is already running and polling every 2s. Cache
     stays fresh whether or not you're talking to Claude. Verify:
       cat /tmp/music-current.json
       launchctl list | grep supply.music.poll

  3. To enable the 🎧 statusline as your default vibe, edit
     ~/.claude/statusline-command.sh and change the fallback from
     "pomodoro" to "music". (Per-session vibe files don't reliably
     work because Claude Code's PPID rotates between statusline ticks.)

  4. Verify history append after listening to a song for 30s+:
       tail -n 5 ~/.cache/music/play_history.md

  5. Note: Claude Code's statusline doesn't auto-refresh on a timer in
     current versions — it only re-renders on events (new assistant
     message, mode change, etc.). The daemon keeps the cache fresh so
     when statusline DOES render, it shows the latest. The countdown
     therefore won't tick visually between events; that's a Claude Code
     limitation, not an music bug.

INSTRUCT
