#!/bin/bash
cd "$(dirname "$0")"
echo "=== Ribuu Edge Node Kurulum (Mac) ==="
echo ""

# Python kontrol
PY=""
for cmd in python3 python; do
    if command -v $cmd &>/dev/null; then PY=$cmd; break; fi
done

if [ -z "$PY" ]; then
    echo "[!] Python bulunamadi. Homebrew ile kuruluyor..."
    if ! command -v brew &>/dev/null; then
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    fi
    brew install python3
    PY=python3
fi

echo "[OK] $($PY --version)"

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

$PY -m pip install fastapi uvicorn httpx --quiet 2>/dev/null || \
$PY -m pip install fastapi uvicorn httpx --break-system-packages --quiet

for f in edge_server.py edge_sync.py ribuu-edge.py; do
    curl -s "https://admin.ribuu.ai/edge/$f" -o "$f"
done

# Web dosyalarini indir (edge versiyonu)
mkdir -p web
for f in admin.html kit.html person.html index.html barista.html sw-ribuu.js; do
    curl -s "https://admin.ribuu.ai/edge/web/$f" -o "web/$f"
done
for f in icon-192.png icon-512.png; do
    curl -s "https://admin.ribuu.ai/$f" -o "web/$f" 2>/dev/null || true
done

echo ""
echo "=== Konfigurasyon ==="
read -p "Edge Token (Admin panelinden alin): " 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}

cat > edge-config.json << EOF
{"cloud_url":"https://admin.ribuu.ai","edge_token":"$EDGE_TOKEN","business_id":$BIZ_ID,"business_slug":"$BIZ_SLUG","local_port":$LOCAL_PORT,"sync_interval":30}
EOF

cat > start-edge.command << 'STARTEOF'
#!/bin/bash
cd "$(dirname "$0")"
for cmd in python3 python; do command -v $cmd &>/dev/null && PY=$cmd && break; done
$PY edge_sync.py &
$PY -m uvicorn edge_server:app --host 0.0.0.0 --port $($PY -c "import json;print(json.load(open('edge-config.json'))['local_port'])")
STARTEOF
chmod +x start-edge.command

# DB olustur
echo "Veritabani olusturuluyor..."
$PY ribuu-edge.py

echo ""
echo "=== Kurulum Tamamlandi ==="
echo "Baslat: $EDGE_DIR/start-edge.command"
read -p "Simdi baslatmak ister misiniz? (E/H): " START
[[ "$START" =~ ^[Ee]$ ]] && bash start-edge.command
