#!/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
#   curl -sSfL https://chronary.ai/agent-init.sh | CHRONARY_ANONYMOUS=1 sh
#
# Environment:
#   CHRONARY_EMAIL        — required unless CHRONARY_ANONYMOUS=1
#   CHRONARY_OTP          — optional; if unset and stdin is a TTY, prompts; else exits 2
#   CHRONARY_ANONYMOUS    — 1 (or true): sign up with no email (#2335). The key works
#                           at once at Sandbox limits; give the printed claim link to the
#                           person who should own the calendar. Unclaimed, the key stops
#                           and everything is deleted after 72 hours.
#   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.
#                           A version set here is never swapped for another: if it
#                           is out of date the script stops and names the current one.
#   CHRONARY_JSON         — 1 (or true): print one JSON line on stdout instead of the
#                           bare key (like `npx @chronary/agent-init --json`)
#
# Signing up accepts the Terms of Service (https://chronary.ai/terms) for the
# person or organization you act for.
#
# 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}"

  anonymous=0
  case "${CHRONARY_ANONYMOUS:-}" in
    1|true|TRUE|True) anonymous=1 ;;
  esac
  json=0
  case "${CHRONARY_JSON:-}" in
    1|true|TRUE|True) json=1 ;;
  esac

  if [ "$anonymous" = "1" ]; then
    if [ -n "${CHRONARY_EMAIL:-}" ] || [ -n "${CHRONARY_OTP:-}" ]; then
      printf 'agent-init: CHRONARY_ANONYMOUS signs up without an email; unset CHRONARY_EMAIL / CHRONARY_OTP.\n' >&2
      exit 2
    fi
  elif [ -z "${CHRONARY_EMAIL:-}" ]; then
    printf 'agent-init: CHRONARY_EMAIL is required (or CHRONARY_ANONYMOUS=1 to sign up without one)\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) ────────────────
  tos_pinned=0
  if [ -n "${CHRONARY_TOS_VERSION:-}" ]; then
    tos="${CHRONARY_TOS_VERSION}"
    tos_pinned=1
  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

  if [ "$anonymous" = "1" ]; then
    anonymous_signup "$tos"
    return
  fi

  # ── 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

  agent_id=$(printf '%s' "$signup_body" | sed -n 's/.*"agent_id" *: *"\([^"]*\)".*/\1/p')

  smoke_calendar "$api_key" || exit 1

  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)
  if [ "$json" = "1" ]; then
    printf '{"api_key":"%s","org_id":"%s","agent_id":"%s","calendar_id":"%s"}\n' \
      "$api_key" "$org_id" "$agent_id" "$cal_id"
  else
    printf '%s\n' "$api_key"
  fi
}

# ── Smoke calendar (proves the key can write) ─────────────────────────────
# Sets cal_id; returns 1 (after printing why) when the calendar was not
# created, and leaves the decision to exit to the caller.
smoke_calendar() {
  cal_id=''
  cal_resp=$(curl -sS -X POST "${CHRONARY_API}/v1/calendars" \
    -H "Authorization: Bearer $1" \
    -H "Content-Type: application/json" \
    -d '{"name":"Welcome to Chronary","timezone":"UTC"}' \
    -w '\n%{http_code}') || {
    printf 'agent-init: create calendar failed: could not reach the API\n' >&2
    return 1
  }
  cal_status=$(printf '%s' "$cal_resp" | tail -n1)
  cal_body=$(printf '%s' "$cal_resp" | sed '$d')
  if [ "$cal_status" != "201" ]; then
    printf 'agent-init: create calendar failed (HTTP %s): %s\n' "$cal_status" "$cal_body" >&2
    return 1
  fi
  cal_id=$(printf '%s' "$cal_body" | sed -n 's/.*"id" *: *"\([^"]*\)".*/\1/p')
  printf '==> Created calendar %s.\n' "$cal_id" >&2
}

# ── No-email sign-up (#2335): a claimable organization ────────────────────
anonymous_signup() {
  tos="$1"
  attempt=0
  while :; do
    anon_payload=$(printf '{"agent_name":"%s","tos_version":"%s"}' "$CHRONARY_AGENT_NAME" "$tos")
    anon_resp=$(curl -sS -X POST "${CHRONARY_API}/v1/agent/sign-up/anonymous" \
      -H "Content-Type: application/json" \
      -d "$anon_payload" \
      -w '\n%{http_code}')
    anon_status=$(printf '%s' "$anon_resp" | tail -n1)
    anon_body=$(printf '%s' "$anon_resp" | sed '$d')
    # The Terms moved between the two calls: retry once with current_version,
    # but only for a version read from the API. A version the caller set in
    # CHRONARY_TOS_VERSION is never swapped for another one.
    if [ "$anon_status" = "409" ]; then
      current=$(printf '%s' "$anon_body" | sed -n 's/.*"current_version" *: *"\([^"]*\)".*/\1/p')
      if [ "$tos_pinned" = "1" ]; then
        printf 'agent-init: the Terms version you pinned (%s) is out of date; the current version is %s.\n' "$tos" "${current:-unknown}" >&2
        printf '            Read https://chronary.ai/terms and set CHRONARY_TOS_VERSION=%s to accept it, or unset it.\n' "${current:-<current>}" >&2
        exit 1
      fi
      if [ "$attempt" = "0" ] && [ -n "$current" ] && [ "$current" != "$tos" ]; then
        printf '==> ToS moved to %s; retrying with it.\n' "$current" >&2
        tos="$current"
        attempt=1
        continue
      fi
    fi
    break
  done

  if [ "$anon_status" != "201" ]; then
    case "$anon_body" in
      *anonymous_signup_disabled*)
        printf 'agent-init: sign-up without an email is not available on this API; use CHRONARY_EMAIL instead.\n' >&2 ;;
      *)
        printf 'agent-init: sign-up failed (HTTP %s): %s\n' "$anon_status" "$anon_body" >&2 ;;
    esac
    exit 1
  fi

  api_key=$(printf '%s' "$anon_body" | sed -n 's/.*"api_key" *: *"\([^"]*\)".*/\1/p')
  org_id=$(printf '%s' "$anon_body" | sed -n 's/.*"org_id" *: *"\([^"]*\)".*/\1/p')
  agent_id=$(printf '%s' "$anon_body" | sed -n 's/.*"agent_id" *: *"\([^"]*\)".*/\1/p')
  claim_url=$(printf '%s' "$anon_body" | sed -n 's/.*"claim_url" *: *"\([^"]*\)".*/\1/p')
  expires_at=$(printf '%s' "$anon_body" | sed -n 's/.*"expires_at" *: *"\([^"]*\)".*/\1/p')
  if [ -z "$api_key" ] || [ -z "$claim_url" ] || [ -z "$expires_at" ]; then
    printf 'agent-init: sign-up answered 201 without the key, claim link and expiry.\n' >&2
    exit 1
  fi
  printf '==> Org: %s\n' "$org_id" >&2

  # The org exists now and its key and claim link are shown only in this
  # response: print them before anything else can fail.
  printf '\nThis calendar has no owner yet.\n\n' >&2
  printf 'Claim link: give it to the person who should own this calendar. It works once;\n' >&2
  printf 'opening it while signed in to the Chronary console moves the agent, calendar and\n' >&2
  printf 'events into their account, and this key then stops working.\n  %s\n\n' "$claim_url" >&2
  printf 'Expires: %s (72 hours after sign-up). Unclaimed, the key stops working then\n' "$expires_at" >&2
  printf 'and the calendar and its events are deleted.\n\n' >&2
  printf 'Export your key:\n  export CHRONARY_API_KEY=%s\n\n' "$api_key" >&2

  # The smoke calendar is a convenience here: a failure is a warning.
  if ! smoke_calendar "$api_key"; then
    printf 'agent-init: warning: the sign-up worked; the key and claim link above are valid.\n' >&2
    printf '            Create a calendar with POST /v1/agents/%s/calendars.\n' "$agent_id" >&2
  fi

  if [ "$json" = "1" ]; then
    if [ -n "$cal_id" ]; then cal_json="\"$cal_id\""; else cal_json=null; fi
    printf '{"api_key":"%s","org_id":"%s","agent_id":"%s","calendar_id":%s,"claim_url":"%s","expires_at":"%s"}\n' \
      "$api_key" "$org_id" "$agent_id" "$cal_json" "$claim_url" "$expires_at"
    return
  fi
  printf '%s\n' "$api_key"
}

main "$@"
