#!/bin/sh
# Chronary agent bootstrap — shell fallback for environments without Node.
# Mirrors `npx @chronary/agent-init` (https://www.npmjs.com/package/@chronary/agent-init).
#
# Usage:
#   CHRONARY_EMAIL=you@example.com sh   <  agent-init.sh
#   curl -sSfL https://chronary.ai/agent-init.sh | CHRONARY_EMAIL=you@example.com sh
#
# Environment:
#   CHRONARY_EMAIL        — required
#   CHRONARY_OTP          — optional; if unset and stdin is a TTY, prompts; else exits 2
#   CHRONARY_API          — defaults to https://api.chronary.ai
#   CHRONARY_AGENT_NAME   — defaults to "Bootstrap Agent"
#   CHRONARY_TOS_VERSION  — defaults to whatever GET /v1/auth/terms/current returns
#
# Exit codes:
#   0 ok · 1 API error · 2 bad input · 3 retries exhausted · 4 dependency missing
#
# Hardening notes (#754 Gap 5):
#   - Whole script wrapped in main() called on the last line so a partial
#     download fails before doing anything (curl|sh anti-pattern mitigation).
#   - Does NOT vary content by User-Agent server-side (static file; no UA-based gating).
#   - Reads CHRONARY_OTP only from env. Never accepts secrets via argv.

set -eu

main() {
  : "${CHRONARY_API:=https://api.chronary.ai}"
  : "${CHRONARY_AGENT_NAME:=Bootstrap Agent}"

  if [ -z "${CHRONARY_EMAIL:-}" ]; then
    printf 'agent-init: CHRONARY_EMAIL is required\n' >&2
    exit 2
  fi

  command -v curl >/dev/null 2>&1 || {
    printf 'agent-init: curl is required\n' >&2
    exit 4
  }

  # ── Resolve current ToS version (POSIX-safe; jq optional) ────────────────
  if [ -n "${CHRONARY_TOS_VERSION:-}" ]; then
    tos="${CHRONARY_TOS_VERSION}"
  else
    tos_body=$(curl -sSfL "${CHRONARY_API}/v1/auth/terms/current") || {
      printf 'agent-init: could not fetch /v1/auth/terms/current\n' >&2
      exit 1
    }
    # Parse "version":"..." without depending on jq. The endpoint emits
    # canonical JSON (no whitespace inside the string), so this is safe.
    tos=$(printf '%s' "$tos_body" | sed -n 's/.*"version" *: *"\([^"]*\)".*/\1/p')
    if [ -z "$tos" ]; then
      printf 'agent-init: could not parse ToS version from %s\n' "$tos_body" >&2
      exit 1
    fi
  fi
  printf '==> ToS version: %s\n' "$tos" >&2

  # ── Sign up (single attempt; 429 backoff via -f doesn't help — surface clear error) ──
  signup_payload=$(printf '{"email":"%s","agent_name":"%s","tos_version":"%s"}' \
    "$CHRONARY_EMAIL" "$CHRONARY_AGENT_NAME" "$tos")
  signup_resp=$(curl -sS -X POST "${CHRONARY_API}/v1/agent/sign-up" \
    -H "Content-Type: application/json" \
    -d "$signup_payload" \
    -w '\n%{http_code}')
  signup_status=$(printf '%s' "$signup_resp" | tail -n1)
  signup_body=$(printf '%s' "$signup_resp" | sed '$d')

  if [ "$signup_status" != "200" ]; then
    printf 'agent-init: sign-up failed (HTTP %s): %s\n' "$signup_status" "$signup_body" >&2
    exit 1
  fi

  api_key=$(printf '%s' "$signup_body" | sed -n 's/.*"api_key" *: *"\([^"]*\)".*/\1/p')
  org_id=$(printf '%s' "$signup_body" | sed -n 's/.*"org_id" *: *"\([^"]*\)".*/\1/p')
  if [ -z "$api_key" ] || [ -z "$org_id" ]; then
    printf 'agent-init: sign-up succeeded but returned the opaque (duplicate) shape.\n' >&2
    printf '            The email may already be registered. Reuse the prior API key.\n' >&2
    exit 1
  fi
  printf '==> Org: %s\n' "$org_id" >&2

  # ── OTP (env, else interactive prompt on TTY) ────────────────────────────
  if [ -z "${CHRONARY_OTP:-}" ]; then
    if [ -t 0 ]; then
      printf 'Enter 6-digit OTP from your email: ' >&2
      read -r CHRONARY_OTP
    else
      printf 'agent-init: stdin is not a TTY and CHRONARY_OTP is unset.\n' >&2
      printf '            Re-run with CHRONARY_OTP=<6 digits>.\n' >&2
      exit 2
    fi
  fi
  case "$CHRONARY_OTP" in
    [0-9][0-9][0-9][0-9][0-9][0-9]) ;;
    *) printf 'agent-init: OTP must be exactly 6 digits\n' >&2; exit 2 ;;
  esac

  # ── Verify ───────────────────────────────────────────────────────────────
  verify_resp=$(curl -sS -X POST "${CHRONARY_API}/v1/agent/verify" \
    -H "Authorization: Bearer ${api_key}" \
    -H "Content-Type: application/json" \
    -d "{\"otp\":\"${CHRONARY_OTP}\"}" \
    -w '\n%{http_code}')
  verify_status=$(printf '%s' "$verify_resp" | tail -n1)
  if [ "$verify_status" != "200" ]; then
    verify_body=$(printf '%s' "$verify_resp" | sed '$d')
    printf 'agent-init: verify failed (HTTP %s): %s\n' "$verify_status" "$verify_body" >&2
    exit 1
  fi
  printf '==> Verified.\n' >&2

  # ── Smoke calendar ───────────────────────────────────────────────────────
  cal_resp=$(curl -sS -X POST "${CHRONARY_API}/v1/calendars" \
    -H "Authorization: Bearer ${api_key}" \
    -H "Content-Type: application/json" \
    -d '{"name":"Welcome to Chronary","timezone":"UTC"}' \
    -w '\n%{http_code}')
  cal_status=$(printf '%s' "$cal_resp" | tail -n1)
  if [ "$cal_status" != "201" ]; then
    cal_body=$(printf '%s' "$cal_resp" | sed '$d')
    printf 'agent-init: create calendar failed (HTTP %s): %s\n' "$cal_status" "$cal_body" >&2
    exit 1
  fi
  cal_body=$(printf '%s' "$cal_resp" | sed '$d')
  cal_id=$(printf '%s' "$cal_body" | sed -n 's/.*"id" *: *"\([^"]*\)".*/\1/p')
  printf '==> Created calendar %s.\n' "$cal_id" >&2

  printf '\nDone. Export your key:\n  export CHRONARY_API_KEY=%s\n' "$api_key" >&2
  # Last stdout line is machine-readable so callers can:
  #   API_KEY=$(curl -sSfL https://chronary.ai/agent-init.sh | CHRONARY_EMAIL=... sh)
  printf '%s\n' "$api_key"
}

main "$@"
