#!/usr/bin/env bash
# Setzt Projekt auf Ausgangszustand (status=NULL) und triggert POST /check/{id}
# Verwendung: bash test-run.sh [projectId]

set -euo pipefail

PROJECT_ID="${1:-1}"
BACKEND="http://localhost:8090"
DB_USER="wksp_ai"
DB_PASS='s!)löyx209aasgtrasdasiudkash5235FDSXljLJ'
DB_HOST="10.75.10.171"
DB_PORT="32710"
DB_SID="freepdb1"
KUBECONFIG_FILE="$(cd "$(dirname "$0")/.." && pwd)/env/frigo-dev.yaml"

echo "=== Test-Run: Projekt $PROJECT_ID ==="

# 1. Projekt zurücksetzen (status=NULL, progress=0, completed_at=NULL)
#    Ergebnisse löschen, aber original_text/translated_text BLEIBEN erhalten
#    → Phase A (OCR) wird beim nächsten Lauf automatisch übersprungen
echo ""
echo "→ DB-Reset: status=NULL, Ergebnisse löschen (Texte bleiben) ..."
sql -S "$DB_USER/$DB_PASS@$DB_HOST:$DB_PORT/$DB_SID" <<SQL
DELETE FROM dc_results WHERE project_id = $PROJECT_ID;
UPDATE dc_projects
SET    status       = NULL,
       progress     = 0,
       completed_at = NULL
WHERE  id = $PROJECT_ID;
COMMIT;
SELECT id, name, status, catalog_id, progress FROM dc_projects WHERE id = $PROJECT_ID;
SQL

# 2. Port-Forward sicherstellen (im Hintergrund, falls noch nicht aktiv)
if ! curl -sf "$BACKEND/check/health" > /dev/null 2>&1; then
    echo ""
    echo "→ Starte Port-Forward localhost:8090 → dc-backend:8090 ..."
    KUBECONFIG="$KUBECONFIG_FILE" kubectl port-forward \
        -n ai-env svc/dc-backend 8090:8090 &
    PF_PID=$!
    echo "  Port-Forward PID: $PF_PID"
    sleep 3
else
    PF_PID=""
    echo "→ Port-Forward bereits aktiv."
fi

# 3. Trigger
echo ""
echo "→ POST $BACKEND/check/$PROJECT_ID ..."
RESPONSE=$(curl -sf -X POST "$BACKEND/check/$PROJECT_ID" \
    -H "Content-Type: application/json" || echo "FEHLER: curl fehlgeschlagen")
echo "  Response: $RESPONSE"

# 4. Logs streamen
echo ""
echo "→ Logs (Ctrl+C zum Beenden):"
POD=$(KUBECONFIG="$KUBECONFIG_FILE" kubectl get pod -n ai-env -l app=dc-backend \
    --field-selector=status.phase=Running \
    -o jsonpath='{.items[0].metadata.name}' 2>/dev/null)
KUBECONFIG="$KUBECONFIG_FILE" kubectl logs -f "$POD" -n ai-env --since=10s

# Cleanup Port-Forward
if [ -n "${PF_PID:-}" ]; then
    kill "$PF_PID" 2>/dev/null || true
fi
