#!/bin/sh
# PosiChat CLI — 3-minute positive check-in. Not therapy.
# Install: curl -fsSL https://posichat.app/cli -o posichat && chmod +x posichat
# Usage:   posichat start | posichat say "text" | posichat done [mood]
set -eu
BASE="${POSICHAT_BASE:-https://posichat.app/v1}"
FILE="${POSICHAT_SESSION:-$HOME/.posichat_session}"
CLIENT_FILE="${POSICHAT_CLIENT:-$HOME/.posichat_client}"
cmd="${1:-}"

if [ ! -f "$CLIENT_FILE" ]; then
  if command -v uuidgen >/dev/null 2>&1; then
    uuidgen | tr -d '\n' > "$CLIENT_FILE"
  else
    echo "cli-$(date +%s)-$$" > "$CLIENT_FILE"
  fi
fi
CLIENT=$(cat "$CLIENT_FILE")

json_escape() {
  printf '%s' "$1" | awk '
    BEGIN { ORS="" }
    {
      gsub(/\\/, "\\\\")
      gsub(/"/, "\\"")
      gsub(/\t/, "\\t")
      gsub(/\r/, "\\r")
      print
    }'
}

api() {
  method="$1"
  path="$2"
  body="${3:-}"
  if [ -n "$body" ]; then
    curl -sS -X "$method" "$BASE$path" \
      -H "Content-Type: application/json" \
      -H "X-PosiChat-Client: $CLIENT" \
      -d "$body"
  else
    curl -sS -X "$method" "$BASE$path" \
      -H "X-PosiChat-Client: $CLIENT"
  fi
}

extract_id() {
  printf '%s' "$1" | sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1
}

if [ -z "$cmd" ]; then
  _n=$(basename "$0")
  if [ "$_n" = "sh" ] || [ "$_n" = "bash" ] || [ "$_n" = "dash" ]; then
    cmd="install"
  fi
fi

case "$cmd" in
  install)
    dest="${HOME}/.local/bin"
    mkdir -p "$dest"
    curl -fsSL https://posichat.app/cli > "$dest/posichat"
    chmod +x "$dest/posichat"
    echo "Installed $dest/posichat"
    echo "Add to PATH: export PATH="$dest:$PATH""
    echo "Then: posichat start"
    echo "Not therapy. Not a diagnosis. Crisis: 988"
    ;;
  start)
    res=$(api POST /checkins "{}")
    printf '%s\n' "$res"
    id=$(extract_id "$res")
    if [ -n "$id" ]; then
      printf '%s\n' "$id" > "$FILE"
    fi
    ;;
  say)
    shift
    text="$*"
    if [ ! -f "$FILE" ]; then
      echo "No session. Run: posichat start" >&2
      exit 1
    fi
    id=$(cat "$FILE")
    esc=$(json_escape "$text")
    api POST "/checkins/$id/turns" "{\"text\":\"$esc\"}"
    printf '\n'
    ;;
  done)
    mood="${2:-}"
    if [ ! -f "$FILE" ]; then
      echo "No session. Run: posichat start" >&2
      exit 1
    fi
    id=$(cat "$FILE")
    if [ -n "$mood" ]; then
      api POST "/checkins/$id/complete" "{\"mood\":$mood}"
    else
      api POST "/checkins/$id/complete" "{}"
    fi
    printf '\n'
    ;;
  *)
    echo "Usage: posichat start | say <text> | done [mood 1-5] | install"
    echo "A 3-minute positive check-in. Not therapy. https://posichat.app"
    exit 1
    ;;
esac
