#!/usr/bin/env bash
# Quickstart step 6 — start a training run and follow it to an evaluated model.
#
# The normal invocation is just:
#   POST /runs {"dataset_id": "...", "model_config_tier": "S"}
# This executable copy layers on ci-train-profile.json — the documented CI
# override profile (reduced dims, <= 50 steps, CPU) — so the docs pipeline
# really trains this model on every change.
set -euo pipefail

: "${TESSERA_API_BASE:?e.g. https://api.staging.tessera.zone/v1}"
: "${TESSERA_API_KEY:?your tsk_test_… key}"
: "${TESSERA_STATE_DIR:=.}"
AUTH=(-H "Authorization: Bearer $TESSERA_API_KEY")
DATASET_ID="$(cat "$TESSERA_STATE_DIR/dataset_id")"

BODY="$(python3 -c '
import json, sys
profile = json.load(open("ci-train-profile.json"))
profile.pop("_comment", None)
profile["dataset_id"] = sys.argv[1]
print(json.dumps(profile))
' "$DATASET_ID")"

RUN="$(curl -sS -X POST "$TESSERA_API_BASE/runs" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quickstart-train" \
  -d "$BODY")"
RUN_ID="$(printf '%s' "$RUN" | python3 -c 'import json,sys; print(json.load(sys.stdin)["run_id"])')"
echo "run $RUN_ID started"

for _ in $(seq 1 600); do
  RUN="$(curl -sS "$TESSERA_API_BASE/runs/$RUN_ID" "${AUTH[@]}")"
  STATUS="$(printf '%s' "$RUN" | python3 -c 'import json,sys; print(json.load(sys.stdin)["status"])')"
  case "$STATUS" in succeeded|failed|cancelled) break ;; esac
  sleep 2
done
printf '%s' "$RUN" | python3 -c '
import json, sys
run = json.load(sys.stdin)
print(json.dumps({k: run.get(k) for k in ("run_id", "status", "total_steps", "model_id")}, indent=2))
'
MODEL_ID="$(printf '%s' "$RUN" | python3 -c 'import json,sys; print(json.load(sys.stdin)["model_id"])')"

# Evaluation runs automatically after training: the model version moves to
# `evaluated` once the six promotion gates (G1-G6) have been computed.
for _ in $(seq 1 600); do
  MODEL="$(curl -sS "$TESSERA_API_BASE/models/$MODEL_ID" "${AUTH[@]}")"
  MODEL_STATUS="$(printf '%s' "$MODEL" | python3 -c 'import json,sys; print(json.load(sys.stdin)["status"])')"
  case "$MODEL_STATUS" in evaluated|promoted|archived) break ;; esac
  sleep 2
done
echo "model $MODEL_ID: $MODEL_STATUS"

curl -sS "$TESSERA_API_BASE/models/$MODEL_ID/eval-report" "${AUTH[@]}" | python3 -c '
import json, sys
report = json.load(sys.stdin)
for gate in sorted(report["gates"]):
    print("gate %s: %s" % (gate, report["gates"][gate]["status"]))
'
printf '%s' "$MODEL_ID" > "$TESSERA_STATE_DIR/model_id"
