#!/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`)
#   CHRONARY_HEARD_ABOUT  — optional: how you found Chronary, plain text up to 200
#                           characters (like `--heard-about`). Email sign-up only.
#
# 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

# The inside of a JSON string for stdin (#2868): backslash and double quote
# escaped, a newline as \n, any other control character and DEL as \u00XX.
# Feed it the value plus ONE trailing newline (`printf '%s\n' "$v" | json_str`):
# awk consumes that terminator, so a value that itself ends in newlines keeps
# them. Every free-text value in a request body goes through this, so no
# input can end the string or add a field; the OTP is the one exception, and
# it is checked as exactly 6 digits before the verify body is built.
# LC_ALL=C: byte by byte in any locale (UTF-8 passes through unchanged).
json_str() {
  LC_ALL=C awk 'BEGIN { for (i = 1; i < 32; i++) ctl[sprintf("%c", i)] = i; ctl[sprintf("%c", 127)] = 127 }
  {
    if (NR > 1) printf "\\n"
    out = ""; len = length($0)
    for (i = 1; i <= len; i++) {
      c = substr($0, i, 1)
      if (c == "\\") out = out "\\\\"
      else if (c == "\"") out = out "\\\""
      else if (c in ctl) out = out sprintf("\\u%04x", ctl[c])
      else out = out c
    }
    printf "%s", out
  }'
}

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
  }
  # json_str builds every request body (#2868). A missing awk inside a command
  # substitution would not stop `set -e`, and the script would send empty fields.
  command -v awk >/dev/null 2>&1 || {
    printf 'agent-init: awk 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

  # First $1 UTF-8 characters of stdin (one line), counted byte by byte so it
  # works the same in any awk and locale and never splits a character.
  cut_chars() {
    LC_ALL=C awk -v max="$1" '{
      out = ""; n = 0; i = 1; len = length($0)
      while (i <= len && n < max) {
        c = substr($0, i, 1); w = 1
        if (c >= "\300" && c < "\340") w = 2
        else if (c >= "\340" && c < "\360") w = 3
        else if (c >= "\360" && c < "\370") w = 4
        out = out substr($0, i, w); i += w; n++
      }
      printf "%s", out
    }'
  }

  # ── 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"' \
    "$(printf '%s\n' "$CHRONARY_EMAIL" | json_str)" \
    "$(printf '%s\n' "$CHRONARY_AGENT_NAME" | json_str)" \
    "$(printf '%s\n' "$tos" | json_str)")
  # Optional free text (#2651): whitespace folded and control characters
  # dropped, then escaped by json_str, so any text stays one JSON string.
  if [ -n "${CHRONARY_HEARD_ABOUT:-}" ]; then
    # Informational: cut to 200 characters first (the API keeps no more), so
    # a long answer never costs the sign-up.
    heard_about=$(printf '%s' "$CHRONARY_HEARD_ABOUT" | tr '\t\n\r' '   ' | tr -d '\000-\037\177' | cut_chars 200 | json_str)
    if [ -n "$heard_about" ]; then
      signup_payload=$(printf '%s,"heard_about":"%s"' "$signup_payload" "$heard_about")
    fi
  fi
  signup_payload="${signup_payload}}"
  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 '            This email already has an organization; its key is never shown again.\n' >&2
    printf '            Not verified yet: a new code was emailed. Finish with the key from the\n' >&2
    printf '            first run: CHRONARY_API_KEY=<key> CHRONARY_OTP=<new code> npx @chronary/agent-init --verify-only\n' >&2
    exit 1
  fi
  printf '==> Org: %s\n' "$org_id" >&2

  # The org exists now and this response is its only copy of the key: a
  # re-run for the same unverified email rotates the OTP and returns no key.
  # Print it before the OTP read, verify or calendar can fail (#2518).
  printf '\nExport your key (shown only once):\n  export CHRONARY_API_KEY=%s\n\n' "$api_key" >&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
      resume_hint
      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; resume_hint; 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
    resume_hint
    exit 1
  fi
  printf '==> Verified.\n' >&2

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

  smoke_calendar "$api_key" || {
    printf '            The sign-up and verify worked: the key above is valid. Create a\n' >&2
    printf '            calendar yourself with POST /v1/calendars.\n' >&2
    exit 1
  }

  printf '\nDone.\n' >&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
}

# ── How to finish an email sign-up that stopped after the key was shown ───
resume_hint() {
  printf '            The sign-up worked and the key above is valid; keep it (a re-run for\n' >&2
  printf '            this email never shows it again). Finish with the code from your\n' >&2
  printf '            email (valid for 60 minutes):\n' >&2
  printf '              CHRONARY_API_KEY=<key above> CHRONARY_OTP=<6 digits> npx @chronary/agent-init --verify-only\n' >&2
  printf '            or POST %s/v1/agent/verify with that key and {"otp":"<6 digits>"}.\n' "$CHRONARY_API" >&2
  printf '            If the code expired or too many tries used it up, re-run this script\n' >&2
  printf '            with the same email for a new code (the key stays valid), then verify.\n' >&2
}

# ── 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"}' \
      "$(printf '%s\n' "$CHRONARY_AGENT_NAME" | json_str)" "$(printf '%s\n' "$tos" | json_str)")
    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 "$@"
