@echo off
setlocal EnableDelayedExpansion
cd /d "%~dp0"
echo === URVault startup ===

:: Update LOCAL_IP in .env
for /f "tokens=2 delims=:" %%a in ('ipconfig ^| findstr /C:"IPv4 Address" ^| findstr /V "169.254"') do (
    set "RAW_IP=%%a" & set "CIP=!RAW_IP: =!" & goto :ipfound
)
:ipfound
if defined CIP (
    node -e "try{const fs=require('fs');let e=fs.readFileSync('.env','utf8');e=e.replace(/^LOCAL_IP=.*/m,'LOCAL_IP=!CIP!');fs.writeFileSync('.env',e);}catch(e){}"
    echo Local IP: !CIP!
)

:: Read PORT from .env
for /f "tokens=1,2 delims==" %%k in (.env) do if "%%k"=="PORT" set PORT=%%l
if not defined PORT set PORT=5173

:: Start Cloudflare tunnel watchdog
if exist cloudflared.exe (
    echo Starting remote access tunnel...
    start /B powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0tunnel-watchdog.ps1" -Port !PORT! -EnvFile "%~dp0.env"
) else (
    echo cloudflared.exe not found -- remote access unavailable.
)

:: Ensure MySQL is running
echo Ensuring database is running...
net start MySQL84 >nul 2>&1
powershell -NoProfile -Command "Start-Service -Name 'MySQL*' -ErrorAction SilentlyContinue" >nul 2>&1

:: Run migrations
echo Running database migrations...
node run-migrations.js 2>nul || echo Migrations skipped.

:: Start server
echo Starting server...
node dist\server.js
