@echo off
title DCOG-OS Client Launcher
cd /d "%~dp0"

:: DCOG-OS Client launcher (Windows)
::
:: TWO MODES:
::   1) OWNER (run your own brain):     start.bat
::        -> runs the local daemon (dcog-commander.exe) on 5318, opens the end-user panel (/app/).
::   2) FRIEND (connect to owner brain): start.bat https://OWNER-TUNNEL.trycloudflare.com
::        -> does NOT run a daemon; opens the owner's /app/ panel directly (same-origin).
::
:: Owner: run  expose-brain (cloudflared)  and share the https://... URL with friends.

set "BRAIN_URL=%~1"
if "%BRAIN_URL%"=="" set "BRAIN_URL=%DCOG_BRAIN_URL%"
set BINARY_NAME=dcog-commander.exe
if "%DCOG_PORT%"=="" (set PORT=5318) else (set PORT=%DCOG_PORT%)

:: -- FRIEND MODE --
if not "%BRAIN_URL%"=="" (
    echo Connecting to the owner's brain: %BRAIN_URL%
    start "" "%BRAIN_URL%/app/"
    echo If the page asks for an address, paste: %BRAIN_URL%
    timeout /t 3 >nul
    exit /b 0
)

:: -- OWNER MODE --
echo Starting DCOG-OS Sovereign Daemon (port %PORT%)...

if not exist "%BINARY_NAME%" (
    if exist "..\src-tauri\target\release\%BINARY_NAME%" (
        echo Copying release binary...
        copy "..\src-tauri\target\release\%BINARY_NAME%" .
    ) else if exist "..\src-tauri\target\debug\%BINARY_NAME%" (
        echo Copying debug binary...
        copy "..\src-tauri\target\debug\%BINARY_NAME%" .
    ) else (
        echo ERROR: %BINARY_NAME% not found. Build first:
        echo   cargo build --manifest-path ..\src-tauri\Cargo.toml --release
        pause
        exit /b 1
    )
)

:: End-user device: god panel and all god authority are DISABLED (client mode).
set DCOG_CLIENT_MODE=1
start "" "%BINARY_NAME%"

echo Waiting for the daemon to come up on port %PORT%...
timeout /t 3 /nobreak >nul 2>&1 || ping 127.0.0.1 -n 4 >nul

:: Open the END-USER panel only. (God panel is DISABLED on this device - client mode.)
start "" "http://127.0.0.1:%PORT%/app/"

echo.
echo DCOG-OS started (end-user mode).
echo   Panel: http://127.0.0.1:%PORT%/app/
echo You can close this window; the daemon keeps running (stop it from Task Manager).
timeout /t 6
