#!/usr/bin/env bash
# Augmented Team — impersonation statusline (ENG-5801).
#
# Renders a `🤖 <display-name>` badge in Claude Code's statusline when the
# operator is inside the project directory where they ran
# `agt impersonate connect`. Other Claude Code sessions on the machine —
# including ones in different projects, or this same project after `exit` —
# render plain `dir git:(branch) ✗` with no badge.
#
# Read-only. No `agt` shell-out; just stat + a small Python JSON parse, so
# refresh cost is negligible.

set -u

manifest="$HOME/.augmented-impersonate/active/manifest.json"

if [ -f "$manifest" ]; then
  # Extract project_cwd, code_name, expires_at from the manifest. Python is
  # preinstalled on macOS and matches Node's JSON precisely (jq isn't
  # guaranteed to be on PATH).
  read -r project_cwd code_name expires_at < <(
    python3 - "$manifest" <<'PY' 2>/dev/null
import json, sys
try:
    with open(sys.argv[1]) as f:
        m = json.load(f)
    print(m.get("project_cwd", ""), m.get("code_name", ""), m.get("expires_at", ""))
except Exception:
    pass
PY
  )

  # Only render the badge when this Claude Code session is INSIDE the
  # project where impersonate connect ran. The marker is intentionally
  # global ("one impersonation at a time" by design) so we must scope here.
  if [ -n "${project_cwd:-}" ] && [ "$project_cwd" = "$PWD" ]; then
    # Prefer the H1 display name from the rendered persona CLAUDE.md so the
    # badge reads `🤖 Koda` not `🤖 koda`. Falls back to code_name when the
    # persona file is missing or has no H1.
    display_name="$code_name"
    persona_md="$HOME/.augmented-impersonate/$code_name/CLAUDE.md"
    if [ -f "$persona_md" ]; then
      h1=$(awk '/^# / { sub(/^# +/, ""); print; exit }' "$persona_md" 2>/dev/null)
      [ -n "$h1" ] && display_name="$h1"
    fi

    # expires_at is unix-seconds (matches the manifest's number type). Red
    # EXPIRED badge cues the operator to run `agt impersonate exit`.
    expired=0
    if [ -n "${expires_at:-}" ]; then
      now_epoch=$(date -u +%s)
      # Strip any trailing decimals defensively in case a future manifest
      # writes a float.
      exp_int=${expires_at%%.*}
      if [ -n "$exp_int" ] && [ "$exp_int" -lt "$now_epoch" ] 2>/dev/null; then
        expired=1
      fi
    fi

    # Pin an explicit bright-white foreground (97) alongside the coloured
    # background. Without it the badge text falls back to the terminal's
    # default foreground, which is a dark colour on many themes and renders
    # near-illegibly on the magenta/red background (ENG-5818 follow-up —
    # dark-on-magenta reported on Scout's impersonation badge).
    if [ "$expired" = "1" ]; then
      printf "\033[1;97;41m 🤖 %s EXPIRED \033[0m " "$display_name"
    else
      printf "\033[1;97;45m 🤖 %s \033[0m " "$display_name"
    fi

    # Also rename the terminal tab to the agent name so operators with
    # multiple impersonation windows can tell them apart at a glance.
    # OSC 1 sets the tab title in iTerm2, Terminal.app, Kitty, Alacritty,
    # and most modern terminals. Emitting it every refresh is cheap (same
    # value = no-op for the terminal). On `agt impersonate exit` the
    # operator's user statusline takes over and stops emitting this — the
    # tab title stays stale until the next process changes it; `exit`
    # emits a one-shot reset to put that right.
    printf "\033]1;🤖 %s\007" "$display_name"
  fi
fi

# --- baseline dir + git segment ---
current_dir=$(basename "$PWD")
if git rev-parse --git-dir >/dev/null 2>&1; then
  branch=$(git branch --show-current 2>/dev/null)
  printf "\033[36m%s\033[0m \033[1;34mgit:(\033[31m%s\033[1;34m)\033[0m" "$current_dir" "$branch"
  if ! git diff --quiet 2>/dev/null || ! git diff --cached --quiet 2>/dev/null; then
    printf " \033[33m✗\033[0m"
  fi
else
  printf "\033[36m%s\033[0m" "$current_dir"
fi
