#!/usr/bin/env bash
# ===============================================================
#   TradeMind AI - Instalador automatico (macOS / Linux)
#
#   USO:
#     chmod +x install.sh && ./install.sh     (descargado como archivo)
#     curl -sSL https://trademind-bot.vercel.app/downloads/install.sh | bash
#     bash <(curl -sSL https://trademind-bot.vercel.app/downloads/install.sh)
# ===============================================================
set -e

WHEEL_URL="https://trademind-bot.vercel.app/downloads/trademind_ai-2.0.3-py3-none-any.whl"
VENV_DIR="$HOME/.trademind-venv"

echo
echo "===================================================="
echo "  TradeMind AI - Instalador"
echo "===================================================="
echo

# ---------- 1. Detectar Python 3.10+ ----------
PY=""
for cand in python3.12 python3.11 python3.10 python3; do
    if command -v "$cand" >/dev/null 2>&1; then
        if "$cand" -c 'import sys; sys.exit(0 if sys.version_info >= (3,10) else 1)' 2>/dev/null; then
            PY="$cand"
            break
        fi
    fi
done

if [ -z "$PY" ]; then
    echo "[ERROR] Python 3.10 o superior no encontrado."
    echo
    echo "macOS:  brew install python@3.12"
    echo "Ubuntu: sudo apt install python3 python3-pip python3-venv"
    echo "Fedora: sudo dnf install python3 python3-pip"
    exit 1
fi

PYVER=$("$PY" -c 'import sys;print(".".join(map(str,sys.version_info[:3])))')
echo "[OK] Python ${PYVER} detectado."

# ---------- 2. Crear venv (no requiere root, evita PEP 668) ----------
if [ ! -x "$VENV_DIR/bin/python" ]; then
    echo "Creando entorno virtual en $VENV_DIR ..."
    "$PY" -m venv "$VENV_DIR" || { echo "[ERROR] No pude crear el venv."; exit 1; }
    # En algunas distros (Debian/Ubuntu sin python3-venv) el comando
    # sale con 0 pero el ejecutable no materializa. Validamos.
    [ -x "$VENV_DIR/bin/python" ] || { echo "[ERROR] El venv se creo pero python no esta ejecutable."; exit 1; }
fi
VENV_PY="$VENV_DIR/bin/python"
echo "[OK] Entorno virtual: $VENV_DIR"

# ---------- 3. pip install — PyPI primero (auto-upgrade post-publish) ----------
echo
echo "Instalando TradeMind AI ..."
"$VENV_PY" -m pip install --upgrade pip --quiet

# Intentar primero PyPI. Si todavia no esta publicado, cae al wheel de Vercel.
if "$VENV_PY" -m pip install --upgrade --quiet trademind-ai 2>/dev/null; then
    echo "[OK] TradeMind AI instalado desde PyPI."
else
    echo "[info] PyPI no disponible, usando rueda alternativa del sitio ..."
    "$VENV_PY" -m pip install --upgrade --quiet "$WHEEL_URL"
fi
echo "[OK] TradeMind AI instalado correctamente."
echo

# ---------- 4. Activar licencia ----------
# Funciona tanto si el script corre como archivo (./install.sh) como
# si se invoca piped (curl | bash). Cuando se ejecuta piped, fd 0 es
# la pipe del script — no la TTY — y `read` consumiria lineas del
# propio script. Por eso, si NO somos TTY, redirigimos al TTY.
ask_key() {
    if [ -t 0 ]; then
        read -p "Pega tu key de licencia (formato XXX-XXX-XXX-XX): " KEY
    elif [ -r /dev/tty ]; then
        read -p "Pega tu key de licencia (formato XXX-XXX-XXX-XX): " KEY < /dev/tty
    else
        echo "[ERROR] No puedo leer desde TTY. Corre chmod +x install.sh && ./install.sh"
        exit 1
    fi
}
while true; do
    ask_key
    if [ -n "$KEY" ]; then break; fi
    echo "Debes pegar una key."
done

"$VENV_PY" -m trademind.cli activate "$KEY"
echo

# ---------- 5. Iniciar ahora o no ----------
if [ -t 0 ]; then
    read -p "Iniciar el bot ahora? (S/N): " RUNNOW
elif [ -r /dev/tty ]; then
    read -p "Iniciar el bot ahora? (S/N): " RUNNOW < /dev/tty
else
    RUNNOW="N"
fi
if [[ "$RUNNOW" =~ ^[SsYy]$ ]]; then
    echo
    echo "Iniciando TradeMind AI en http://localhost:3000 ..."
    exec "$VENV_PY" -m trademind.cli run --no-browser
else
    cat <<EOF

Listo. Para iniciar el bot mas tarde:

  $VENV_PY -m trademind.cli run

Si agregas $VENV_DIR/bin a tu PATH, podes usar simplemente:
  trademind

Para actualizar a la ultima version cuando lance una nueva:
  $VENV_PY -m pip install --upgrade trademind-ai

EOF
fi
