#!/bin/bash
echo "🌱 Iniciando Nodo Tairuma..."

# 1. Python Setup
if ! command -v python3 &> /dev/null; then
    echo "Error: Python3 no encontrado."
    exit 1
fi

if [ ! -d "venv" ]; then
    echo "Creando entorno virtual..."
    python3 -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
else
    source venv/bin/activate
fi

# 2. Cloudflare Tunnel Setup (Auto-Download)
if [ ! -f "cloudflared" ]; then
    echo "⬇️ Descargando Cloudflare Tunnel..."
    OS=$(uname -s | tr '[:upper:]' '[:lower:]')
    ARCH=$(uname -m)
    
    if [ "$ARCH" == "x86_64" ]; then ARCH="amd64"; fi
    if [ "$ARCH" == "aarch64" ]; then ARCH="arm64"; fi

    URL="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-${OS}-${ARCH}"
    
    echo "Detectado: ${OS} ${ARCH}"
    curl -L --output cloudflared "$URL"
    chmod +x cloudflared
fi

# 3. Start Tunnel
echo "🚇 Iniciando Tunel..."
pkill -f cloudflared
./cloudflared tunnel --url http://localhost:8000 --logfile tunnel.log > /dev/null 2>&1 &
sleep 5

# 4. Extract URL (Quick Tunnel)
TUNNEL_URL=$(grep -o 'https://.*\.trycloudflare.com' tunnel.log | head -n 1)

if [ ! -z "$TUNNEL_URL" ]; then
    echo "🌍 Tu Nodo Publico: $TUNNEL_URL"
    
    # Auto-Register with Founder
    echo "🔍 Buscando Nodo Fundador..."
    SEED_NODE=$(python3 -c "import requests; print(requests.get('https://tairuma.netlify.app/nodes.json').json()[0])")
    
    if [ ! -z "$SEED_NODE" ]; then
        echo "🌱 Registrando en: $SEED_NODE"
        curl -X POST "$SEED_NODE/api/network/register" -H "Content-Type: application/json" -d "{\"url\": \"$TUNNEL_URL\"}"
    else
        echo "⚠️ No se encontro nodo fundador activo."
    fi
else
    echo "⚠️ Tunel iniciado (Verifica tunnel.log si no aparece URL)"
fi

# 5. Run Node
echo "🚀 Arrancando Tairuma..."
python3 main.py
