@echo off
chcp 65001 >nul 2>&1
title NECOCLAW
setlocal enabledelayedexpansion

set "SCRIPT_DIR=%~dp0"
set "PASS=0"
set "FAIL=0"
set "WARN=0"
set "PORT=24088"

echo.
echo   /\_/\
echo  ( o.o )  NECOCLAW Startup
echo   ^> ^^ ^<
echo.
echo ==================================================
echo   Environment Check
echo ==================================================
echo.

:: ─── 1. OS Detection ───
echo [1/8] Operating System ...
for /f "tokens=2 delims==" %%a in ('wmic os get Caption /value 2^>nul ^| findstr "Caption"') do set "OS_NAME=%%a"
for /f "tokens=2 delims==" %%a in ('wmic os get Version /value 2^>nul ^| findstr "Version"') do set "OS_VER=%%a"
for /f "tokens=2 delims==" %%a in ('wmic os get OSArchitecture /value 2^>nul ^| findstr "OSArchitecture"') do set "OS_ARCH=%%a"
if defined OS_NAME (
    echo       OK: !OS_NAME! !OS_VER! [!OS_ARCH!]
    set /a PASS+=1
) else (
    echo       OK: Windows
    set /a PASS+=1
)

:: ─── 2. Architecture Check ───
echo [2/8] Architecture ...
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" (
    echo       OK: x86_64 64-bit
    set /a PASS+=1
) else if "%PROCESSOR_ARCHITECTURE%"=="ARM64" (
    echo       OK: ARM64 64-bit
    set /a PASS+=1
) else (
    echo       WARN: %PROCESSOR_ARCHITECTURE% -- NECOCLAW requires 64-bit
    set /a WARN+=1
)

:: ─── 3. Memory Check ───
echo [3/8] Memory ...
for /f "tokens=2 delims==" %%a in ('wmic ComputerSystem get TotalPhysicalMemory /value 2^>nul ^| findstr "TotalPhysicalMemory"') do set "RAM_BYTES=%%a"
if defined RAM_BYTES (
    for /f %%m in ('powershell -NoProfile -Command "[math]::Round(%RAM_BYTES%/1MB)" 2^>nul') do set "RAM_MB=%%m"
)
if defined RAM_MB (
    echo       OK: !RAM_MB! MB total RAM
    if !RAM_MB! LSS 512 (
        echo       WARN: Less than 512 MB RAM -- may be slow
        set /a WARN+=1
    ) else (
        set /a PASS+=1
    )
) else (
    echo       OK: RAM check skipped
    set /a PASS+=1
)

:: ─── 4. Disk Space Check ───
echo [4/8] Disk Space ...
set "DISK_MB="
for /f %%m in ('powershell -NoProfile -Command "(Get-PSDrive -Name ($pwd.Drive.Name) -ErrorAction SilentlyContinue).Free / 1MB -as [int]" 2^>nul') do set "DISK_MB=%%m"
if defined DISK_MB (
    echo       OK: !DISK_MB! MB free
    if !DISK_MB! LSS 200 (
        echo       WARN: Less than 200 MB free
        set /a WARN+=1
    ) else (
        set /a PASS+=1
    )
) else (
    echo       OK: Disk check skipped
    set /a PASS+=1
)

:: ─── 5. Find Executable ───
echo [5/8] NECOCLAW Binary ...
set "NECO="
if exist "%SCRIPT_DIR%necoclaw.exe" (
    set "NECO=%SCRIPT_DIR%necoclaw.exe"
)
if not defined NECO (
    if exist "%USERPROFILE%\.necoclaw\necoclaw.exe" set "NECO=%USERPROFILE%\.necoclaw\necoclaw.exe"
)
if defined NECO (
    echo       OK: Found necoclaw.exe
    echo       Path: !NECO!
    set /a PASS+=1
) else (
    echo       FAIL: necoclaw.exe not found!
    echo       Expected: %SCRIPT_DIR%necoclaw.exe
    set /a FAIL+=1
    goto :show_result
)

:: ─── 6. Config File Check ───
echo [6/8] Configuration ...
if exist "%SCRIPT_DIR%config.yaml" (
    echo       OK: config.yaml found
    echo       Path: %SCRIPT_DIR%config.yaml
    set /a PASS+=1
    for /f "tokens=2 delims=: " %%p in ('findstr /R "port:" "%SCRIPT_DIR%config.yaml" 2^>nul') do (
        set "CFG_PORT=%%p"
    )
    if defined CFG_PORT (
        for /f "tokens=1" %%q in ("!CFG_PORT!") do set "PORT=%%q"
    )
    echo       WebUI port: !PORT!
) else (
    echo       WARN: No config.yaml -- using defaults
    set /a WARN+=1
)

:: ─── 7. Port Availability ───
echo [7/8] Port !PORT! ...
set "PORT_BUSY=0"
netstat -ano 2>nul | findstr ":!PORT! " | findstr "LISTENING" >nul 2>&1 && set "PORT_BUSY=1"
if "!PORT_BUSY!"=="1" (
    echo       WARN: Port !PORT! is already in use!
    echo       To check: netstat -ano ^| findstr :!PORT!
    set /a WARN+=1
) else (
    echo       OK: Port !PORT! is available
    set /a PASS+=1
)

:: ─── 8. Data Directories ───
echo [8/8] Data Directories ...
set "DATA_DIR=%SCRIPT_DIR%"
set "DIR_CREATED=0"
set "DIR_EXISTS=0"
call :check_dir workspace
call :check_dir workspace\sessions
call :check_dir workspace\cron
call :check_dir workspace\projects
call :check_dir workspace\screenshots
call :check_dir skills
call :check_dir uploads
call :check_dir genetic
call :check_dir logs
echo       OK: !DIR_EXISTS! exist, !DIR_CREATED! newly created
set /a PASS+=1

:: ─── Result Summary ───
:show_result
echo.
echo --------------------------------------------------
echo   Check Results:  !PASS! passed / !WARN! warnings / !FAIL! failed
echo --------------------------------------------------

if !FAIL! GTR 0 (
    echo.
    echo   FATAL: !FAIL! check failed. Cannot start.
    echo.
    goto :end
)

if !WARN! GTR 0 (
    echo.
    echo   !WARN! warning. NECOCLAW will try to start anyway.
)

echo.
echo ==================================================
echo   Starting NECOCLAW ...
echo ==================================================
echo.
echo   Executable: !NECO!
echo   Data Dir:   %DATA_DIR%
echo   WebUI:      http://localhost:!PORT!
echo   Press Ctrl+C to stop
echo.

:: ─── Start background health check via inline PowerShell ───
set "HC_CMD=$p=!PORT!; $n=0; Start-Sleep 2; while($n -lt 30){try{$r=Invoke-WebRequest -Uri http://localhost:$p/api/health -UseBasicParsing -TimeoutSec 2 -EA Stop; if($r.StatusCode -eq 200){Write-Host ''; Write-Host '  [WebUI] Health Check: OK' -Fore Green; Write-Host '  [WebUI] Opening browser...' -Fore Green; Write-Host ''; Start-Process http://localhost:$p; exit}}catch{}; Start-Sleep 2; $n+=2; Write-Host \"  [health] waiting... ($n/30s)\" -Fore DarkGray}; Write-Host ''; Write-Host '  [WebUI] FAILED: No response after 30s' -Fore Red; Write-Host '  Check: netstat -ano | findstr :$p' -Fore Red; Write-Host ''"
start /b powershell -NoProfile -ExecutionPolicy Bypass -Command "!HC_CMD!"

:: Start the agent (blocks until Ctrl+C)
"!NECO!" start

:: Agent exited
set "EXIT_CODE=!errorlevel!"
echo.
if !EXIT_CODE! equ 0 (
    echo   NECOCLAW stopped normally.
) else (
    echo   NECOCLAW exited with code !EXIT_CODE!
    echo   Check logs above for error details.
)

:end
echo.
pause
exit /b 0

:: ─── Helper: check/create a directory ───
:check_dir
if not exist "%DATA_DIR%%~1" (
    mkdir "%DATA_DIR%%~1" 2>nul
    if exist "%DATA_DIR%%~1" (
        set /a DIR_CREATED+=1
    )
) else (
    set /a DIR_EXISTS+=1
)
goto :eof
