#!/usr/bin/env bash
# Lanza backend Go (puerto 8095) + frontend Vite dev (puerto 5180) en paralelo.
# Vite hace proxy /api -> 8095, asi que abrir http://localhost:5180
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACK_DIR="$ROOT/backend"
FRONT_DIR="$ROOT/frontend"

PORT_BACK="${PORT_BACK:-8095}"
PORT_FRONT="${PORT_FRONT:-5180}"
DB_PATH="${DB_PATH:-./operations.db}"

cleanup() {
    echo ""
    echo ">>> Stopping..."
    [[ -n "${BACK_PID:-}" ]] && kill "$BACK_PID" 2>/dev/null || true
    [[ -n "${FRONT_PID:-}" ]] && kill "$FRONT_PID" 2>/dev/null || true
    wait 2>/dev/null || true
    exit 0
}
trap cleanup INT TERM EXIT

# 1. Build backend si no existe o si los .go/.sql son mas nuevos que el binario
if [[ ! -x "$BACK_DIR/kanban" ]] || [[ -n "$(find "$BACK_DIR" -maxdepth 3 \( -name '*.go' -o -name '*.sql' \) -newer "$BACK_DIR/kanban" 2>/dev/null)" ]]; then
    echo ">>> Building backend..."
    (cd "$BACK_DIR" && CGO_ENABLED=1 go build -tags fts5 -o kanban .)
fi

# 2. Asegurar deps frontend
if [[ ! -d "$FRONT_DIR/node_modules" ]]; then
    echo ">>> Installing frontend deps..."
    (cd "$FRONT_DIR" && pnpm install)
fi

# 3. Lanzar backend
echo ">>> Backend  http://localhost:$PORT_BACK  (db=$DB_PATH)"
(cd "$BACK_DIR" && ./kanban --port "$PORT_BACK" --db "$DB_PATH") &
BACK_PID=$!

# 4. Lanzar frontend (Vite con HMR + proxy a backend)
echo ">>> Frontend http://localhost:$PORT_FRONT  (HMR)"
(cd "$FRONT_DIR" && pnpm dev --port "$PORT_FRONT" --strictPort) &
FRONT_PID=$!

echo ""
echo ">>> PIDs: back=$BACK_PID front=$FRONT_PID"
echo ">>> Abrir: http://localhost:$PORT_FRONT"
echo ">>> Ctrl+C para parar ambos"

wait -n
