@echo off
chcp 65001 >CON
setlocal EnableDelayedExpansion

cd /d "%~dp0"

set APP_NAME=lesingle-aicreate-client
set APP_PORT=3001

echo ============================================================
echo   %APP_NAME%  Port: %APP_PORT%
echo ============================================================
echo.

echo [1/3] Checking port %APP_PORT%...
set "KILL_PID="
for /f "tokens=5" %%a in ('netstat -ano 2^>^&1 ^| findstr /R "LISTENING" ^| findstr /R ":%APP_PORT% "') do (
    if not "%%a"=="0" set "KILL_PID=%%a"
)
if defined KILL_PID (
    echo       Killing PID=!KILL_PID!...
    taskkill /F /PID !KILL_PID!
    timeout /t 2 /nobreak >CON
) else (
    echo       Port %APP_PORT% is free
)
echo.

echo [2/3] Checking dependencies...
if not exist "node_modules\" (
    echo       Installing dependencies...
    where pnpm >CON 2>&1
    if !errorlevel! equ 0 (
        call pnpm install
    ) else (
        echo       pnpm not found, using npm...
        call npm install
    )
    if !errorlevel! neq 0 (
        echo       [FAILED] Install failed
        goto :fail
    )
    echo.
) else (
    echo       Dependencies OK
)
echo.

echo [3/3] Starting dev server...
echo.
echo ============================================================
echo   URL:  http://localhost:%APP_PORT%
echo   Proxy: /api -^> http://localhost:8080
echo   Press Ctrl+C to stop
echo ============================================================
echo.

where pnpm >CON 2>&1
if !errorlevel! equ 0 (
    call pnpm exec vite --port %APP_PORT% --host
) else (
    call npx vite --port %APP_PORT% --host
)

goto :end

:fail
echo.
echo [Script stopped]
:end
pause
