@echo off
title SAMI Caddy API Server - Debug Mode
echo ========================================
echo SAMI Caddy API Server - Debug Mode
echo ========================================

cd /d "%~dp0"
echo Current directory: %CD%

echo.
echo Checking Node.js...
node --version
if %errorlevel% neq 0 (
    echo ERROR: Node.js not found
    pause
    exit /b 1
)

echo.
echo Checking files...
if exist "caddy-api.js" (
    echo ✓ caddy-api.js found
) else (
    echo ✗ caddy-api.js NOT found
    pause
    exit /b 1
)

if exist "package.json" (
    echo ✓ package.json found
) else (
    echo ✗ package.json NOT found
    pause
    exit /b 1
)

if exist "caddy-manager.ps1" (
    echo ✓ caddy-manager.ps1 found
) else (
    echo ✗ caddy-manager.ps1 NOT found
    pause
    exit /b 1
)

echo.
echo Installing dependencies...
npm install
if %errorlevel% neq 0 (
    echo ERROR: npm install failed
    pause
    exit /b 1
)

echo.
echo ========================================
echo Starting server with error capture...
echo ========================================
echo Server will run on: http://localhost:3001
echo Test endpoint: http://localhost:3001/api/caddy/test
echo.
echo If server starts successfully, you'll see "Caddy API server running..."
echo Press Ctrl+C to stop the server
echo ========================================
echo.

REM Capture both stdout and stderr
node caddy-api.js 2>&1
set SERVER_EXIT_CODE=%errorlevel%

echo.
echo ========================================
echo Server exited with code: %SERVER_EXIT_CODE%
echo ========================================

if %SERVER_EXIT_CODE% neq 0 (
    echo ERROR: Server failed to start or crashed
    echo Check the error messages above
) else (
    echo Server stopped normally
)

echo.
echo Press any key to close this window...
pause >nul