param(
    [ValidateSet("2021", "2022", "2023", "2024", "2025", "2026")]
    [string[]]$RevitVersion,
    [switch]$All
)

$ErrorActionPreference = "Stop"
$packageRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$payloadRoot = Join-Path $packageRoot "payload"
$manifestPath = Join-Path $packageRoot "release-manifest.json"
$supported = @("2021", "2022", "2023", "2024", "2025", "2026")
$externalToolsRoot = Join-Path $packageRoot "external-tools"

function Copy-TreeFiles([string]$Source, [string]$Destination) {
    Get-ChildItem -LiteralPath $Source -File -Recurse | ForEach-Object {
        $relative = $_.FullName.Substring($Source.Length).TrimStart("\", "/")
        $target = Join-Path $Destination $relative
        New-Item -ItemType Directory -Path (Split-Path -Parent $target) -Force | Out-Null
        Copy-Item -LiteralPath $_.FullName -Destination $target -Force
    }
}

if (-not (Test-Path -LiteralPath $manifestPath)) {
    throw "release-manifest.json is missing. The package authenticity cannot be verified."
}
$manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
foreach ($property in $manifest.files.PSObject.Properties) {
    $candidate = Join-Path $packageRoot $property.Name.Replace("/", "\")
    if (-not (Test-Path -LiteralPath $candidate)) {
        throw "Package file is missing: $($property.Name)"
    }
    $actual = (Get-FileHash -LiteralPath $candidate -Algorithm SHA256).Hash.ToLowerInvariant()
    if ($actual -ne [string]$property.Value) {
        throw "Checksum verification failed: $($property.Name)"
    }
}
Write-Host "Package checksums verified." -ForegroundColor Green

if (-not $RevitVersion -or $RevitVersion.Count -eq 0) {
    $detected = @(
        $supported | Where-Object {
            Test-Path -LiteralPath "C:\Program Files\Autodesk\Revit $_\Revit.exe"
        }
    )

    if ($All) {
        $RevitVersion = $supported
    }
    elseif ($detected.Count -gt 0) {
        $RevitVersion = $detected
    }
    else {
        throw "Revit 2021-2026 was not detected. Run with -RevitVersion 2024."
    }
}

$addinsRoot = Join-Path $env:APPDATA "Autodesk\Revit\Addins"
foreach ($version in $RevitVersion) {
    $source = Join-Path $payloadRoot $version
    if (-not (Test-Path -LiteralPath $source)) {
        throw "The package does not contain a Revit $version build."
    }

    $versionRoot = Join-Path $addinsRoot $version
    $pluginRoot = Join-Path $versionRoot "INPUG BIM"
    New-Item -ItemType Directory -Path $pluginRoot -Force | Out-Null

    Copy-TreeFiles $source $pluginRoot
    if (Test-Path -LiteralPath $externalToolsRoot) {
        Copy-TreeFiles $externalToolsRoot (Join-Path $pluginRoot "ExternalTools")
    }
    Copy-Item -LiteralPath (Join-Path $packageRoot "INPUG BIM.addin") -Destination $versionRoot -Force

    $processorTemplate = Join-Path $externalToolsRoot "ModelExportProcessor\INPLUG Export Processor.addin.template"
    $processorSource = Join-Path $externalToolsRoot "ModelExportProcessor\$version\InpugModelExportProcessor.dll"
    $processorAssembly = $null
    if (Test-Path -LiteralPath $processorSource) {
        # Use a content-addressed file name because Revit locks a loaded add-in
        # DLL. The next background Revit process can switch versions immediately.
        $processorHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $processorSource).Hash.ToLowerInvariant()
        $processorName = "InpugModelExportProcessor.$($processorHash.Substring(0, 12)).dll"
        $processorAssembly = Join-Path $pluginRoot "ExternalTools\ModelExportProcessor\$version\$processorName"
        Copy-Item -LiteralPath $processorSource -Destination $processorAssembly -Force
    }
    if ((Test-Path -LiteralPath $processorTemplate) -and
        $processorAssembly -and (Test-Path -LiteralPath $processorAssembly)) {
        $processorManifest = Get-Content -LiteralPath $processorTemplate -Raw
        $processorManifest = $processorManifest.Replace("__ASSEMBLY__", $processorAssembly)
        Set-Content -LiteralPath (Join-Path $versionRoot "INPLUG Export Processor.addin") `
            -Value $processorManifest -Encoding UTF8
    }

    Write-Host "INPLUG.BIM installed for Revit $version" -ForegroundColor Green
}

Write-Host ""
Write-Host "Done. Start Revit and open the INPLUG BIM ribbon tab." -ForegroundColor Cyan
Write-Host "Use your inplug.pro/bim account for activation."
