@echo off
setlocal enabledelayedexpansion
cd /d "%~dp0"
title Manual server - %CD%

echo Starting the manual server...
echo.

set "PYEXE="
set "PYARG="

rem 1. The py launcher, installed alongside every python.org build.
py -3 -c "import sys" >nul 2>&1 && (set "PYEXE=py" & set "PYARG=-3")

rem 2. python on PATH. Skip the Windows Store alias: on a clean Windows 11 a
rem    bare `python` is an App Execution Alias under \WindowsApps\ that opens
rem    the Microsoft Store rather than running anything.
if not defined PYEXE (
  for /f "delims=" %%I in ('where python 2^>nul') do (
    if not defined PYEXE (
      echo %%I | find /i "\WindowsApps\" >nul
      if errorlevel 1 (
        "%%~fI" -c "import sys" >nul 2>&1 && set "PYEXE=%%~fI"
      )
    )
  )
)

rem 3. Nothing installed: fetch a private copy of the embeddable distribution.
rem    It is stdlib-only with site disabled, which is all this server needs.
if not defined PYEXE (
  set "EMB=%LOCALAPPDATA%\python-3.11.4-embed-amd64"
  if not exist "!EMB!\python.exe" (
    echo Python was not found on this computer.
    echo Downloading a private copy ^(about 10 MB, one time^)...
    curl -L -o "%TEMP%\python-embed.zip" "https://www.python.org/ftp/python/3.11.4/python-3.11.4-embed-amd64.zip"
    if errorlevel 1 goto :nopython
    if not exist "!EMB!" md "!EMB!"
    tar -x -f "%TEMP%\python-embed.zip" -C "!EMB!"
    if errorlevel 1 goto :nopython
    del "%TEMP%\python-embed.zip" >nul 2>&1
  )
  if exist "!EMB!\python.exe" set "PYEXE=!EMB!\python.exe"
)

if not defined PYEXE goto :nopython

rem Run in the foreground: this window is the server. Closing it stops it.
"%PYEXE%" %PYARG% serve_manual.py %*
goto :end

:nopython
echo.
echo Could not find or install Python, which this server needs.
echo Install it from https://www.python.org/downloads/ and run this file again.
echo.
pause

:end
endlocal
