#!/bin/bash
# dev.sh — GnommoEditor local development
# Requires gu_common to be running (postgres :5432, minio :9000).
#
# Usage:
#   ./dev.sh [--port <frontend_port>] [--api-port <backend_port>]
#
# Services (gu_common):     This script runs natively:
#   - PostgreSQL :5432        - Express backend :<BACKEND_PORT>
#   - MinIO      :9000        - Vite frontend  :<FRONTEND_PORT>

set -e

# ── Args ───────────────────────────────────────────────────────────────────────

FRONTEND_PORT=5173
BACKEND_PORT=3001

while [[ $# -gt 0 ]]; do
  case "$1" in
    --port)     FRONTEND_PORT="$2"; shift 2 ;;
    --api-port) BACKEND_PORT="$2";  shift 2 ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

# ── Setup ──────────────────────────────────────────────────────────────────────

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="$SCRIPT_DIR/dev.log"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'

log() { local c="$1"; shift; echo -e "${c}$*${NC}"; echo "$*" >> "$LOG_FILE"; }

echo "=== dev.sh started $(date -u '+%Y-%m-%d %H:%M:%S UTC') ===" > "$LOG_FILE"
log "$GREEN" "Starting GnommoEditor..."
log "$GREEN" "  Frontend : http://localhost:${FRONTEND_PORT}"
log "$GREEN" "  Backend  : http://localhost:${BACKEND_PORT}"
log "$GREEN" "  Log file : ${LOG_FILE}"

# ── Node version guard ─────────────────────────────────────────────────────────

REQUIRED_NODE=20
CURRENT_NODE=$(node --version 2>/dev/null | sed 's/v//' | cut -d. -f1)

if [ -z "$CURRENT_NODE" ]; then
  log "$RED" "Error: node not found."; log "$YELLOW" "Run: nvm use ${REQUIRED_NODE}"; exit 1
fi
if [ "$CURRENT_NODE" -lt "$REQUIRED_NODE" ]; then
  log "$RED" "Error: Node ${CURRENT_NODE} too old (need >= ${REQUIRED_NODE})."
  log "$YELLOW" "Fix: nvm use ${REQUIRED_NODE}"; exit 1
fi
log "$GREEN" "✓ Node v${CURRENT_NODE}"

# ── Load .env ──────────────────────────────────────────────────────────────────

if [ -f "$SCRIPT_DIR/.env" ]; then
  set -a; source "$SCRIPT_DIR/.env"; set +a
  log "$GREEN" "✓ Loaded .env"
fi

# ── npm install ────────────────────────────────────────────────────────────────

if [ ! -d "$SCRIPT_DIR/node_modules" ]; then
  log "$YELLOW" "Installing frontend dependencies..."
  npm install --prefix "$SCRIPT_DIR" >> "$LOG_FILE" 2>&1
  log "$GREEN" "✓ Frontend deps installed"
fi
if [ ! -d "$SCRIPT_DIR/backend/node_modules" ]; then
  log "$YELLOW" "Installing backend dependencies..."
  npm install --prefix "$SCRIPT_DIR/backend" >> "$LOG_FILE" 2>&1
  log "$GREEN" "✓ Backend deps installed"
fi

# ── Check gu_common services ───────────────────────────────────────────────────

if ! docker ps --format "{{.Names}}" | grep -qE "gnommo.?db"; then
  log "$RED" "Error: postgres (gnommo-db) is not running."
  log "$YELLOW" "Start gu_common first:  cd ../gu_common && ./dev.sh"
  exit 1
fi
log "$GREEN" "✓ PostgreSQL is running"

if ! docker ps --format "{{.Names}}" | grep -q "gnommo-minio"; then
  log "$YELLOW" "⚠ MinIO not running — file uploads won't work"
else
  log "$GREEN" "✓ MinIO is running"
fi

# ── Ensure gnommoeditor database exists ────────────────────────────────────────

DB_CONTAINER=$(docker ps --format "{{.Names}}" | grep -E "gnommo.?db" | head -1)
docker exec "$DB_CONTAINER" psql -U gnommo \
  -c "CREATE DATABASE gnommoeditor;" 2>/dev/null \
  && log "$GREEN" "✓ Database gnommoeditor created" \
  || log "$GREEN" "✓ Database gnommoeditor already exists"

# ── Environment ────────────────────────────────────────────────────────────────

export NODE_ENV=development
export PORT=$BACKEND_PORT
export DATABASE_URL="postgresql://gnommo:${POSTGRES_PASSWORD:-gnommo_secret}@localhost:5432/gnommoeditor"
export CORS_ORIGIN="http://localhost:${FRONTEND_PORT}"
export INGEST_API_KEY="${INGEST_API_KEY:-dev-ingest-key-change-me}"
export JWT_SECRET="${JWT_SECRET:-dev-jwt-secret-change-me}"
export MINIO_ENDPOINT="http://localhost:9000"
export MINIO_PUBLIC_URL="http://localhost:9000"
export MINIO_BUCKET="${MINIO_BUCKET:-glitch-university}"
export MINIO_ROOT_USER="${MINIO_ROOT_USER:-minioadmin}"
export MINIO_ROOT_PASSWORD="${MINIO_ROOT_PASSWORD:-minioadmin}"

# ── Cleanup trap ───────────────────────────────────────────────────────────────

cleanup() {
  echo ""
  log "$YELLOW" "Shutting down..."
  kill $BACKEND_PID  2>/dev/null || true
  kill $FRONTEND_PID 2>/dev/null || true
  echo "=== dev.sh stopped $(date -u '+%Y-%m-%d %H:%M:%S UTC') ===" >> "$LOG_FILE"
  log "$YELLOW" "gu_common services left running."
  exit 0
}
trap cleanup SIGINT SIGTERM

# ── Migrations ─────────────────────────────────────────────────────────────────

log "$GREEN" "Running migrations..."
cd "$SCRIPT_DIR/backend"
npm run migrate:up >> "$LOG_FILE" 2>&1 \
  && log "$GREEN" "✓ Migrations up to date" \
  || { log "$RED" "Migration failed — check dev.log"; exit 1; }

# ── Start backend ──────────────────────────────────────────────────────────────

log "$GREEN" "Starting backend on port ${BACKEND_PORT}..."
npm run dev >> "$LOG_FILE" 2>&1 &
BACKEND_PID=$!

sleep 2

# ── Start frontend ─────────────────────────────────────────────────────────────

log "$GREEN" "Starting frontend on port ${FRONTEND_PORT}..."
cd "$SCRIPT_DIR"
npm run dev -- --port "$FRONTEND_PORT" >> "$LOG_FILE" 2>&1 &
FRONTEND_PID=$!

echo ""
echo -e "${GREEN}============================================${NC}"
echo -e "${GREEN}  GnommoEditor is running!${NC}"
echo -e "${GREEN}============================================${NC}"
echo ""
echo -e "  Frontend : ${YELLOW}http://localhost:${FRONTEND_PORT}${NC}"
echo -e "  Backend  : ${YELLOW}http://localhost:${BACKEND_PORT}${NC}"
echo -e "  Database : ${YELLOW}localhost:5432 / gnommoeditor${NC}"
echo -e "  MinIO    : ${YELLOW}localhost:9000${NC}"
echo -e "  Log file : ${YELLOW}${LOG_FILE}${NC}"
echo ""
echo -e "  Press ${RED}Ctrl+C${NC} to stop (gu_common keeps running)"
echo ""

wait
