@echo off
setlocal

REM HyperTwist Freestyle STT Sidecar Launcher
REM Phase 1B: Runs freestyle server as external HTTP sidecar process on port 8766

set REPO_ROOT=%~dp0\..\..
set FREESTYLE_DIR=%REPO_ROOT%\.external\freestyle
set SERVER_DIR=%FREESTYLE_DIR%\apps\server
set START_SCRIPT=%REPO_ROOT%\Solvers\freestyle\freestyle_start.ts

cd /d "%SERVER_DIR%"

REM Check if pnpm is available
where pnpm >nul 2>nul
if errorlevel 1 (
    echo ERROR: pnpm not found. Install pnpm first:
    echo   npm install -g pnpm
    exit /b 1
)

REM Install dependencies if node_modules is missing
if not exist "node_modules" (
    echo Installing freestyle dependencies...
    call pnpm install
    if errorlevel 1 (
        echo ERROR: pnpm install failed
        exit /b 1
    )
)

REM Ensure tsx is available for TypeScript execution
if not exist "node_modules\.bin\tsx.cmd" (
    echo Installing tsx runtime...
    call pnpm add -D tsx
    if errorlevel 1 (
        echo ERROR: tsx install failed
        exit /b 1
    )
)

REM Start the server from source using tsx
REM The custom entry point imports the upstream Hono app and attaches a Node HTTP server.
echo Starting freestyle server on port 8766...
set PORT=8766
npx tsx "%START_SCRIPT%"
