#!/bin/bash
# Ribuu Edge Node Kurulum Scripti
# Kafedeki PC'ye bir kez calistirilir

set -e
echo "=== Ribuu Edge Node Kurulum ==="
echo ""

# Python kontrol
if ! command -v python3 &> /dev/null; then
    echo "Python3 kuruluyor..."
    if command -v apt &> /dev/null; then
        sudo apt update && sudo apt install -y python3 python3-pip
    elif command -v brew &> /dev/null; then
        brew install python3
    else
        echo "HATA: Python3 bulunamadi. Manuel kurun: https://python.org"
        exit 1
    fi
fi

echo "[OK] Python3: $(python3 --version)"

# Klasor
EDGE_DIR="$HOME/ribuu-edge"
mkdir -p "$EDGE_DIR"
cd "$EDGE_DIR"

# Python paketleri
echo "Gerekli paketler kuruluyor..."
pip3 install fastapi uvicorn httpx --quiet

# Edge dosyalarini indir
echo "Ribuu Edge dosyalari indiriliyor..."
curl -s "https://admin.ribuu.ai/edge/edge_server.py" -o edge_server.py
curl -s "https://admin.ribuu.ai/edge/edge_sync.py" -o edge_sync.py
curl -s "https://admin.ribuu.ai/edge/ribuu-edge.py" -o ribuu-edge.py

# Konfigurasyonu al
echo ""
echo "=== Konfigürasyon ==="
read -p "Cloud URL [https://admin.ribuu.ai]: " CLOUD_URL
CLOUD_URL=${CLOUD_URL:-"https://admin.ribuu.ai"}
read -p "Edge Token (Admin panelinden alın): " EDGE_TOKEN
read -p "Business ID: " BIZ_ID
read -p "Business Slug: " BIZ_SLUG
read -p "Lokal Port [8080]: " LOCAL_PORT
LOCAL_PORT=${LOCAL_PORT:-8080}

# Config dosyasi yaz
cat > edge-config.json << EOF
{
  "cloud_url": "$CLOUD_URL",
  "edge_token": "$EDGE_TOKEN",
  "business_id": $BIZ_ID,
  "business_slug": "$BIZ_SLUG",
  "local_port": $LOCAL_PORT,
  "sync_interval": 30
}
EOF

echo "[OK] Konfigürasyon kaydedildi"

# DB olustur
python3 ribuu-edge.py

# Servis scripti olustur
cat > start-edge.sh << 'EOF'
#!/bin/bash
cd "$(dirname "$0")"
echo "[Edge] Baslatiliyor..."
# Sync servisini arka planda baslat
python3 edge_sync.py &
SYNC_PID=$!
echo "[Sync] PID: $SYNC_PID"
# Ana server
python3 -m uvicorn edge_server:app --host 0.0.0.0 --port $(python3 -c "import json;print(json.load(open('edge-config.json'))['local_port'])")
EOF
chmod +x start-edge.sh

echo ""
echo "=== Kurulum Tamamlandi ==="
echo ""
echo "Baslat: cd $EDGE_DIR && ./start-edge.sh"
echo ""
echo "Admin/Garson/Mutfak cihaslari su adrese baglaniyor:"
echo "http://$(hostname -I | awk '{print $1}'):$LOCAL_PORT"
echo ""
echo "Not: Cihazlar kafenin WiFi'sine baglanmali"
