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

# 1) Basis-URL Deines FastAPI-Servers
export BASE_URL="http://localhost:8000"

# 2) MediaWiki-Zugangsdaten
export WIKI_API_URL="https://karatetrainer.net/api.php"
export WIKI_BOT_USER="LarsS@APIBot"
export WIKI_BOT_PASSWORD="6snci781sh79tbmvb2u9ld4bkd1i7n5t"

echo -e "\n?? Starte Health-Check für MediaWiki…"
HTTP=$(curl -s -o /dev/null -w '%{http_code}' "${BASE_URL}/import/wiki/health")
if [[ "$HTTP" != "200" ]]; then
  echo "? Health-Check fehlgeschlagen (HTTP $HTTP)"
  exit 1
fi
echo "? MediaWiki-Health OK (200)"

echo -e "\n?? Teste MediaWiki-Login…"
LOGIN_RESP=$(curl -s -X POST "${BASE_URL}/import/wiki/login" \
  -H "Content-Type: application/json" \
  -d "{\"username\":\"${WIKI_BOT_USER}\",\"password\":\"${WIKI_BOT_PASSWORD}\"}" )
echo "? Login-Response: $LOGIN_RESP"
# Optional: prüfen, ob "success" enthalten ist
if [[ "$LOGIN_RESP" != *"success"* ]]; then
  echo "? MediaWiki-Login fehlgeschlagen"
  exit 1
fi
echo "? MediaWiki-Login erfolgreich"

echo -e "\n?? Testet bestehenden /exercise-Endpoint…"
# Collection exercises aufräumen
curl -s -X DELETE "${BASE_URL}/delete-collection?collection=exercises" || true >/dev/null

# Erzeugen
CREATE=$(curl -s -X POST "${BASE_URL}/exercise" \
  -H 'Content-Type: application/json' \
  -d '{
    "title":"TestÜbung",
    "summary":"Zusammenfassung",
    "short_description":"Kurz",
    "discipline":"Test",
    "age_group":"Erwachsene",
    "target_group":"Tester",
    "min_participants":1,
    "duration_minutes":5,
    "category":"test",
    "purpose":"Demo",
    "execution":"Ausführen",
    "notes":"",
    "preparation":"",
    "method":"",
    "equipment":[]
  }')
echo "? Create Übung: $CREATE"
if [[ "$CREATE" != *"TestÜbung"* ]]; then
  echo "? Übung wurde nicht angelegt"
  exit 1
fi
echo "? /exercise POST OK"

# Auflisten
LIST=$(curl -s "${BASE_URL}/exercise?discipline=Test")
if [[ "$LIST" != *"TestÜbung"* ]]; then
  echo "? /exercise GET liefert nicht die TestÜbung"
  exit 1
fi
echo "? /exercise GET OK"

echo -e "\n?? Testet Embed/Search…"
# Einen Chunk einbetten
curl -s -X POST "${BASE_URL}/embed" \
  -H 'Content-Type: application/json' \
  -d '{
    "chunks": [
      {"text":"Hallo Welt","source":"test","source_type":"txt","title":"T","version":"1","related_to":"","tags":[],"owner":""}
    ],
    "collection":"default"
  }' >/dev/null

# Suche
SEARCH=$(curl -s "${BASE_URL}/search?query=Hallo")
if [[ "$SEARCH" != *"Hallo Welt"* ]]; then
  echo "? /search liefert unerwartetes Ergebnis"
  exit 1
fi
echo "? /search OK"

echo -e "\n?? Alle Tests erfolgreich abgeschlossen!"
