#!/bin/bash
echo "=== Ribuu Edge Node Kurulum ==="
echo ""

# OS tespiti
if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "win32" ]]; then
    OS="windows"
elif [[ "$OSTYPE" == "darwin"* ]]; then
    OS="mac"
else
    OS="linux"
fi
echo "Sistem: $OS"

# Python ve pip tespit
PY=""
PIP=""

for cmd in python3 python py; do
    if command -v $cmd &>/dev/null; then
        PY=$cmd
        PIP="$cmd -m pip"
        break
    fi
done

if [ -z "$PY" ]; then
    echo ""
    echo "[!] Python bulunamadi!"
    if [ "$OS" == "windows" ]; then
        echo "    1. https://python.org adresine gidin"
        echo "    2. Python'u indirin ve kurun"
        echo "    3. Kurulumda 'Add Python to PATH' secenegini isaretleyin"
        echo "    4. Bu scripti tekrar calistirin"
    elif [ "$OS" == "mac" ]; then
        echo "    brew install python3"
    else
        echo "    sudo apt install python3 python3-pip"
    fi
    exit 1
fi

echo "[OK] Python: $($PY --version)"
echo "[OK] Pip: $PIP"

# Klasor
if [ "$OS" == "windows" ]; then
    EDGE_DIR="$USERPROFILE/ribuu-edge"
else
    EDGE_DIR="$HOME/ribuu-edge"
fi
mkdir -p "$EDGE_DIR"
cd "$EDGE_DIR"

# Paketler
echo "Paketler kuruluyor..."
$PIP install fastapi uvicorn httpx --quiet 2>/dev/null || \
$PIP install fastapi uvicorn httpx --break-system-packages --quiet 2>/dev/null

# Edge dosyalarini indir
echo "Edge dosyalari indiriliyor..."
for f in edge_server.py edge_sync.py ribuu-edge.py; do
    if command -v curl &>/dev/null; then
        curl -s "https://admin.ribuu.ai/edge/$f" -o "$f"
    elif command -v wget &>/dev/null; then
        wget -q "https://admin.ribuu.ai/edge/$f" -O "$f"
    fi
done

# Konfigurasyon
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

echo "[OK] Konfigurasyon kaydedildi"

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

# Baslat scripti
cat > start-edge.sh << 'STARTEOF'
#!/bin/bash
cd "$(dirname "$0")"
for cmd in python3 python py; do
    if command -v $cmd &>/dev/null; then
        PY=$cmd; break
    fi
done
echo "[Edge] Baslatiliyor..."
$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.sh

echo ""
echo "=== Kurulum Tamamlandi ==="
echo "Baslat: cd $EDGE_DIR && bash start-edge.sh"
