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

# ==============================================================================
# LFŠ Organizer – development on a phone in the local network
#
# Starts the local PocketBase and the frontend (Vite) so that other devices on
# the same Wi-Fi reach them, and prints the address for the phone. Ctrl+C stops
# both.
#
#   ./start_lan.sh                 finds the computer's IP itself
#   LAN_IP=192.168.1.20 ./start_lan.sh
#   PB_PORT=8091 WEB_PORT=5174 ./start_lan.sh
#
# Windows: run it in Git Bash, like start_pocketbase.sh, which also prepares the
# database and demo data (needed once).
# ==============================================================================

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

PB_PORT="${PB_PORT:-8090}"
WEB_PORT="${WEB_PORT:-5173}"

case "$(uname -s)" in
    Darwin)               OS="mac";     EXE="" ;;
    Linux)                OS="linux";   EXE="" ;;
    MINGW*|MSYS*|CYGWIN*) OS="windows"; EXE=".exe" ;;
    *)                    echo "❌ Nepodporovaný OS: $(uname -s)"; exit 1 ;;
esac

PB_BIN="$PROJECT_DIR/bin/pocketbase$EXE"
if [ ! -f "$PB_BIN" ] || [ ! -f "$PROJECT_DIR/pb_data/data.db" ]; then
    echo "❌ Chybí PocketBase nebo jeho databáze. Nejdřív jednou spusťte ./start_pocketbase.sh."
    exit 1
fi
if [ ! -d "$PROJECT_DIR/frontend/node_modules" ]; then
    echo "❌ Chybí balíčky frontendu. Spusťte: cd frontend && npm install"
    exit 1
fi

# --- The computer's IP in the network: the interface of the default route --------
find_lan_ip() {
    case "$OS" in
        windows)
            powershell.exe -NoProfile -Command \
                "\$r = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue | Sort-Object { \$_.RouteMetric + \$_.InterfaceMetric } | Select-Object -First 1; if (\$r) { (Get-NetIPAddress -InterfaceIndex \$r.ifIndex -AddressFamily IPv4 | Where-Object { \$_.IPAddress -notlike '169.254.*' } | Select-Object -First 1).IPAddress }" \
                2>/dev/null | tr -d '\r'
            ;;
        mac)
            local iface
            iface="$(route -n get default 2>/dev/null | awk '/interface:/ {print $2}')"
            ipconfig getifaddr "${iface:-en0}" 2>/dev/null
            ;;
        linux)
            ip route get 1.1.1.1 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "src") {print $(i + 1); exit}}'
            ;;
    esac
}

LAN_IP="${LAN_IP:-$(find_lan_ip || true)}"
if [ -z "$LAN_IP" ]; then
    echo "❌ Nenašel jsem IP adresu počítače v síti. Zadejte ji ručně: LAN_IP=192.168.x.x ./start_lan.sh"
    exit 1
fi

# --- Both ports must be free: PocketBase or Vite running for this computer only block them
port_busy() {
    curl -s -o /dev/null --max-time 2 "http://127.0.0.1:$1/" 2>/dev/null
}
if port_busy "$PB_PORT"; then
    echo "❌ Na portu $PB_PORT už něco běží (nejspíš PocketBase ze start_pocketbase.sh). Zastavte ho a spusťte skript znovu."
    exit 1
fi
if port_busy "$WEB_PORT"; then
    echo "❌ Na portu $WEB_PORT už něco běží (nejspíš npm run dev:local). Zastavte ho a spusťte skript znovu."
    exit 1
fi

# --- Stopping: Ctrl+C stops PocketBase and Vite ---------------------------------
PIDS=()
# A process and everything it started (npm starts sh, which starts Vite's node), listed before anything is stopped:
# a stopped parent may take its children along, and the rest then belong to init.
tree_of() {
    local child
    echo "$1"
    for child in $(pgrep -P "$1" 2>/dev/null || true); do tree_of "$child"; done
}
kill_tree() {
    local pids
    pids="$(tree_of "$1")"
    # shellcheck disable=SC2086
    kill $pids 2>/dev/null || true
}
stop_all() {
    trap - INT TERM EXIT
    echo ""
    echo "⏹️  Zastavuji PocketBase a frontend..."
    for pid in ${PIDS[@]+"${PIDS[@]}"}; do
        if [ "$OS" = "windows" ] && [ -r "/proc/$pid/winpid" ]; then
            # Programs of Windows: taskkill stops the whole tree.
            taskkill //F //T //PID "$(cat "/proc/$pid/winpid")" > /dev/null 2>&1 || true
        else
            kill_tree "$pid"
        fi
    done
    wait 2>/dev/null || true
    exit 0
}
trap stop_all INT TERM EXIT

# --- PocketBase on every interface ---------------------------------------------
echo "🚀 Spouštím PocketBase na 0.0.0.0:$PB_PORT..."
"$PB_BIN" serve --http="0.0.0.0:$PB_PORT" --dir="$PROJECT_DIR/pb_data" --hooksDir="$PROJECT_DIR/pb_hooks" \
    --migrationsDir="$PROJECT_DIR/pb_migrations" > "$PROJECT_DIR/pb_lan.log" 2>&1 &
PIDS+=($!)

for _ in $(seq 1 40); do
    if curl -s --max-time 1 "http://127.0.0.1:$PB_PORT/api/health" | grep -q '200'; then break; fi
    if ! kill -0 "${PIDS[0]}" 2>/dev/null; then
        echo "❌ PocketBase se nespustil. Konec jeho výpisu (pb_lan.log):"
        tail -n 20 "$PROJECT_DIR/pb_lan.log"
        exit 1
    fi
    sleep 0.5
done

# --- The frontend, with PocketBase at the computer's IP -------------------------
echo "🚀 Spouštím frontend na 0.0.0.0:$WEB_PORT..."
(
    cd "$PROJECT_DIR/frontend"
    # The environment beats .env.localpb, whose 127.0.0.1 would be the phone itself.
    VITE_POCKETBASE_URL="http://$LAN_IP:$PB_PORT" exec npm run dev:local -- --host 0.0.0.0 --port "$WEB_PORT" --strictPort
) &
PIDS+=($!)

echo ""
echo "📱 ========================================================"
echo "   Na mobilu (stejná Wi-Fi) otevřete:"
echo ""
echo "      http://$LAN_IP:$WEB_PORT/"
echo ""
echo "   PocketBase:  http://$LAN_IP:$PB_PORT/_/  (výpis v pb_lan.log)"
echo "========================================================"
if [ "$OS" = "windows" ]; then
    PROFILE="$(powershell.exe -NoProfile -Command "(Get-NetConnectionProfile | Where-Object { \$_.IPv4Connectivity -eq 'Internet' } | Select-Object -First 1).NetworkCategory" 2>/dev/null | tr -d '\r' || true)"
    if [ "$PROFILE" = "Public" ]; then
        echo "   ⚠️  Síť je ve Windows vedená jako Veřejná: firewall může mobil blokovat."
        echo "      Přepněte ji na Soukromou (Nastavení → Síť a internet → Wi-Fi → síť → Typ síťového profilu)."
    fi
    echo "   Když se Windows zeptá na přístup pro node.exe nebo pocketbase.exe, dejte Povolit."
fi
echo "   Instalace na plochu a offline režim potřebují HTTPS, přes tuto adresu nepůjdou."
echo "   Ctrl+C zastaví obojí."
echo ""

# Runs while both run; when one ends, the trap above stops the other.
while kill -0 "${PIDS[0]}" 2>/dev/null && kill -0 "${PIDS[1]}" 2>/dev/null; do
    sleep 1
done
echo "⚠️  PocketBase nebo frontend skončil, zastavuji i druhý."
