#!/usr/bin/env bash
# End to end checks for this kit. Exit non-zero when a check fails.
# Run from the kit directory after `make deploy` (reads build/config.json).
set -euo pipefail
cd "$(dirname "$0")/.."

CFG=build/config.json
[ -f "$CFG" ] || { echo "FAIL: $CFG not found. Run make deploy first."; exit 1; }
[ -d poc/node_modules ] || { echo "FAIL: poc/node_modules not found. Run make deps first."; exit 1; }
api_url=$(jq -r .api_url.value "$CFG")
function_name=$(jq -r .function_name.value "$CFG")
prompt="Write a Python function that returns the nth Fibonacci number iteratively, with a docstring."
work=build/verify
mkdir -p "$work"

echo "== 1. The API rejects a request with no token"
status=$(curl -s -o /dev/null -w '%{http_code}' -X POST "$api_url" -H 'Content-Type: application/json' -d '{"prompt":"hi"}')
[ "$status" = "401" ] || { echo "FAIL: expected 401, got $status"; exit 1; }
echo "ok: 401"

echo "== 2. Direct Bedrock ConverseStream call to Ergo with local credentials"
(cd poc && PROMPT="$prompt" node --input-type=module -e '
import { chat } from "./lambda/index.mjs";
let text = "";
const done = await chat({ prompt: process.env.PROMPT, effort: "low" }, (e) => { if (e.type === "text") text += e.text; });
if (!text.trim() || !done.usage.output_tokens) { console.error("FAIL: no text or no usage"); process.exit(1); }
console.log(`ok: ${text.length} characters, ${done.usage.input_tokens} tokens in, ${done.usage.output_tokens} tokens out`);
console.log(`ok: first token ${done.metrics.ttft_ms} ms, total ${done.metrics.total_ms} ms, ${done.metrics.tokens_per_second} output tokens per second`);
// Ergo always reasons: an effort of "none" must be rejected, which also proves the effort field reaches the model.
try {
  await chat({ prompt: "hi", effort: "none" }, () => {});
  console.error("FAIL: effort none was accepted, so the effort setting is not reaching the model");
  process.exit(1);
} catch (err) {
  if (err.name !== "ValidationException") throw err;
  console.log("ok: effort none is rejected by Bedrock");
}
')

echo "== 3. The Lambda, invoked directly, returns a streamed answer with usage"
jq -n --arg p "$prompt" '{body: ({prompt: $p, effort: "low"} | tojson)}' > "$work/event.json"
aws lambda invoke --function-name "$function_name" --cli-binary-format raw-in-base64-out \
  --payload "file://$work/event.json" "$work/out" > "$work/invoke.json"
if jq -e .FunctionError "$work/invoke.json" > /dev/null; then echo "FAIL: function error"; head -c 600 "$work/out"; exit 1; fi
# A buffered invoke returns the response metadata, eight NUL bytes, then the event lines.
perl -0777 -pe 's/^.*?\x00{8}//s' "$work/out" > "$work/events.ndjson"
done_event=$(grep '"type":"done"' "$work/events.ndjson" | tail -1 || true)
[ -n "$done_event" ] || { echo "FAIL: no done event"; head -c 600 "$work/out"; exit 1; }
grep -q '"type":"text"' "$work/events.ndjson" || { echo "FAIL: no text events"; exit 1; }
[ "$(echo "$done_event" | jq .usage.output_tokens)" -gt 0 ] || { echo "FAIL: no output tokens"; exit 1; }
echo "ok: $(grep -c '"type":"text"' "$work/events.ndjson") text events, $(echo "$done_event" | jq -r '"\(.usage.input_tokens) tokens in, \(.usage.output_tokens) tokens out"')"
echo "ok: $(echo "$done_event" | jq -r '"first token \(.metrics.ttft_ms) ms, total \(.metrics.total_ms) ms, \(.metrics.tokens_per_second) output tokens per second"')"

echo "verify passed"
