# PowerShell script for installing Python dependencies

# Error handling function
function Test-LastExitCode {
    param(
        [string]$ErrorMessage
    )
    if ($LASTEXITCODE -ne 0) {
        Write-Error $ErrorMessage
        exit $LASTEXITCODE
    }
}

# Remove existing Python environments and build directory
Remove-Item -Path "$env:USERPROFILE\anaconda3\envs\virtualize" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "Virtualize.build" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "Virtualize.dist" -Recurse -Force -ErrorAction SilentlyContinue

# Create and activate Conda environment
conda create -n virtualize -y python=3.10
Test-LastExitCode "Failed to create Conda environment"

# Activate Conda environment
conda activate virtualize
Test-LastExitCode "Failed to activate Conda environment"

pip install torch<2.6 torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
Test-LastExitCode "Failed to install PyTorch"

pip install "git+https://github.com/Quidient/gsplat.git"
Test-LastExitCode "Failed to install gsplat"

pip install "git+https://github.com/Quidient/nerfstudio.git"
Test-LastExitCode "Failed to install nerfstudio"

pip install "git+https://github.com/apple/ml-depth-pro.git"
Test-LastExitCode "Failed to install ml-depth-pro"

# Install Python dependencies
pip install "git+https://github.com/Quidient/quidient-reality.git" --config-settings=cmake.define.CUDA_ARCHES=all
Test-LastExitCode "Failed to install qr"

# install quidint module from python subfolder
pip install "git+https://github.com/Quidient/quidient-reality.git#subdirectory=python"
Test-LastExitCode "Failed to install quidient"

# install runtime dependencies
pip install wxpython panda3d panda3d-simplepbr openexr pynvml drjit pandas hydra-core omegaconf natsort path qrcode
# Install Nuitka Commercial
pip install "$env:USERPROFILE\Downloads\Nuitka-commercial-main.zip"
Test-LastExitCode "Failed to install Nuitka Commercial"

# Build executable using Nuitka
Write-Host "Building executable with Nuitka..."
.\RunNuitka.ps1
Test-LastExitCode "Failed to build executable with Nuitka"
makensis.exe .\virtualize_installer.nsi
Test-LastExitCode "Failed to build installer with makensis"