#!/usr/bin/env bash
# P0 煙測：login → me → settings → usage → accounts
set -euo pipefail
BASE="${API_BASE:-http://127.0.0.1:8888}"
EMAIL="${SMOKE_EMAIL:-admin@haixun.local}"
PASS="${SMOKE_PASSWORD:-Admin123!@#x}"

ok() { printf '[ok] %s\n' "$*"; }
fail() { printf '[FAIL] %s\n' "$*" >&2; exit 1; }

json_field() {
  python3 -c "import sys,json; d=json.load(sys.stdin); print(d$1)" 2>/dev/null || true
}

echo "=== smoke P0 against $BASE ==="

login=$(curl -sf -X POST "$BASE/api/v1/auth/login" \
  -H 'Content-Type: application/json' \
  -d "{\"email\":\"$EMAIL\",\"password\":\"$PASS\"}" ) || fail "AU-01 login"
code=$(echo "$login" | python3 -c "import sys,json; print(json.load(sys.stdin).get('code'))")
[[ "$code" == "102000" ]] || fail "login code=$code"
TOKEN=$(echo "$login" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['tokens']['access_token'])")
ok "AU-01 login"

me=$(curl -sf "$BASE/api/v1/auth/me" -H "Authorization: Bearer $TOKEN") || fail "me"
code=$(echo "$me" | python3 -c "import sys,json; print(json.load(sys.stdin).get('code'))")
[[ "$code" == "102000" ]] || fail "me code=$code"
ok "AU-me / A-06 envelope"

ai=$(curl -sf "$BASE/api/v1/settings/ai" -H "Authorization: Bearer $TOKEN") || fail "settings ai"
code=$(echo "$ai" | python3 -c "import sys,json; print(json.load(sys.stdin).get('code'))")
[[ "$code" == "102000" ]] || fail "settings code=$code"
ok "ST-01 settings"

us=$(curl -sf "$BASE/api/v1/usage/summary" -H "Authorization: Bearer $TOKEN") || fail "usage"
code=$(echo "$us" | python3 -c "import sys,json; print(json.load(sys.stdin).get('code'))")
[[ "$code" == "102000" ]] || fail "usage code=$code"
ok "USG summary"

acc=$(curl -sf "$BASE/api/v1/threads-accounts" -H "Authorization: Bearer $TOKEN") || fail "accounts"
code=$(echo "$acc" | python3 -c "import sys,json; print(json.load(sys.stdin).get('code'))")
[[ "$code" == "102000" ]] || fail "accounts code=$code"
ok "TH-05 list accounts"

echo "=== smoke P0 passed ==="
