#!/bin/bash

ENDPOINT="https://projectlando.net/genie/fitment/fitment_check.php?debug=1"

PRODUCT_IDS=(
  8339516915955
  8340087177459
  8382847287539
  9052351496435
  9081652445427
)

FAIL=0

for PID in "${PRODUCT_IDS[@]}"; do
  echo "----------------------------------------"
  echo "Testing Product ID: $PID"

  RESPONSE=$(curl -s -X POST "$ENDPOINT" \
    -H "Content-Type: application/json" \
    -d "{
      \"product_id\": $PID,
      \"vehicle\": {
        \"year\": 2020,
        \"make\": \"Ford\",
        \"model\": \"Mustang\"
      }
    }")

  if [ -z "$RESPONSE" ]; then
    echo "Curl failed or empty response."
    FAIL=1
    continue
  fi

  STATUS=$(echo "$RESPONSE" | jq -r '.status')
  DET_CONF=$(echo "$RESPONSE" | jq -r '.deterministic_confidence')
  FINAL_CONF=$(echo "$RESPONSE" | jq -r '.final_confidence')
  LLM_USED=$(echo "$RESPONSE" | jq -r '.llm.used')
  HEALTH_STATUS=$(echo "$RESPONSE" | jq -r '.llm.llm_health.status')
  HTTP_CODE=$(echo "$RESPONSE" | jq -r '.llm.llm_health.http_code')
  TOKENS=$(echo "$RESPONSE" | jq -r '.llm.usage.tokens_total')

  echo "status: $STATUS"
  echo "deterministic_confidence: $DET_CONF"
  echo "final_confidence: $FINAL_CONF"
  echo "llm_used: $LLM_USED"
  echo "llm_health_status: $HEALTH_STATUS"
  echo "http_code: $HTTP_CODE"
  echo "tokens_total: $TOKENS"

  if [[ "$HEALTH_STATUS" == "degraded_credit" || "$HEALTH_STATUS" == "degraded_transport" ]]; then
    echo "LLM HEALTH FAILURE DETECTED"
    FAIL=1
  fi
done

echo "----------------------------------------"

if [ $FAIL -ne 0 ]; then
  echo "One or more LLM health failures detected."
  exit 1
else
  echo "All products passed LLM health checks."
  exit 0
fi
