@echo off
setlocal enabledelayedexpansion

:: uvx installation script - Windows version
:: This script installs uvx and configures environment variables

:: Check for administrator privileges
net session >nul 2>&1
if %errorLevel% == 0 (
    goto :Admin
) else (
    echo Administrator privileges required
    echo Please run this script as administrator
    pause
    exit /b
)

:Admin
echo Starting uvx installation...

:: Check if uvx is already installed
where uvx >nul 2>&1
if %errorLevel% equ 0 (
    echo uvx is already installed, version:
    uvx --version
    goto :EOF
)

:: Create temporary directory
set "TEMP_DIR=%TEMP%\uvx_install"
if exist "%TEMP_DIR%" rd /s /q "%TEMP_DIR%"
mkdir "%TEMP_DIR%"
cd /d "%TEMP_DIR%"

:: Download and install uvx
echo Downloading uvx...

:: Determine system architecture
echo Detecting system architecture...
set "ARCH=unknown"

:: Check system architecture
if defined PROCESSOR_ARCHITEW6432 (
    :: Running 32-bit process on 64-bit system
    set "ARCH=x86_64"
) else if "%PROCESSOR_ARCHITECTURE%"=="AMD64" (
    :: Native 64-bit process
    set "ARCH=x86_64"
) else if "%PROCESSOR_ARCHITECTURE%"=="ARM64" (
    :: ARM 64-bit
    set "ARCH=aarch64"
) else if "%PROCESSOR_ARCHITECTURE%"=="x86" (
    :: 32-bit system
    set "ARCH=i686"
)

if "%ARCH%"=="unknown" (
    echo Unable to determine system architecture
    goto :Cleanup
)

echo Detected architecture: %ARCH%

:: Set download URL based on architecture
set "UV_VERSION=0.6.14"
if "%ARCH%"=="x86_64" (
    set "DOWNLOAD_URL=https://github.com/astral-sh/uv/releases/download/%UV_VERSION%/uv-x86_64-pc-windows-msvc.zip"
    set "CHECKSUM_URL=https://github.com/astral-sh/uv/releases/download/%UV_VERSION%/uv-x86_64-pc-windows-msvc.zip.sha256"
) else if "%ARCH%"=="aarch64" (
    set "DOWNLOAD_URL=https://github.com/astral-sh/uv/releases/download/%UV_VERSION%/uv-aarch64-pc-windows-msvc.zip"
    set "CHECKSUM_URL=https://github.com/astral-sh/uv/releases/download/%UV_VERSION%/uv-aarch64-pc-windows-msvc.zip.sha256"
) else if "%ARCH%"=="i686" (
    set "DOWNLOAD_URL=https://github.com/astral-sh/uv/releases/download/%UV_VERSION%/uv-i686-pc-windows-msvc.zip"
    set "CHECKSUM_URL=https://github.com/astral-sh/uv/releases/download/%UV_VERSION%/uv-i686-pc-windows-msvc.zip.sha256"
)

echo Downloading from: %DOWNLOAD_URL%

:: Download the zip file using curl
curl -L -o "uv.zip" "%DOWNLOAD_URL%"

:: Download the checksum file for the specific architecture
curl -L -o "uv.zip.sha256" "%CHECKSUM_URL%"

:: Check if both files exist and have a size greater than 0
if not exist "uv.zip" (
    echo Failed to download uvx: File not found
    goto :Cleanup
)

if not exist "uv.zip.sha256" (
    echo Failed to download checksum file
    goto :Cleanup
)

for %%A in ("uv.zip") do if %%~zA==0 (
    echo Failed to download uvx: File is empty
    goto :Cleanup
)

for %%A in ("uv.zip.sha256") do if %%~zA==0 (
    echo Failed to download checksum file: File is empty
    goto :Cleanup
)

:: Verify checksum
echo Verifying checksum...
certutil -hashfile "uv.zip" SHA256 > "%TEMP_DIR%\actual_checksum.txt"
for /f "tokens=1" %%A in ('type "%TEMP_DIR%\actual_checksum.txt" ^| findstr /v "CertUtil"') do set "ACTUAL_CHECKSUM=%%A"
for /f "tokens=1" %%A in ('type "uv.zip.sha256"') do set "EXPECTED_CHECKSUM=%%A"

if not "%ACTUAL_CHECKSUM%"=="%EXPECTED_CHECKSUM%" (
    echo Checksum verification failed!
    echo Expected: %EXPECTED_CHECKSUM%
    echo Actual:   %ACTUAL_CHECKSUM%
    goto :Cleanup
)

echo Download successful and checksum verified!

:: Create installation directory
set "UVX_HOME=%LOCALAPPDATA%\uv\bin"
if not exist "%UVX_HOME%" mkdir "%UVX_HOME%" 2>nul

:: Extract the zip file using VBScript (no PowerShell required)
echo Extracting uvx...

:: Create a VBScript to extract the ZIP file
echo Set objShell = CreateObject("Shell.Application") > "%TEMP_DIR%\unzip.vbs"
echo objShell.NameSpace("%UVX_HOME%").CopyHere objShell.NameSpace("%CD%\uv.zip").Items >> "%TEMP_DIR%\unzip.vbs"
echo WScript.Sleep 2000 >> "%TEMP_DIR%\unzip.vbs"

:: Run the VBScript
cscript //nologo "%TEMP_DIR%\unzip.vbs"

:: Check if extraction was successful
if not exist "%UVX_HOME%\uv.exe" (
    echo Failed to extract uv.exe
    goto :Cleanup
)

:: Add to PATH
echo Adding uv to PATH...

:: Update system PATH environment variable
echo Configuring environment variables...

:: Update PATH environment variable using registry query (similar to npx script)
for /f "skip=2 tokens=2,*" %%A in ('reg query "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /v Path 2^>nul') do (
  setx /M PATH "%%B;%UVX_HOME%"
)

:: Update PATH for current session
set "PATH=%UVX_HOME%;%PATH%"

:: Create wrapper batch files in System32 for immediate availability
echo Creating wrapper scripts for immediate availability...
set "SYSTEM32_DIR=%SystemRoot%\System32"

:: Create uv.bat wrapper
echo @echo off > "%SYSTEM32_DIR%\uv.bat"
echo "%UVX_HOME%\uv.exe" %%* >> "%SYSTEM32_DIR%\uv.bat"

:: Create uvx.bat wrapper
echo @echo off > "%SYSTEM32_DIR%\uvx.bat"
echo "%UVX_HOME%\uvx.exe" %%* >> "%SYSTEM32_DIR%\uvx.bat"

echo Successfully added uv directory to system PATH and created wrapper scripts for immediate availability

:: Verify installation
echo Verifying installation...

:: Check for uv command using wrapper scripts
where uv >nul 2>&1
if %errorLevel% equ 0 (
    echo uv installation successful!
    echo uv version:
    uv --version
    echo.
    echo You can now use uv immediately in any command prompt
) else (
    :: Check for uvx command as fallback
    where uvx >nul 2>&1
    if %errorLevel% equ 0 (
        echo uvx installation successful!
        echo uvx version:
        uvx --version
        echo.
        echo You can now use uvx immediately in any command prompt
    ) else (
        echo Warning: Commands not found in PATH, checking installation files...
        
        if exist "%UVX_HOME%\uv.exe" (
            echo uv executable exists at: %UVX_HOME%\uv.exe
            echo Wrapper script created at: %SYSTEM32_DIR%\uv.bat
            echo.
            echo You should be able to use 'uv' command immediately.
            echo If not, try running: %SYSTEM32_DIR%\uv.bat
        )
        
        if exist "%UVX_HOME%\uvx.exe" (
            echo uvx executable exists at: %UVX_HOME%\uvx.exe
            echo Wrapper script created at: %SYSTEM32_DIR%\uvx.bat
            echo.
            echo You should be able to use 'uvx' command immediately.
            echo If not, try running: %SYSTEM32_DIR%\uvx.bat
        )
    )
)

:Cleanup
:: Clean up temporary files
cd /d "%USERPROFILE%"
if exist "%TEMP_DIR%" rd /s /q "%TEMP_DIR%"

endlocal
