$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$root = Join-Path $root '..'

$useDockerComposer = $false
$dockerRoot = $null

if (-not (Get-Command composer -ErrorAction SilentlyContinue)) {
    Write-Host "Composer non trovato localmente. Verifico se Docker è disponibile..."
    if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
        throw "Composer non trovato e Docker mancante! Installa Composer o Docker prima di generare il pacchetto."
    }

    $dockerRoot = $root -replace '\\', '/'
    if ($dockerRoot -match '^([A-Za-z]):') {
        $dockerRoot = "/$($Matches[1].ToLower())$($dockerRoot.Substring(2))"
    }

    Write-Host "Docker trovato. Root: '$dockerRoot' Test di Composer tramite container..."
    docker run --rm -v "$($dockerRoot):/app" -w /app composer:2 composer --version 2>&1
    if ($LASTEXITCODE -ne 0) {
        throw "Docker presente, ma Composer non riesce ad avviarsi tramite container. Installa Composer localmente o verifica Docker."
    }

    $useDockerComposer = $true
}

Push-Location $root
try {
    Write-Host "Installazione dipendenze PHP"
    if ($useDockerComposer) {
        docker run --rm -v "$($dockerRoot):/app" -w /app composer:2 composer install --optimize-autoloader
    }
    else {
        composer install --optimize-autoloader
    }
}
finally {
    Pop-Location
}