param(
    [Parameter(ValueFromRemainingArguments = $true)]
    [string[]]$PipArgs
)

$commonScript = Join-Path $PSScriptRoot "script-common.ps1"
if (-not (Test-Path $commonScript)) {
    throw "Missing helper script: $commonScript"
}
. $commonScript

$repoRoot = Resolve-JournalRepoRoot -StartPath $PSScriptRoot

Initialize-JournalPipEnv -RepoRoot $repoRoot
Clear-JournalProxyEnv

if (-not $PipArgs -or $PipArgs.Count -eq 0) {
    Write-Host "Usage: ./scripts/pip-min.ps1 <pip args>"
    Write-Host "Example: ./scripts/pip-min.ps1 install --index-url https://pypi.org/simple faster-whisper"
    exit 2
}

# Default install target to a repo-local directory so installs do not require
# user/site-packages write access on constrained hosts.
$effectiveArgs = @($PipArgs)
$firstArg = $effectiveArgs[0].ToLowerInvariant()
if ($firstArg -eq "install") {
    # On Windows, map PyAudio to pyaudiowpatch (wheel available for newer CPython),
    # avoiding source builds that require PortAudio headers/toolchain wiring.
    for ($i = 0; $i -lt $effectiveArgs.Count; $i++) {
        $arg = $effectiveArgs[$i]
        if ($arg -match '^(?i)pyaudio($|[<>=!~].*)') {
            $suffix = $arg.Substring(7)
            $effectiveArgs[$i] = "pyaudiowpatch$suffix"
            Write-Host "pip-min: mapped '$arg' -> '$($effectiveArgs[$i])' on Windows."
        }
    }

    $hasTarget = $effectiveArgs -contains "--target" -or $effectiveArgs -contains "-t" -or $effectiveArgs -contains "--prefix"
    if (-not $hasTarget) {
        $effectiveArgs = $effectiveArgs | Where-Object { $_ -ne "--user" }
        $localTarget = Join-Path $repoRoot ".pydeps\py314"
        New-Item -ItemType Directory -Force -Path $localTarget | Out-Null
        $effectiveArgs += @("--target", $localTarget)
        Write-Host "pip-min: using local target $localTarget"
    }
}

$pipWrapper = Join-Path $PSScriptRoot "pip_safe.py"
if (Test-Path $pipWrapper) {
    & python $pipWrapper @effectiveArgs
}
else {
    & python -m pip @effectiveArgs
}
exit $LASTEXITCODE
