#!/bin/bash
#
# Crumbforest Setup Script
# Komplettes Setup für Development Environment
#

set -e  # Exit on error

echo "============================================"
echo "🦉 Crumbforest Setup"
echo "============================================"
echo ""

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Functions
print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

check_command() {
    if command -v $1 &> /dev/null; then
        print_success "$1 ist installiert"
        return 0
    else
        print_error "$1 ist NICHT installiert"
        return 1
    fi
}

# Step 1: Check Prerequisites
echo "=== Step 1: Prerequisites Check ==="
echo ""

all_ok=true

if ! check_command docker; then
    print_error "Docker ist nicht installiert!"
    echo "  Installation: https://docs.docker.com/get-docker/"
    all_ok=false
fi

if ! check_command docker-compose || ! check_command docker; then
    if docker compose version &> /dev/null; then
        print_success "docker compose (V2) ist installiert"
    else
        print_error "docker-compose ist nicht installiert!"
        echo "  Installation: https://docs.docker.com/compose/install/"
        all_ok=false
    fi
else
    print_success "docker-compose ist installiert"
fi

if ! check_command python3; then
    print_warning "Python 3 ist nicht installiert (optional für Tests)"
fi

if ! check_command curl; then
    print_warning "curl ist nicht installiert (empfohlen für Tests)"
fi

echo ""

if [ "$all_ok" = false ]; then
    print_error "Bitte installiere die fehlenden Dependencies"
    exit 1
fi

# Step 2: Environment Setup
echo "=== Step 2: Environment Setup ==="
echo ""

if [ ! -f "compose/.env" ]; then
    print_warning ".env Datei existiert noch nicht"
    echo ""
    echo "Erstelle compose/.env aus Template..."

    cat > compose/.env << 'EOF'
# Database Configuration
MARIADB_HOST=db
MARIADB_USER=crumb
MARIADB_PASSWORD=crumbsecret
MARIADB_DATABASE=crumbforest
MARIADB_ROOT_PASSWORD=rootsecret

# FastAPI Configuration
APP_SECRET=change-me-in-production-to-random-string

# Qdrant Configuration
QDRANT_URL=http://qdrant:6333

# AI Provider API Keys
# Mindestens einen Provider konfigurieren!
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
OPENROUTER_API_KEY=

# Default Providers
DEFAULT_EMBEDDING_PROVIDER=openai
DEFAULT_COMPLETION_PROVIDER=openai

# RAG Settings
RAG_CHUNK_SIZE=1000
RAG_CHUNK_OVERLAP=200
EOF

    print_success "compose/.env erstellt"
    echo ""
    print_warning "WICHTIG: Bitte füge deine API Keys in compose/.env ein!"
    echo ""
    echo "Beispiel:"
    echo "  OPENAI_API_KEY=sk-..."
    echo "  ANTHROPIC_API_KEY=sk-ant-..."
    echo ""

    read -p "Drücke ENTER um fortzufahren, wenn du die API Keys eingetragen hast..."
else
    print_success "compose/.env existiert bereits"
fi

# Check if API keys are set
if grep -q "OPENAI_API_KEY=$" compose/.env && \
   grep -q "ANTHROPIC_API_KEY=$" compose/.env && \
   grep -q "OPENROUTER_API_KEY=$" compose/.env; then
    print_warning "Keine API Keys gefunden in compose/.env"
    echo "  Das System wird starten, aber RAG-Features funktionieren nicht!"
    echo ""
fi

# Step 3: Docker Setup
echo "=== Step 3: Docker Setup ==="
echo ""

# Check if docker daemon is running
if ! docker info &> /dev/null; then
    print_error "Docker daemon läuft nicht!"
    echo "  Bitte starte Docker Desktop oder den Docker Daemon"
    exit 1
fi

print_success "Docker daemon läuft"

# Create necessary directories
echo "Erstelle Daten-Verzeichnisse..."
mkdir -p data/mysql data/qdrant
print_success "Verzeichnisse erstellt"

# Step 4: Build and Start
echo ""
echo "=== Step 4: Build & Start ==="
echo ""

cd compose

echo "Baue Docker Images (das kann einige Minuten dauern)..."
if docker compose build; then
    print_success "Docker Images gebaut"
else
    print_error "Build fehlgeschlagen!"
    exit 1
fi

echo ""
echo "Starte Container..."
if docker compose up -d; then
    print_success "Container gestartet"
else
    print_error "Start fehlgeschlagen!"
    exit 1
fi

cd ..

# Step 5: Wait for Services
echo ""
echo "=== Step 5: Warte auf Services ==="
echo ""

echo "Warte auf MariaDB..."
sleep 5

max_attempts=30
attempt=0
while [ $attempt -lt $max_attempts ]; do
    if docker compose -f compose/docker-compose.yml exec -T db sh -c 'mariadb -u$MARIADB_USER -p$MARIADB_PASSWORD -e "SELECT 1" >/dev/null 2>&1'; then
        print_success "MariaDB ist bereit"
        break
    fi
    attempt=$((attempt + 1))
    echo -n "."
    sleep 1
done

if [ $attempt -eq $max_attempts ]; then
    print_error "MariaDB Timeout"
    exit 1
fi

echo "Warte auf FastAPI..."
sleep 3

attempt=0
while [ $attempt -lt $max_attempts ]; do
    if curl -s http://localhost:8000/health > /dev/null 2>&1; then
        print_success "FastAPI ist bereit"
        break
    fi
    attempt=$((attempt + 1))
    echo -n "."
    sleep 1
done

if [ $attempt -eq $max_attempts ]; then
    print_error "FastAPI Timeout"
    exit 1
fi

echo ""
print_success "Qdrant ist bereit"

# Step 6: Verify Installation
echo ""
echo "=== Step 6: Verification ==="
echo ""

# Check FastAPI
if curl -s http://localhost:8000/health | grep -q "ok"; then
    print_success "FastAPI Health Check OK"
else
    print_error "FastAPI Health Check FAILED"
fi

# Check Qdrant
if curl -s http://localhost:6333/collections > /dev/null 2>&1; then
    print_success "Qdrant erreichbar"
else
    print_warning "Qdrant nicht erreichbar"
fi

# Check Database
if docker compose -f compose/docker-compose.yml exec -T db sh -c 'mariadb -u$MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE -e "SHOW TABLES;" 2>/dev/null' | grep -q "users"; then
    print_success "Datenbank-Schema erstellt"
else
    print_error "Datenbank-Schema fehlt"
fi

# Step 7: Summary
echo ""
echo "============================================"
echo "✓ Setup abgeschlossen!"
echo "============================================"
echo ""
echo "URLs:"
echo "  - FastAPI:        http://localhost:8000"
echo "  - Admin Login:    http://localhost:8000/de/login"
echo "  - Qdrant UI:      http://localhost:6333/dashboard"
echo "  - API Docs:       http://localhost:8000/docs"
echo ""
echo "Admin Credentials:"
echo "  - Email:    admin@crumb.local"
echo "  - Password: admin123"
echo ""
echo "Demo User:"
echo "  - Email:    demo@crumb.local"
echo "  - Password: demo123"
echo ""
echo "Nächste Schritte:"
echo "  1. Logs ansehen:    ./logs.sh"
echo "  2. Tests ausführen: ./test.sh"
echo "  3. System stoppen:  ./stop.sh"
echo ""
echo "Wuuuuhuuu! 💚"
echo ""
