#!/usr/bin/env bash

set -u

URL="https://projectlando.net/genie/fitment/fitment_check.php"
show_json=false

if [ "${1:-}" = "--show-json" ] || [ "${1:-}" = "-j" ]; then
  show_json=true
elif [ -n "${1:-}" ]; then
  echo "Usage: $0 [--show-json|-j]"
  exit 1
fi

PRODUCT_IDS=(
  "8339516915955"
  "8340087177459"
  "8382847287539"
  "9052351496435"
  "9081652445427"
)

passed=0
failed=0
does_not_fit_count=0

if ! command -v curl >/dev/null 2>&1; then
  echo "Error: curl is required but not installed."
  exit 1
fi

if ! command -v jq >/dev/null 2>&1; then
  echo "Error: jq is required but not installed."
  exit 1
fi

for product_id in "${PRODUCT_IDS[@]}"; do
  request_body=$(jq -n \
    --argjson product_id "$product_id" \
    '{
      product_id: $product_id,
      vehicle: {
        year: 2020,
        make: "Ford",
        model: "Mustang"
      }
    }')

  response=$(curl -s -X POST "$URL" \
    -H "Content-Type: application/json" \
    -d "$request_body")

  is_pass=false
  if printf '%s' "$response" | jq -e '
      (.status == "unknown" or .status == "does_not_fit") and
      .llm_used == true and
      (.llm | type) == "object" and
      .llm.used == true and
      (.llm.raw_text != null) and
      ((.llm.parsed // {}) | type) == "object" and
      .deterministic_confidence == 0 and
      .confidence_band == "low" and
      (.explanation | type) == "object" and
      ((.explanation.summary // null) != null) and
      ((.explanation.compatibility_factors // []) | type) == "array" and
      ((.explanation.mechanical_differences // []) | type) == "array" and
      ((.llm.raw_text | test("\\n"; "m")) | not) and
      ((tostring | test("<"; "i")) | not)
    ' >/dev/null 2>&1; then
    if printf '%s' "$response" | jq -e '.status == "does_not_fit"' >/dev/null 2>&1; then
      does_not_fit_count=$((does_not_fit_count + 1))
    fi
    is_pass=true
    echo "✅ PASS - $product_id"
    passed=$((passed + 1))
  else
    echo "❌ FAIL - $product_id"
    failed=$((failed + 1))
  fi

  if [ "$show_json" = true ] || [ "$is_pass" = false ]; then
    printf '%s\n' "$response" | jq . 2>/dev/null || printf '%s\n' "$response"
  fi
done

echo
echo "Total Passed: $passed"
echo "Total Failed: $failed"
echo "Total does_not_fit: $does_not_fit_count"

if [ "$does_not_fit_count" -eq 0 ]; then
  echo "❌ FAIL - expected at least one does_not_fit result"
  exit 1
fi

if [ "$failed" -gt 0 ]; then
  exit 1
fi

exit 0
