#!/usr/bin/env bash
set -euo pipefail

BASE_URL="${1:-http://localhost:8080}"

pass=0
fail=0

check() {
  local name="$1" body="$2"

  printf "%-40s " "$name"
  code=$(curl -s --max-time 60 -o /tmp/api_lite_response.json -w '%{http_code}' \
    -X POST "$BASE_URL/eval" \
    -H "Content-Type: application/json" \
    -d "$body")

  if [ "$code" -eq 200 ]; then
    echo "PASS (HTTP $code)"
    ((++pass))
  else
    echo "FAIL (expected HTTP 200, got $code)"
    cat /tmp/api_lite_response.json
    echo
    ((++fail))
  fi
}

# Verify no errors in the IU Result JSON
check_ok() {
  local name="$1" body="$2"

  printf "%-40s running..." "$name"
  code=$(curl -s --max-time 60 -o /tmp/api_lite_response.json -w '%{http_code}' \
    -X POST "$BASE_URL/eval" \
    -H "Content-Type: application/json" \
    -d "$body")

  errors=$(python3 -c "import json; d=json.load(open('/tmp/api_lite_response.json')); print(len(d.get('errors',[])))")

  if [ "$code" -eq 200 ] && [ "$errors" -eq 0 ]; then
    printf "\r%-40s PASS (HTTP %s)\n" "$name" "$code"
    ((++pass))
  else
    printf "\r%-40s FAIL (HTTP %s, errors=%s)\n" "$name" "$code" "$errors"
    cat /tmp/api_lite_response.json
    echo
    ((++fail))
  fi
}

echo "Testing codelogician-lite (IU reasoner) at $BASE_URL"
echo "(each request may take up to 60s as it runs a subprocess)"
echo "==="

# Single IML fixture covering: type-check, verify goal, decomp annotation
IML='let double (x: int) : int = x * 2

let simple_branch (x: int) : int =
  if x > 0 then x + 1 else x - 1
[@@decomp top ()]

verify (fun x -> x > 0 ==> double x > x)'

mk_payload() {
  jq -n --arg cmd "$1" --arg body "$IML" '{input: ({command: $cmd, body: $body} | tojson)}'
}

echo

echo
echo "--- eval commands ---"
check_ok "eval --help"                  '{"input": "{\"command\": \"eval --help\"}"}'
check_ok "eval check"                   "$(mk_payload 'eval check')"
check_ok "eval list-vg"                 "$(mk_payload 'eval list-vg')"
check_ok "eval check-vg"                "$(mk_payload 'eval check-vg')"
check_ok "eval list-decomp"             "$(mk_payload 'eval list-decomp')"
check_ok "eval check-decomp"            "$(mk_payload 'eval check-decomp')"
check_ok "eval gen-test"                "$(mk_payload 'eval gen-test -f simple_branch -l python')"

echo
echo "--- doc commands ---"
check_ok "doc --help"                   '{"input": "{\"command\": \"doc --help\"}"}'
check_ok "doc contents"                 '{"input": "{\"command\": \"doc contents\"}"}'
check_ok "doc ref summary"              '{"input": "{\"command\": \"doc ref summary\"}"}'
check_ok "doc ref view int"             '{"input": "{\"command\": \"doc ref view int\"}"}'
check_ok "doc search verification"      '{"input": "{\"command\": \"doc search verification\"}"}'
check_ok "doc view errors"              '{"input": "{\"command\": \"doc view errors\"}"}'

echo
echo "==="
echo "$pass passed, $fail failed"
[ "$fail" -eq 0 ]
