#!/bin/bash

echo "=== Ranking CAPES - Iniciando com ngrok ==="

cd /home/fred/projetos/ranking

echo "[1/5] Parando containers antigos..."
docker compose down 2>/dev/null

echo "[2/5] Limpando portas ocupadas..."
sudo fuser -k 8010/tcp 2>/dev/null
sudo fuser -k 5173/tcp 2>/dev/null

echo "[3/5] Matando ngrok antigo..."
pkill -f "ngrok http 5173" 2>/dev/null

echo "[4/5] Criando rede e subindo containers..."
docker network create shared_network 2>/dev/null
docker compose up -d
echo "Aguardando containers subirem..."
sleep 10

sleep 2

if ! docker ps | grep -q ranking_backend; then
    echo "ERRO: Backend não subiu!"
    exit 1
fi

if ! docker ps | grep -q ranking_frontend; then
    echo "ERRO: Frontend não subiu!"
    exit 1
fi

echo "[5/5] Iniciando ngrok..."
ngrok http 5173 --log=stdout > /tmp/ngrok-ranking.log 2>&1 &

sleep 4

NGROK_URL=$(curl -s http://127.0.0.1:4040/api/tunnels 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['tunnels'][0]['public_url'])" 2>/dev/null)

if [ -z "$NGROK_URL" ]; then
    echo "ERRO: ngrok não iniciou corretamente"
    exit 1
fi

echo ""
echo "=========================================="
echo "  Sistema Ranking CAPES iniciado!"
echo "=========================================="
echo ""
echo "  URL Publica (ngrok): $NGROK_URL"
echo ""
echo "  URLs Locais:"
echo "    - Frontend: http://localhost:5173"
echo "    - Backend:  http://localhost:8010"
echo "    - Ngrok UI: http://localhost:4040"
echo ""
echo "=========================================="
