#!/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}"
# Default DB lives at apps/kanban/operations.db. Force an absolute path so
# the value survives the `cd $BACK_DIR` below — otherwise a relative
# ./operations.db would land inside backend/.
DB_PATH="${DB_PATH:-$ROOT/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
VERSION=$(awk -F': ' '/^version:/ {print $2; exit}' "$ROOT/app.md" 2>/dev/null || echo "dev")
if [[ ! -x "$BACK_DIR/kanban" ]] \
   || [[ -n "$(find "$BACK_DIR" -maxdepth 3 \( -name '*.go' -o -name '*.sql' \) -newer "$BACK_DIR/kanban" 2>/dev/null)" ]] \
   || [[ "$ROOT/app.md" -nt "$BACK_DIR/kanban" ]]; then
    echo ">>> Building backend (version=$VERSION)..."
    (cd "$BACK_DIR" && CGO_ENABLED=1 go build -tags fts5 \
        -ldflags="-X main.Version=$VERSION" \
        -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
# KANBAN_MODULE_KEY: passphrase used to AES-GCM encrypt module config_json.
# A stable default keeps the dev loop ergonomic; in production set this via
# the host's secret store. Changing it invalidates previously stored modules.
export KANBAN_MODULE_KEY="${KANBAN_MODULE_KEY:-local-dev-secret-rotate-in-prod}"
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
