@echo off
title Start Node
cd /d "%~dp0"
for /f "usebackq delims=" %%V in ("bin\version.txt") do set "NODE_VERSION=%%V"
title AI-Network Start - %NODE_VERSION%

echo ==============================================
echo       AI-Network Node %NODE_VERSION%
echo ==============================================
echo.

:: Check for updates before starting
echo Checking for updates...
powershell -ExecutionPolicy Bypass -File "bin\check-update.ps1"
if %ERRORLEVEL% EQU 1 (
    echo Restarting with updated version...
    start "" "%~f0"
    exit /b
)
echo.

echo Killing any old abandoned background processes...
powershell -Command "Stop-Process -Name 'proxy-agent', 'frpc', 'gost' -Force -ErrorAction SilentlyContinue" >nul 2>&1

echo Sweeping old .tmp session folders...
if exist ".tmp\session_*" for /d %%D in (".tmp\session_*") do rmdir /s /q "%%D" >nul 2>&1
if exist ".tmp\active_session.txt" del /q ".tmp\active_session.txt" >nul 2>&1

:: Generate unique session ID using date and time safely
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /value') do set datetime=%%I
set SESSION_NAME=session_%datetime:~0,14%

echo Creating isolated session environment: %SESSION_NAME%...
if not exist ".tmp" mkdir ".tmp"
mkdir ".tmp\%SESSION_NAME%"

:: Copy bin contents to the fresh session folder
xcopy "bin\*" ".tmp\%SESSION_NAME%\" /E /Y /Q >nul

:: Save active session pointer so Monitor and Stop know where to look
echo %SESSION_NAME% > ".tmp\active_session.txt"

:: Run from the new isolated folder
cd /d ".tmp\%SESSION_NAME%"
call start_all.bat

