#!/bin/bash
# Jupyter Lab — modo colaborativo con autodeteccion de puerto
# Generado por write_jupyter_launcher (fn_registry)

find_free_port() {
    for port in 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899; do
        if ! ss -tln 2>/dev/null | grep -q ":${port} " && \
           ! lsof -i:"$port" >/dev/null 2>&1; then
            echo $port
            return
        fi
    done
    echo 8888
}

PORT=${1:-$(find_free_port)}
cd "$(dirname "$0")"

echo $PORT > .jupyter-port

source .venv/bin/activate 2>/dev/null || true

if ! python -c "import jupyter_collaboration" 2>/dev/null; then
    echo "ERROR: jupyter-collaboration no esta instalado"
    echo "Instala con: uv add jupyter-collaboration"
    exit 1
fi

echo "════════════════════════════════════════════════"
echo "  Jupyter Lab + Colaboracion en puerto $PORT"
echo "════════════════════════════════════════════════"
echo ""
echo "  Abre: http://localhost:$PORT"
echo "  Ctrl+C para detener"
echo ""

jupyter lab \
    --port=$PORT \
    --no-browser \
    --ServerApp.token='' \
    --ServerApp.password='' \
    --ServerApp.disable_check_xsrf=True \
    --ServerApp.allow_origin='*' \
    --ServerApp.root_dir="$(pwd)" \
    --collaborative
