@echo off
setlocal
cd /d "%~dp0"


set "START_LOCAL_BACKEND=0"
for /f "usebackq delims=" %%A in (`powershell -NoProfile -ExecutionPolicy Bypass -Command "$p='config_server.json'; if(Test-Path $p){ try { $c=Get-Content $p -Raw | ConvertFrom-Json; if($c.client.autoStartLocalBackend -eq $true){ '1' } else { '0' } } catch { '0' } } else { '0' }"`) do set "START_LOCAL_BACKEND=%%A"

if "%START_LOCAL_BACKEND%"=="1" (
  where node >nul 2>nul
  if not errorlevel 1 (
    powershell -NoProfile -ExecutionPolicy Bypass -Command "try { Invoke-RestMethod -Uri 'http://127.0.0.1:31337/health' -TimeoutSec 1 | Out-Null } catch { Start-Process -WindowStyle Minimized -FilePath 'node' -ArgumentList 'backend/server.js' -WorkingDirectory '%CD%' }" >nul 2>nul
  ) else (
    echo Node.js nao encontrado. O jogo abre, mas sem backend local automatico.
  )
) else (
  echo Cliente configurado para servidor externo. Nao vou iniciar backend local.
)

set "GAME=%CD%\src\index.html"
set "GAME_URL=file:///%GAME:\=/%"
set "EDGE=%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe"
if not exist "%EDGE%" set "EDGE=%ProgramFiles%\Microsoft\Edge\Application\msedge.exe"
set "CHROME=%ProgramFiles%\Google\Chrome\Application\chrome.exe"
if not exist "%CHROME%" set "CHROME=%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe"

if exist "%EDGE%" (
  start "Reinos de Ferro" "%EDGE%" --app="%GAME_URL%" --start-maximized --allow-file-access-from-files --no-first-run
  exit /b 0
)
if exist "%CHROME%" (
  start "Reinos de Ferro" "%CHROME%" --app="%GAME_URL%" --start-maximized --allow-file-access-from-files --no-first-run
  exit /b 0
)
start "Reinos de Ferro" "%GAME%"
