@echo off
setlocal EnableExtensions

rem One-click installer for Python 3.12 + latest MediaPipe on 64-bit Windows.
rem Save this file as ANSI or UTF-8 without Korean text issues; all output is ASCII.

net session >nul 2>&1
if not "%errorlevel%"=="0" (
    echo Requesting administrator permission...
    set "SCRIPT_TO_RUN=%~f0"
    powershell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -FilePath $env:SCRIPT_TO_RUN -WorkingDirectory (Split-Path -Path $env:SCRIPT_TO_RUN) -Verb RunAs"
    exit /b
)

set "PY_MAJOR_MINOR=3.12"
set "PY_VER=3.12.10"
set "PRIMARY_PY_DIR=C:\Python312"
set "FALLBACK_PY_DIR=C:\MediaPipePython312"
set "PY_DIR=%PRIMARY_PY_DIR%"
set "PY_EXE=%PY_DIR%\python.exe"
set "PY_INSTALLER=%TEMP%\python-%PY_VER%-amd64.exe"
set "PY_URL=https://www.python.org/ftp/python/%PY_VER%/python-%PY_VER%-amd64.exe"

echo.
echo ============================================================
echo Setting up Python %PY_MAJOR_MINOR% and MediaPipe
echo Installing latest compatible MediaPipe globally
echo ============================================================
echo.

echo Looking for an existing Python %PY_MAJOR_MINOR%...
call :resolve_python quiet
if not errorlevel 1 (
    echo Using Python at %PY_EXE%
) else (
    call :choose_install_target
    if errorlevel 1 goto fail

    echo Downloading Python installer...
    powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri '%PY_URL%' -OutFile '%PY_INSTALLER%'"
    if errorlevel 1 goto fail

    echo Running Python installer to %PY_DIR%...
    "%PY_INSTALLER%" /quiet InstallAllUsers=1 PrependPath=1 Include_pip=1 Include_launcher=1 Include_test=0 TargetDir="%PY_DIR%"
    if errorlevel 1 goto fail
)

rem Installer PATH changes apply to future shells, so resolve python.exe here.
echo Locating installed Python...
call :wait_for_python 30
if errorlevel 1 goto fail

echo.
echo Making Python %PY_MAJOR_MINOR% first on PATH for new CMD windows...
call :persist_python_path
if errorlevel 1 goto fail

echo.
echo Updating PATH for this command window...
set "PATH=%PY_DIR%;%PY_DIR%\Scripts;%PATH%"

echo.
echo Verifying Python...
"%PY_EXE%" --version
if errorlevel 1 goto fail

echo.
echo Upgrading pip...
"%PY_EXE%" -m pip install --upgrade pip
if errorlevel 1 goto fail

echo.
echo Installing latest MediaPipe globally...
"%PY_EXE%" -m pip install --upgrade mediapipe
if errorlevel 1 goto fail

echo.
echo Verifying MediaPipe import...
"%PY_EXE%" -c "import sys, mediapipe as mp; print('Python:', sys.version.split()[0]); print('MediaPipe:', mp.__version__)"
if errorlevel 1 goto fail

echo.
echo ============================================================
echo Done.
echo New CMD windows can use:
echo   python --version
echo   python -c "import mediapipe as mp; print(mp.__version__)"
echo ============================================================
echo.
pause
exit /b 0

:choose_install_target
set "PY_DIR=%PRIMARY_PY_DIR%"
set "PY_EXE=%PY_DIR%\python.exe"
if exist "%PY_DIR%" (
    echo Found %PY_DIR%, but it is not a usable Python %PY_MAJOR_MINOR% install.
    echo Leaving it unchanged and using %FALLBACK_PY_DIR% instead.
    set "PY_DIR=%FALLBACK_PY_DIR%"
    set "PY_EXE=%PY_DIR%\python.exe"
)
if exist "%PY_DIR%" (
    call :is_python_312 "%PY_EXE%"
    if not errorlevel 1 exit /b 0
    echo %PY_DIR% already exists but is not a usable Python %PY_MAJOR_MINOR% install.
    echo Rename or remove that folder manually, then run this file again.
    exit /b 1
)
exit /b 0

:persist_python_path
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; $pythonDir=$env:PY_DIR; $scriptsDir=Join-Path $pythonDir 'Scripts'; $machine=[Environment]::GetEnvironmentVariable('Path','Machine'); $parts=@(); if($machine){ $parts=$machine -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ } }; $wanted=@($pythonDir,$scriptsDir); $wantedNorm=$wanted | ForEach-Object { [IO.Path]::GetFullPath($_).TrimEnd('\').ToLowerInvariant() }; $filtered=@(); foreach($p in $parts){ try { $norm=[IO.Path]::GetFullPath([Environment]::ExpandEnvironmentVariables($p)).TrimEnd('\').ToLowerInvariant() } catch { $norm=$p.TrimEnd('\').ToLowerInvariant() }; if($wantedNorm -notcontains $norm){ $filtered += $p } }; [Environment]::SetEnvironmentVariable('Path',(($wanted + $filtered) -join ';'),'Machine')"
if errorlevel 1 exit /b 1
exit /b 0

:wait_for_python
set "WAIT_SECONDS=%~1"
if "%WAIT_SECONDS%"=="" set "WAIT_SECONDS=30"
for /l %%I in (1,1,%WAIT_SECONDS%) do (
    call :resolve_python quiet
    if not errorlevel 1 exit /b 0
    timeout /t 1 /nobreak >nul
)
call :resolve_python
exit /b %errorlevel%

:resolve_python
for %%P in (
    "%PY_EXE%"
    "%PRIMARY_PY_DIR%\python.exe"
    "%FALLBACK_PY_DIR%\python.exe"
    "%ProgramFiles%\Python312\python.exe"
    "%LocalAppData%\Programs\Python\Python312\python.exe"
    "%ProgramFiles(x86)%\Python312\python.exe"
) do (
    call :is_python_312 "%%~P"
    if not errorlevel 1 (
        set "PY_EXE=%%~P"
        for %%D in ("%%~dpP.") do set "PY_DIR=%%~fD"
        exit /b 0
    )
)
for /f "delims=" %%P in ('py -3.12 -c "import sys; print(sys.executable)" 2^>nul') do (
    call :is_python_312 "%%~P"
    if not errorlevel 1 (
        set "PY_EXE=%%~P"
        for %%D in ("%%~dpP.") do set "PY_DIR=%%~fD"
        exit /b 0
    )
)
for /f "delims=" %%P in ('where python 2^>nul') do (
    call :is_python_312 "%%~P"
    if not errorlevel 1 (
        set "PY_EXE=%%~P"
        for %%D in ("%%~dpP.") do set "PY_DIR=%%~fD"
        exit /b 0
    )
)
if /i "%~1"=="quiet" exit /b 1
echo Could not find Python %PY_VER% after installation.
echo Expected path: %PY_DIR%\python.exe
echo Open a new CMD and try: py -3.12 --version
exit /b 1

:is_python_312
if not exist "%~1" exit /b 1
"%~1" -c "import sys; raise SystemExit(0 if sys.version_info[:2] == (3, 12) else 1)" >nul 2>&1
exit /b %errorlevel%

:fail
echo.
echo ============================================================
echo Installation failed.
echo Check your internet connection and make sure Windows is 64-bit.
echo If this window was not elevated, right-click and run as administrator.
echo ============================================================
echo.
pause
exit /b 1
