#!/usr/bin/env bash
set -euo pipefail

# ============================================================
# X-Financial Reimbursement Admin - Start Script
# ============================================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

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

info()  { echo -e "${GREEN}[INFO]${NC} $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }

# ----------------------------------------------------------
# Check Node.js
# ----------------------------------------------------------
if ! command -v node &>/dev/null; then
    error "Node.js is not installed. Install it first: https://nodejs.org"
fi

if ! command -v npm &>/dev/null; then
    error "npm is not installed. It should come with Node.js."
fi

info "Node.js $(node -v) | npm $(npm -v)"

# ----------------------------------------------------------
# WSL on a Windows-mounted repo should reuse Windows Node
# ----------------------------------------------------------
is_wsl() {
    grep -qi microsoft /proc/version 2>/dev/null
}

is_windows_mount() {
    case "$SCRIPT_DIR" in
        /mnt/*) return 0 ;;
        *) return 1 ;;
    esac
}

if is_wsl && is_windows_mount && command -v powershell.exe &>/dev/null && command -v wslpath &>/dev/null; then
    WIN_PATH="$(wslpath -w "$SCRIPT_DIR")"
    WIN_PATH_PS="${WIN_PATH//\'/\'\'}"
    info "Detected WSL on a Windows-mounted project"
    info "Using Windows npm to avoid cross-platform node_modules installs"
    info "Access: http://127.0.0.1:5173"
    echo ""
    exec powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Set-Location -LiteralPath '$WIN_PATH_PS'; npm start"
fi

# ----------------------------------------------------------
# Install dependencies only when they are missing or unusable
# ----------------------------------------------------------
dependencies_ready() {
    [ -d "node_modules" ] || return 1
    [ -f "node_modules/vite/bin/vite.js" ] || return 1
    [ -e "node_modules/.bin/vite" ] || [ -e "node_modules/.bin/vite.cmd" ] || return 1

    node -e "require('rollup')" >/dev/null 2>&1
}

if ! dependencies_ready; then
    warn "Dependencies are missing or incomplete"
    info "Running npm install..."
    npm install

    if ! dependencies_ready; then
        error "Dependencies are still incomplete after npm install. Try deleting node_modules and running npm install manually."
    fi
fi

# ----------------------------------------------------------
# Start dev server
# ----------------------------------------------------------
info "Starting X-Financial Reimbursement Admin..."
info "Access: http://127.0.0.1:5173"
echo ""

exec npm start
