#!/usr/bin/env bash
# Phase 5: 3003 Playground Specific Test
# Tests the 3 problematic endpoints on the local dev environment.
# Base: http://localhost:3003

BASE="http://localhost:3003"
API_KEY="muser_demo_key_32chars_abcdef1234567890"
FILE_UUID="a6fb22eebefaef17e62af874997c5944"
IDENTITY_UUID="89cbaa58-a48b-4ee8-8171-df87c54da881"

PASS=0
FAIL=0
TOTAL=0

echo "============================================"
echo " Phase 5: 3003 Playground Specific Test"
echo " Base:    $BASE"
echo " File:    $FILE_UUID"
echo " Identity: $IDENTITY_UUID"
echo "============================================"
echo ""

test_api() {
    local method="$1" path="$2" body="$3" desc="$4"
    TOTAL=$((TOTAL+1))

    local tmpfile="/tmp/m5api_3003_resp_${TOTAL}.json"
    local curl_args=(-s -o "$tmpfile" -w "\nHTTP:%{http_code}")
    curl_args+=(-X "$method")
    curl_args+=(-H "Content-Type: application/json")
    curl_args+=(-H "X-API-Key: $API_KEY")

    if [ -n "$body" ]; then
        curl_args+=(-d "$body")
    fi

    local result
    result=$(curl "${curl_args[@]}" "${BASE}${path}" 2>/dev/null)
    local code=$(echo "$result" | grep "HTTP:" | tr -d "HTTP:")
    local resp_body=$(echo "$result" | sed '/^HTTP:/d')
    local size=${#resp_body}

    if [ "$code" -ge 200 ] 2>/dev/null && [ "$code" -lt 400 ] 2>/dev/null; then
        PASS=$((PASS+1))
        printf "  ✅ %2d. %-5s %-55s → %s (%d B) — %s\n" "$TOTAL" "$method" "$path" "$code" "$size" "$desc"
    else
        FAIL=$((FAIL+1))
        printf "  ❌ %2d. %-5s %-55s → %s (%d B) — %s\n" "$TOTAL" "$method" "$path" "$code" "$size" "$desc"
        local preview
        preview=$(echo "$resp_body" | head -c 150)
        echo "      $preview"
    fi
}

echo "── Identity Binding (non-destructive) ──"
test_api "POST" "/api/v1/identity/$IDENTITY_UUID/bind" "{\"file_uuid\":\"$FILE_UUID\",\"face_id\":\"face_1\"}" "Bind identity"
test_api "POST" "/api/v1/identity/$IDENTITY_UUID/unbind" "{\"file_uuid\":\"$FILE_UUID\",\"face_id\":\"face_1\"}" "Unbind identity"

echo ""
echo "── Identity Agent ──"
test_api "POST" "/api/v1/agents/identity/match-from-trace" "{\"file_uuid\":\"$FILE_UUID\",\"trace_id\":1,\"identity_uuid\":\"$IDENTITY_UUID\"}" "Match from trace"

echo ""
echo "============================================"
echo " Total:  $TOTAL"
echo " Passed: $PASS ✅"
echo " Failed: $FAIL ❌"
echo "============================================"

if [ $FAIL -gt 0 ]; then
    echo "❌ Phase 5 (3003) FAILED"
    exit 1
else
    echo "✅ Phase 5 (3003) PASSED"
fi
