#!/bin/sh
# Agent Notifier - one-line installer.
#
#   curl -fsSL https://notifier.aicrew.in/i | sh
#
# Installs notify.py, links this machine to your account by browser approval,
# and sends a notification to prove it works. No API key is pasted anywhere.
set -eu

SITE_URL="${AGENT_NOTIFIER_SITE_URL:-https://notifier.aicrew.in}"
API_BASE="$SITE_URL/api/v1"
APP_STORE_URL="https://apps.apple.com/app/id6763598043"
ANDROID_BETA_URL="$SITE_URL/android-beta"
BIN_DIR="${AGENT_NOTIFIER_BIN_DIR:-$HOME/bin}"
NOTIFY="$BIN_DIR/notify.py"

# Colour only when attached to a terminal; piped output stays plain.
if [ -t 1 ]; then
  B=$(printf '\033[1m'); DIM=$(printf '\033[2m'); R=$(printf '\033[0m')
  GREEN=$(printf '\033[32m'); RED=$(printf '\033[31m')
else
  B=''; DIM=''; R=''; GREEN=''; RED=''
fi

say()  { printf '%s\n' "$*"; }
fail() { printf '%s%s%s\n' "$RED" "$*" "$R" >&2; exit 1; }

need() {
  command -v "$1" >/dev/null 2>&1 || fail "Agent Notifier needs $1. Install it and re-run this command."
}
need curl
need python3
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 9) else 1)' || fail "Python 3.9 or later is required."
INSTALL_RELAY="${AN_INSTALL_RELAY:-auto}"
INSTALL_ADAPTERS=auto
REENROLL=0
for arg in "$@"; do
  case "$arg" in
    --relay) INSTALL_RELAY=1 ;;
    --no-relay) INSTALL_RELAY=0 ;;
    --reenroll) INSTALL_RELAY=1; REENROLL=1 ;;
    --adapters) INSTALL_ADAPTERS=1 ;;
    --no-adapters) INSTALL_ADAPTERS=0 ;;
    --help) say "Usage: curl -fsSL $SITE_URL/i | sh -s -- [--relay|--no-relay] [--reenroll] [--adapters|--no-adapters]"; exit 0 ;;
    *) fail "Unknown option: $arg (try --help)" ;;
  esac
done
case "$INSTALL_RELAY" in auto|0|1) ;; *) fail "AN_INSTALL_RELAY must be 0 or 1" ;; esac
TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
ask_yes() {
  # curl | sh consumes stdin. Read the controlling terminal, never the script.
  [ -t 1 ] && ( : </dev/tty ) 2>/dev/null || return 1
  printf '%s' "$1" >/dev/tty
  IFS= read -r answer </dev/tty || return 1
  case "$answer" in ''|y|Y|yes|Yes) return 0 ;; *) return 1 ;; esac
}

say "${B}Install the phone app first${R}"
say "  iPhone:      ${B}$APP_STORE_URL${R}"
say "  Android beta: ${B}$ANDROID_BETA_URL${R}"
say "  ${DIM}Open the app, sign in, and allow notifications. Use the same account when the browser opens.${R}"
say ""

# --- 1. Install the CLI -----------------------------------------------------
say "${B}Installing notify.py${R}"
mkdir -p "$BIN_DIR"
curl -fsSL "$SITE_URL/notify.py" -o "$TMP_DIR/notify.py" || fail "Could not download $SITE_URL/notify.py"
chmod +x "$TMP_DIR/notify.py"
mv "$TMP_DIR/notify.py" "$NOTIFY"
say "  ${GREEN}OK${R} $NOTIFY"

# --- 2. Ask for a device code ----------------------------------------------
# python3 is already a hard dependency, so it parses the JSON. Requiring jq as
# well would double the number of machines this cannot run on.
json_get() { python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get(sys.argv[1],""))' "$1"; }
json_obj() { python3 -c 'import json,sys; print(json.dumps({sys.argv[1]: sys.argv[2]}))' "$1" "$2"; }

# Keep a configured account key on re-run; never mint duplicate keys silently.
if python3 - "$SITE_URL" <<'KEY_PY'
import json, os, pathlib, sys
try:
    path = pathlib.Path(os.environ.get('AGENT_NOTIFIER_CONFIG') or '~/.config/agent-notifier/config.json').expanduser()
    config = json.loads(path.read_text())
    ok = bool(config.get('api_key')) and config.get('base_url', 'https://notifier.aicrew.in').rstrip('/') == sys.argv[1] and config.get('api_path', '/api/v1') == '/api/v1'
except (ValueError, OSError):
    ok = False
sys.exit(0 if ok else 1)
KEY_PY
then
  say "  Existing notification key retained."
else
DEVICE_NAME=$(hostname 2>/dev/null || echo 'this machine')
CODE_JSON=$(curl -fsS -X POST "$API_BASE/device/code" \
  -H 'Content-Type: application/json' \
  -d "$(json_obj device_name "$DEVICE_NAME")") \
  || fail "Could not reach $API_BASE. Check your connection."

DEVICE_CODE=$(printf '%s' "$CODE_JSON" | json_get device_code)
USER_CODE=$(printf '%s' "$CODE_JSON" | json_get user_code)
VERIFY_URL=$(printf '%s' "$CODE_JSON" | json_get verification_uri_complete)
INTERVAL=$(printf '%s' "$CODE_JSON" | json_get interval)
[ -n "$DEVICE_CODE" ] || fail "Unexpected response from $API_BASE/device/code"
[ -n "$INTERVAL" ] || INTERVAL=3

say ""
say "${B}Authorize this machine${R}"
say "  Open: ${B}$VERIFY_URL${R}"
say "  Code: ${B}$USER_CODE${R}"
say "  ${DIM}Waiting for approval... (Ctrl-C to cancel)${R}"

# Best-effort: open the browser when there is one. Failure is fine - the URL is
# printed above, which is what makes this work over SSH.
if [ -z "${AGENT_NOTIFIER_NO_BROWSER:-}" ]; then
  { command -v open >/dev/null 2>&1 && open "$VERIFY_URL" >/dev/null 2>&1; } ||
  { command -v xdg-open >/dev/null 2>&1 && xdg-open "$VERIFY_URL" >/dev/null 2>&1; } || true
fi

# --- 3. Poll until approved -------------------------------------------------
API_KEY=''
DEADLINE=$(( $(date +%s) + 600 ))
while [ "$(date +%s)" -lt "$DEADLINE" ]; do
  sleep "$INTERVAL"
  TOKEN_JSON=$(curl -fsS -X POST "$API_BASE/device/token" \
    -H 'Content-Type: application/json' \
    -d "$(json_obj device_code "$DEVICE_CODE")") || continue
  STATUS=$(printf '%s' "$TOKEN_JSON" | json_get status)
  case "$STATUS" in
    approved) API_KEY=$(printf '%s' "$TOKEN_JSON" | json_get api_key); break ;;
    denied)   fail "That request was declined. Nothing was installed beyond notify.py." ;;
    expired)  fail "The code expired. Re-run: curl -fsSL $SITE_URL/i | sh" ;;
  esac
done
[ -n "$API_KEY" ] || fail "Timed out waiting for approval. Re-run: curl -fsSL $SITE_URL/i | sh"

# --- 4. Save the key --------------------------------------------------------
# Piped from a shell builtin, so the key never appears in the process list, and
# --save-config writes it to a 0600 file. No --project: notify.py detects one
# per git repo on every send, so projects appear by themselves.
printf %s "$API_KEY" | "$NOTIFY" --save-config --api-key-stdin --base-url "$SITE_URL" --api-path /api/v1 >/dev/null || fail "Could not save the API key."
unset API_KEY
fi
say ""
say "  ${GREEN}OK${R} Key saved to ~/.config/agent-notifier/config.json"


# --- Relay: separate, explicit device approval ------------------------------
if [ "$INSTALL_RELAY" = auto ]; then
  INSTALL_RELAY=0
  if ask_yes "Install the steering relay and user service? [Y/n] "; then INSTALL_RELAY=1; fi
fi
if [ "$INSTALL_RELAY" = 1 ]; then
  say ""
  say "Installing steering relay (separate machine credential)"
  RELAY_DIR="$HOME/.local/share/agent-notifier/relay"
  AN="$BIN_DIR/an"
  if [ -e "$AN" ] || [ -L "$AN" ]; then
    [ -L "$AN" ] && [ "$(readlink "$AN")" = "$RELAY_DIR/an" ] || fail "$AN already exists and is not our relay link. Move it aside first."
  fi
  curl -fsSL "$SITE_URL/relay.json" -o "$TMP_DIR/relay.json" || fail "Could not download relay; notify.py is still configured."
  python3 - "$TMP_DIR/relay.json" "$RELAY_DIR" <<'RELAY_PY' || fail "Could not install relay; previous files were preserved."
import hashlib, json, pathlib, re, subprocess, sys, tempfile
bundle = json.loads(pathlib.Path(sys.argv[1]).read_text())
target = pathlib.Path(sys.argv[2])
files = bundle['files']
assert bundle['version'] == 1 and 3 <= len(files) <= 100, 'invalid bundle'
paths = [f['path'] for f in files]
assert len(set(paths)) == len(paths), 'duplicate paths'
assert {'an', 'an_relay/__init__.py', 'an_relay/cli.py'} <= set(paths), 'incomplete bundle'
for f in files:
    assert re.fullmatch(r'an|an_relay/[a-z_]+[.]py', f['path']), 'unsafe path'
    assert hashlib.sha256(f['content'].encode()).hexdigest() == f['sha256'], 'corrupt bundle'
target.parent.mkdir(parents=True, exist_ok=True)
assert not target.is_symlink(), 'refusing symlink install directory'
with tempfile.TemporaryDirectory(prefix='.relay-upgrade-', dir=target.parent) as work:
    stage, backup = pathlib.Path(work) / 'new', pathlib.Path(work) / 'previous'
    for f in files:
        p = stage / f['path']
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(f['content'])
        p.chmod(0o700 if f['path'] == 'an' else 0o600)
    subprocess.run([sys.executable, str(stage / 'an'), '--version'], check=True)
    if target.exists():
        target.rename(backup)
    try:
        stage.rename(target)
    except BaseException:
        if backup.exists():
            backup.rename(target)
        raise
RELAY_PY
  ln -sf "$RELAY_DIR/an" "$AN"
  # status never prints a secret. Exit 3 means enrolled but not running too.
  "$AN" status --json > "$TMP_DIR/relay-status.json" 2>/dev/null || true
  if [ "$REENROLL" = 0 ] && python3 - "$TMP_DIR/relay-status.json" "$API_BASE" <<'STATUS_PY'
import json, sys
try:
    status = json.load(open(sys.argv[1]))
    ok = bool(status.get('machine_id')) and status.get('base_url') == sys.argv[2]
except (ValueError, OSError):
    ok = False
sys.exit(0 if ok else 1)
STATUS_PY
  then
    say "  Existing relay enrollment retained (use --reenroll to change consent or rotate)."
  else
    say "  Approve the NEW relay code in a browser/phone; choose projects there."
    "$AN" enroll --base-url "$API_BASE" || fail "Relay approval failed. No new service was installed; notify.py still works. Retry: $AN enroll --base-url $API_BASE && $AN install-service"
  fi
  "$AN" install-service || fail "Relay enrolled, but the user service could not start. Retry: $AN install-service (or run $AN start under your supervisor)."
  # systemd enable --now does not restart an already-active unit on upgrade.
  if [ "$(uname -s)" = Linux ]; then
    UNIT="${AN_RELAY_SERVICE_LABEL:-in.aicrew.agent-notifier.relay}"
    if [ "$UNIT" = in.aicrew.agent-notifier.relay ]; then UNIT=agent-notifier-relay; fi
    systemctl --user restart "$UNIT.service" || fail "Relay installed but service restart failed: systemctl --user restart $UNIT.service"
  fi
  say "  OK Relay installed. Check: $AN status"
  say "  Between agent steps: an inbox --session <id> --claim; terminal opt-in: an attach --help"
  say "  Uninstall service: $AN uninstall-service"
  say "  Then remove $AN and $RELAY_DIR; credential data is retained. See $SITE_URL/setup and docs/AGENT_ADAPTERS.md for revocation."
else
  say "  Steering relay skipped. Enable later: curl -fsSL $SITE_URL/i | sh -s -- --relay"
fi


# Offer repo-local adapters only when detected, or explicitly requested.
if [ "$INSTALL_ADAPTERS" = auto ]; then
  INSTALL_ADAPTERS=0
  if command -v claude >/dev/null 2>&1 || command -v copilot >/dev/null 2>&1; then
    say "  Claude/Copilot detected. Adapters install in the current project: $PWD"
    if ask_yes "Install project hooks and Copilot extension here? [Y/n] "; then INSTALL_ADAPTERS=1; fi
  fi
fi
if [ "$INSTALL_ADAPTERS" = 1 ]; then
  curl -fsSL "$SITE_URL/install.sh" -o "$TMP_DIR/adapters.sh" || fail "Could not download adapters."
  AGENT_NOTIFIER_SITE_URL="$SITE_URL" bash "$TMP_DIR/adapters.sh" || fail "Adapter setup failed; notification and relay setup were retained."
else
  say "  Project adapters skipped. From your repo, re-run with --adapters to install hooks/extension."
fi

# --- 5. Prove it works ------------------------------------------------------
if "$NOTIFY" "Agent Notifier is connected" >/dev/null 2>&1; then
  say "  ${GREEN}OK${R} Test notification sent - check the phone app"
else
  say "  ${DIM}Key saved, but the test notification did not send. Try: $NOTIFY \"hello\"${R}"
fi

# --- 6. PATH ----------------------------------------------------------------
case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *)
    say ""
    say "  ${DIM}$BIN_DIR is not on your PATH. Add this to your shell rc file:${R}"
    say "    export PATH=\"$BIN_DIR:\$PATH\""
    ;;
esac

# --- 7. Teach your agent to use it ------------------------------------------
# ~/AGENTS.md is the closest thing to a universal convention - Codex, opencode,
# and several other harnesses read it from the home directory by default. The
# HTML-comment markers let a re-run refresh its own block without touching
# surrounding instructions. Failure here never aborts the install: the CLI
# itself is already working by this point.
say ""
say "${B}Teaching your agent${R}"
AGENTS_FILE="$HOME/AGENTS.md"

cat <<'AGENT_NOTIFIER_GUIDE_EOF' > "$TMP_DIR/guide"
<!-- BEGIN AGENT NOTIFIER NOTIFY.PY GUIDE -->
## Agent Notifier - keep the human updated (notify.py)

`~/bin/notify.py` pushes real-time updates to my phone and desktop. Use it two ways:

**Ask, don't wait silently.** When you need my input mid-task, use a blocking ask instead
of your built-in interactive question tool - I'm often away from the terminal, a push
reaches me and a terminal prompt does not.
- Yes/No or choices: `~/bin/notify.py --ask "Deploy to prod?" -c Deploy -c Hold`
- Typed answer: `~/bin/notify.py --ask-text "What should the branch be named?"`

**Report progress proactively, with proof.** Don't wait to be asked for status - send an
update at task start, every major milestone, each blocker, and completion, unprompted.
- Progress: `~/bin/notify.py "Migrating database" --progress 0.5` or `--step 3/5` for step N of M
- Proof: `~/bin/notify.py "Tests passing" --file-path ./logs/proof.png`
- Link: `~/bin/notify.py "PR ready" --url https://github.com/... --url-title "Open PR"`
- Blocked/urgent: `~/bin/notify.py "Blocked: need prod creds" --priority 1`

The project auto-detects from the git repo, never pass `--project`. Never echo the API
key. Never say a task is done without attaching proof. Run `~/bin/notify.py --help` for
the full flag list.

**Steering.** Between steps run `an inbox --session <id>` (then `--claim` to read and
acknowledge pending messages), or rely on an explicitly opted-in `an attach`. Never
ignore steering. Use the server session ID; keep normal agent permission gates.
<!-- END AGENT NOTIFIER NOTIFY.PY GUIDE -->
AGENT_NOTIFIER_GUIDE_EOF
if python3 - "$AGENTS_FILE" "$TMP_DIR/guide" <<'GUIDE_PY'
import pathlib, sys
path, guide = map(pathlib.Path, sys.argv[1:])
text = path.read_text() if path.exists() else ''
block = guide.read_text().rstrip()
begin, end = '<!-- BEGIN AGENT NOTIFIER NOTIFY.PY GUIDE -->', '<!-- END AGENT NOTIFIER NOTIFY.PY GUIDE -->'
if begin in text:
    assert text.count(begin) == text.count(end) == 1, 'ambiguous guide markers; edit manually'
    start, finish = text.index(begin), text.index(end)
    assert finish > start, 'invalid guide markers'
    text = text[:start] + block + text[finish + len(end):]
else:
    assert end not in text, 'incomplete guide markers; edit manually'
    text = text.rstrip() + ('\n\n' if text.strip() else '') + block + '\n'
path.write_text(text)
GUIDE_PY
then
  say "  ${GREEN}OK${R} Updated the notify.py and steering guide in ~/AGENTS.md"
else
  say "  ${DIM}Could not update ~/AGENTS.md - see $SITE_URL/setup to add it yourself${R}"
fi

say ""
say "${B}Done.${R} Notify yourself from anything:"
say "  ${DIM}$NOTIFY \"Build finished\"${R}"
say "  ${DIM}$NOTIFY --ask \"Deploy to prod?\" -c Deploy -c Hold${R}"
say "  ${DIM}Your coding agent already knows to use it - see ~/AGENTS.md${R}"
say ""
say "  Docs: $SITE_URL/setup"
