#!/usr/bin/env bash
# inflight: report what you're working on to https://inflight.cretezy.com
#
#   inflight.sh set "Short title" [--details TEXT] [--link URL] [--key KEY] [--ttl SECONDS]
#   inflight.sh heartbeat [--key KEY] [--ttl SECONDS]
#   inflight.sh clear [--key KEY]
#   inflight.sh list
#
# Env: INFLIGHT_API_KEY (or saved in ~/.config/inflight/key by install.sh)
#      INFLIGHT_URL      (default https://inflight.cretezy.com)
#      INFLIGHT_AGENT    (label shown on the board, default "claude-code")
#      INFLIGHT_REPO     (owner/repo; default: parsed from `git remote get-url origin`)
set -euo pipefail

URL="${INFLIGHT_URL:-https://inflight.cretezy.com}"
KEY_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/inflight/key"
if [[ -z "${INFLIGHT_API_KEY:-}" && -r $KEY_FILE ]]; then INFLIGHT_API_KEY=$(<"$KEY_FILE"); fi
AGENT="${INFLIGHT_AGENT:-claude-code}"

die() { echo "inflight: $*" >&2; exit 1; }

json_str() {
  local s=$1
  s=${s//\\/\\\\}; s=${s//\"/\\\"}; s=${s//$'\n'/\\n}; s=${s//$'\r'/}; s=${s//$'\t'/\\t}
  printf '"%s"' "$s"
}

detect_repo() {
  if [[ -n "${INFLIGHT_REPO:-}" ]]; then echo "$INFLIGHT_REPO"; return; fi
  local remote
  remote=$(git remote get-url origin 2>/dev/null) || die "no git remote 'origin'; set INFLIGHT_REPO=owner/repo"
  remote=${remote%.git}
  if [[ $remote =~ github\.com[:/]+([^/]+)/([^/]+)$ ]]; then
    echo "${BASH_REMATCH[1]}/${BASH_REMATCH[2]}"
  else
    die "origin is not a GitHub remote ($remote); set INFLIGHT_REPO=owner/repo"
  fi
}

default_key() {
  local b
  b=$(git branch --show-current 2>/dev/null || true)
  [[ -z $b ]] && b=$(jj log -r @ --no-graph -T 'change_id.short()' 2>/dev/null || true)
  [[ -z $b ]] && b=default
  echo "${AGENT}-${b}" | tr -c 'A-Za-z0-9_.:-' '-' | cut -c1-100 | sed 's/-*$//'
}

call() {
  local method=$1 path=$2 body=${3:-}
  [[ -n "${INFLIGHT_API_KEY:-}" ]] || die "no API key: set INFLIGHT_API_KEY or save it to $KEY_FILE (create one at $URL/agents)"
  local args=(-sS -X "$method" -H "authorization: Bearer $INFLIGHT_API_KEY" -w '\n%{http_code}')
  [[ -n $body ]] && args+=(-H 'content-type: application/json' --data "$body")
  local out code
  out=$(curl "${args[@]}" "$URL$path") || die "request failed"
  code=${out##*$'\n'}; out=${out%$'\n'*}
  if [[ $code -ge 400 ]]; then die "HTTP $code: $out"; fi
  echo "$out"
}

cmd=${1:-}; shift || true
title="" details="" link="" key="" ttl=""
if [[ $cmd == set ]]; then title=${1:-}; shift || true; fi
while [[ $# -gt 0 ]]; do
  case $1 in
    --details) details=$2; shift 2 ;;
    --link) link=$2; shift 2 ;;
    --key) key=$2; shift 2 ;;
    --ttl) ttl=$2; shift 2 ;;
    *) die "unknown argument: $1" ;;
  esac
done

repo=$(detect_repo)
key=${key:-$(default_key)}

case $cmd in
  set)
    [[ -n $title ]] || die 'usage: inflight.sh set "title" [--details ..] [--link ..]'
    body="{\"title\":$(json_str "$title"),\"agent\":$(json_str "$AGENT")"
    [[ -n $details ]] && body+=",\"details\":$(json_str "$details")"
    [[ -n $link ]] && body+=",\"link\":$(json_str "$link")"
    [[ -n $ttl ]] && body+=",\"ttl\":$ttl"
    body+="}"
    call PUT "/api/repos/$repo/items/$key" "$body" >/dev/null
    echo "inflight: posted to $URL/$repo ($key)"
    ;;
  heartbeat)
    hb=""
    [[ -n $ttl ]] && hb="{\"ttl\":$ttl}"
    call POST "/api/repos/$repo/items/$key/heartbeat" "$hb" >/dev/null
    echo "inflight: refreshed $key"
    ;;
  clear)
    call DELETE "/api/repos/$repo/items/$key" >/dev/null
    echo "inflight: cleared $key"
    ;;
  list)
    curl -sS "$URL/api/repos/$repo/items"
    echo
    ;;
  *)
    sed -n '2,13p' "$0"; exit 1 ;;
esac
