@echo off

REM Get the directory where this batch file is located
set "BAT_DIR=%~dp0"
set "BAT_DIR=%BAT_DIR:~0,-1%"

REM If running from dist directory, go up one level
if "%BAT_DIR:~-4%"=="dist" (
    set "APP_DIR=%BAT_DIR%\.."
    cd /d "%APP_DIR%"
    set "APP_DIR=%CD%"
) else (
    set "APP_DIR=%BAT_DIR%"
)

set DATA_DIR=%APP_DIR%\data
set ZIP_FILE=%DATA_DIR%\web.exe
set TOOLS_DIR=%DATA_DIR%\Tools
set PORT_FILE=%APP_DIR%\port
set KEY_FILE=%DATA_DIR%\key
set PYC_FILE=%TOOLS_DIR%\http_server.pyc

REM Read port from port file, default to 50080 if not found
set PORT=50080
if exist "%PORT_FILE%" (
    for /f "usebackq tokens=*" %%i in ("%PORT_FILE%") do (
        set "PORT=%%i"
        goto :port_read
    )
)
:port_read
REM Remove any whitespace from port
set "PORT=%PORT: =%"

REM Detect system architecture
set "ARCH="
if "%PROCESSOR_ARCHITEW6432%"=="ARM64" (
    set "ARCH=arm64"
) else if "%PROCESSOR_ARCHITECTURE%"=="ARM64" (
    set "ARCH=arm64"
) else if "%PROCESSOR_ARCHITEW6432%"=="AMD64" (
    set "ARCH=amd64"
) else if "%PROCESSOR_ARCHITECTURE%"=="AMD64" (
    set "ARCH=amd64"
) else if "%PROCESSOR_ARCHITECTURE%"=="x86" (
    set "ARCH=win32"
) else (
    REM Fallback: try to detect via wmic
    for /f "tokens=*" %%i in ('wmic os get osarchitecture /value 2^>nul ^| findstr "="') do (
        set "%%i"
    )
    if "%OSArchitecture%"=="64-bit" (
        set "ARCH=amd64"
    ) else (
        set "ARCH=win32"
    )
)

REM Set Python path based on architecture
set "PYTHON_DIR=%TOOLS_DIR%\python\python-3.14.2-embed-%ARCH%"
set "PYTHON_EXE=%PYTHON_DIR%\python.exe"

if not exist "%ZIP_FILE%" (
    echo Error: web.exe not found
    pause
    exit /b 1
)

if not exist "%PYC_FILE%" (
    echo Error: http_server.pyc not found
    echo Please run compile.bat first to compile the Python script
    pause
    exit /b 1
)

if not exist "%PYTHON_EXE%" (
    echo Error: Python not found for architecture: %ARCH%
    echo Expected path: %PYTHON_EXE%
    pause
    exit /b 1
)

"%PYTHON_EXE%" "%TOOLS_DIR%\run_pyc.py" "%PYC_FILE%" %PORT% "%ZIP_FILE%" "%KEY_FILE%"
if errorlevel 1 (
    pause
    exit /b 1
)

pause
