[CmdletBinding()]
param(
    [string]$PythonCommand,
    [switch]$UpgradePip
)

$ErrorActionPreference = "Stop"

function Resolve-QgisPythonCommand {
    param([string]$ExplicitCommand)

    if ($ExplicitCommand) {
        return $ExplicitCommand
    }

    $candidates = @()

    foreach ($commandName in @("python-qgis-ltr.bat", "python-qgis.bat")) {
        $resolved = Get-Command $commandName -ErrorAction SilentlyContinue
        if ($resolved) {
            $candidates += $resolved.Source
        }
    }

    foreach ($root in @($env:OSGEO4W_ROOT, "C:\OSGeo4W")) {
        if (-not [string]::IsNullOrWhiteSpace($root)) {
            $candidates += Join-Path $root "bin\python-qgis-ltr.bat"
            $candidates += Join-Path $root "bin\python-qgis.bat"
        }
    }

    foreach ($programFilesRoot in @($env:ProgramFiles, ${env:ProgramFiles(x86)})) {
        if (-not [string]::IsNullOrWhiteSpace($programFilesRoot) -and (Test-Path $programFilesRoot)) {
            $candidates += Get-ChildItem -Path $programFilesRoot -Filter "python-qgis*.bat" -Recurse -ErrorAction SilentlyContinue |
                Sort-Object FullName -Descending |
                Select-Object -ExpandProperty FullName
        }
    }

    $resolvedCandidate = $candidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1
    if ($resolvedCandidate) {
        return $resolvedCandidate
    }

    throw @"
Could not locate the QGIS Python command automatically.

Run this script again with -PythonCommand, for example:
  .\install_qgis_dependencies.ps1 -PythonCommand "C:\OSGeo4W\bin\python-qgis-ltr.bat"
"@
}

$pluginRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$requirementsPath = Join-Path $pluginRoot "requirements-qgis.txt"

if (-not (Test-Path $requirementsPath -PathType Leaf)) {
    throw "requirements-qgis.txt not found: $requirementsPath"
}

$qgisPython = Resolve-QgisPythonCommand -ExplicitCommand $PythonCommand

Write-Host "Using QGIS Python command:" -ForegroundColor Cyan
Write-Host "  $qgisPython"

if ($UpgradePip) {
    & $qgisPython -m pip install --upgrade pip
}

& $qgisPython -m pip install -r $requirementsPath

Write-Host "Installed plugin dependencies from $requirementsPath" -ForegroundColor Green
Write-Host "You can now restart QGIS and use download/sync features."