#!/usr/bin/env bash
# adom-mouser LIVE smoke — burns ~2 Mouser API calls.
#
# Runs ONCE per day (daily cron). Verifies that an actual upstream
# search returns real data. If today's quota is already gone, we exit
# 0 with a "skipped" status (not a failure — it's just business).
#
# Usage:
#   tests/smoke-live.sh                              # deployed backend
#   tests/smoke-live.sh http://127.0.0.1:8775        # local

set -u
BACKEND="${1:-${MOUSER_API:-https://mouser-xr8t4f5d01bt.adom.cloud}}"
BACKEND="${BACKEND%/}"

if [ -t 1 ]; then
  C_OK=$'\033[32m'; C_FAIL=$'\033[31m'; C_SKIP=$'\033[33m'; C_DIM=$'\033[2m'; C_BOLD=$'\033[1m'; C_RESET=$'\033[0m'
else C_OK=''; C_FAIL=''; C_SKIP=''; C_DIM=''; C_BOLD=''; C_RESET=''; fi

pass=0; fail=0; failures=()

echo "${C_BOLD}adom-mouser LIVE smoke${C_RESET}  ${C_DIM}$BACKEND${C_RESET}"
echo "${C_DIM}────────────────────────────────────────────────────────${C_RESET}"

# Step 0 — cheap /health (no live ping), check today's quota state.
health=$(curl -sS --max-time 10 "$BACKEND/health" 2>/dev/null)
quota_hit=$(printf '%s' "$health" | jq -r '.quota.first_quota_hit_ts // 0')
if [ "$quota_hit" != "0" ] && [ "$quota_hit" != "null" ]; then
  searches=$(printf '%s' "$health" | jq -r '.quota.searches // 0')
  echo "${C_SKIP}SKIP${C_RESET}  Mouser daily quota already hit today ($searches searches used)"
  echo "${C_DIM}       exit 0 — skipping live queries until midnight CT reset.${C_RESET}"
  exit 0
fi

run_case() {
  local label="$1" keyword="$2" expect="$3"
  local body resp count match
  body=$(jq -n --arg k "$keyword" '{action:"search", keyword:$k, limit:2}')
  resp=$(curl -sS --max-time 20 -X POST "$BACKEND/search" \
    -H 'content-type: application/json' -d "$body" 2>/dev/null)
  count=$(printf '%s' "$resp" | jq '.count // 0' 2>/dev/null)
  match=$(printf '%s' "$resp" | jq --arg s "$expect" \
    '[.components[]? | (.mpn // .mfr // "") + " " + (.description // "") | ascii_downcase | contains($s | ascii_downcase)] | any' 2>/dev/null)
  if [ "$match" = "true" ] && [ "${count:-0}" -ge 1 ]; then
    pass=$((pass+1)); printf '%sPASS%s  %-28s  count=%s  contains %s\n' "$C_OK" "$C_RESET" "$label" "$count" "$expect"
  else
    fail=$((fail+1)); failures+=("$label — count=$count contains-$expect=$match")
    printf '%sFAIL%s  %-28s  count=%s  contains %s? %s\n' "$C_FAIL" "$C_RESET" "$label" "$count" "$expect" "${match:-null}"
  fi
}

# Frugal: 2 canonical MPNs. Increments the quota tracker by 2.
run_case "stm32f103 (arm mcu)"   "STM32F103RBT6"  "stm32f103"
run_case "lm555 (timer)"         "LM555"          "lm555"

echo "${C_DIM}────────────────────────────────────────────────────────${C_RESET}"
if [ "$fail" -eq 0 ]; then
  echo "${C_OK}${C_BOLD}OK${C_RESET}  $pass live queries passed"
  exit 0
else
  echo "${C_FAIL}${C_BOLD}FAIL${C_RESET}  $pass passed / $fail failed"
  for f in "${failures[@]}"; do echo "      - $f"; done
  exit 1
fi