@echo off
REM Questions MCP Server publish script (ASCII, simple, venv-friendly)

chcp 65001 >nul
setlocal

echo [1/4] Checking required tools...

REM assume you already activated .venv in the shell
REM just check commands exist; if not, fail with a clear message

uv --version >nul 2>&1
IF ERRORLEVEL 1 (
    echo [ERROR] Command "uv" not found. Please activate your virtual environment and install uv.
    goto END_ERROR
)

twine --version >nul 2>&1
IF ERRORLEVEL 1 (
    echo [ERROR] Command "twine" not found. Please activate your virtual environment and install twine.
    goto END_ERROR
)

echo [OK] Tools are available.
echo.

echo [2/4] Reading version from pyproject.toml...

IF NOT EXIST pyproject.toml (
    echo [ERROR] pyproject.toml not found.
    goto END_ERROR
)

set "VERSION="
for /f "tokens=3 delims= " %%A in ('findstr /B /C:"version = " pyproject.toml') do set "VERSION=%%A"

rem strip double quotes from version value
set "VERSION=%VERSION:"=%"

IF NOT DEFINED VERSION (
    echo [ERROR] Failed to parse version from pyproject.toml.
    goto END_ERROR
)

echo   Version: %VERSION%
echo.

echo [3/4] Cleaning old build artifacts...

IF EXIST dist  rmdir /s /q dist
IF EXIST build rmdir /s /q build

for /d %%D in (*.egg-info) do (
    rmdir /s /q "%%D"
)

echo [OK] Clean.
echo.

echo [3/4] Building package with uv (may be verbose)...

uv build
IF ERRORLEVEL 1 (
    echo [ERROR] uv build failed.
    goto END_ERROR
)

echo [OK] Build finished.
echo.

echo [4/4] Upload target:
echo   1. PyPI
echo   2. TestPyPI
set "UPLOAD_TARGET="
set /p UPLOAD_TARGET=Select target (1/2, default 2): 

IF "%UPLOAD_TARGET%"=="" set "UPLOAD_TARGET=2"

echo.
IF "%UPLOAD_TARGET%"=="1" goto DO_PYPI
goto DO_TESTPYPI

:DO_PYPI
echo Uploading to PyPI...
twine upload dist/*
IF ERRORLEVEL 1 (
    echo [ERROR] twine upload to PyPI failed.
    goto END_ERROR
)
set "PYPI_URL=https://pypi.org/project/questions-mcp-server/"
set "INSTALL_COMMAND=pip install questions-mcp-server==%VERSION%"
goto AFTER_UPLOAD

:DO_TESTPYPI
echo Uploading to TestPyPI...
twine upload --repository testpypi dist/*
IF ERRORLEVEL 1 (
    echo [ERROR] twine upload to TestPyPI failed.
    goto END_ERROR
)
set "PYPI_URL=https://test.pypi.org/project/questions-mcp-server/"
set "INSTALL_COMMAND=pip install --index-url https://test.pypi.org/simple/ questions-mcp-server==%VERSION%"

:AFTER_UPLOAD
echo.
echo [OK] Upload step finished.
echo.

echo ===== Publish finished =====
echo   Version : %VERSION%
echo   Project : %PYPI_URL%
echo.
echo You can install this version with:
echo   %INSTALL_COMMAND%
echo.
goto END_OK

:END_ERROR
echo.
echo ===== Publish FAILED, please check the error above =====
echo.
exit /b 1

:END_OK
pause
