param(
    [string]$RevitYear = "2026"
)

$ErrorActionPreference = "Stop"

function Write-QartLog {
    param([string]$Message)

    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $line = "[$timestamp] $Message"
    Add-Content -LiteralPath $script:logPath -Value $line -Encoding UTF8
}

function Unblock-QartFiles {
    param([string]$Path)

    if (!(Test-Path $Path)) {
        return
    }

    Get-ChildItem -LiteralPath $Path -Recurse -File | ForEach-Object {
        try {
            Unblock-File -LiteralPath $_.FullName -ErrorAction SilentlyContinue
        }
        catch {
        }

        try {
            Remove-Item -LiteralPath $_.FullName -Stream Zone.Identifier -ErrorAction SilentlyContinue
        }
        catch {
        }
    }
}

try {
    $desktop = [Environment]::GetFolderPath("Desktop")
    $script:logPath = Join-Path $desktop ("QART_INSTALL_" + $RevitYear + ".log")
    Set-Content -LiteralPath $script:logPath -Value "QART BIM Composer - installazione Revit $RevitYear" -Encoding UTF8

    $packageRoot = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
    $binSource = Join-Path $packageRoot ("Bin\" + $RevitYear)
    $assetsSource = Join-Path $packageRoot "Assets"

    Write-QartLog "Pacchetto: $packageRoot"
    Write-QartLog "Bin sorgente: $binSource"

    $runningRevit =
        Get-Process -Name "Revit" -ErrorAction SilentlyContinue |
        Select-Object -First 1

    if ($runningRevit) {
        throw "Revit risulta aperto. Chiudi completamente Revit $RevitYear e rilancia l'installer."
    }

    if (!(Test-Path $binSource)) {
        throw "Cartella Bin non trovata per Revit $RevitYear. Estrai completamente lo zip prima di installare."
    }

    $dllPath = Join-Path $binSource "QART.dll"

    if (!(Test-Path $dllPath)) {
        throw "QART.dll non trovata in $binSource."
    }

    Unblock-QartFiles -Path $packageRoot
    Write-QartLog "File sorgenti sbloccati."

    $addinRoot = Join-Path $env:APPDATA "Autodesk\Revit\Addins\$RevitYear"
    $installDir = Join-Path $addinRoot "QART BIM Composer"
    $manifestPath = Join-Path $addinRoot "QART BIM Composer.addin"
    $legacyManifestPath = Join-Path $addinRoot "QART.addin"

    New-Item -ItemType Directory -Force -Path $addinRoot | Out-Null

    if (Test-Path $legacyManifestPath) {
        $legacyDisabledPath =
            Join-Path $addinRoot ("QART.addin.disabled-" + (Get-Date -Format "yyyyMMdd-HHmmss"))
        Move-Item -LiteralPath $legacyManifestPath -Destination $legacyDisabledPath -Force
        Write-QartLog "Manifest legacy disattivato: $legacyDisabledPath"
    }

    if (Test-Path $installDir) {
        Remove-Item -LiteralPath $installDir -Recurse -Force
        Write-QartLog "Cartella installata precedente rimossa: $installDir"
    }

    New-Item -ItemType Directory -Force -Path $installDir | Out-Null

    Copy-Item -Path (Join-Path $binSource "*") -Destination $installDir -Recurse -Force
    Write-QartLog "DLL copiate in: $installDir"

    if (Test-Path $assetsSource) {
        $assetInstallDir = Join-Path $installDir "Assets"
        New-Item -ItemType Directory -Force -Path $assetInstallDir | Out-Null
        Copy-Item -Path (Join-Path $assetsSource "*") -Destination $assetInstallDir -Recurse -Force
        Write-QartLog "Assets copiati in: $assetInstallDir"
    }

    $installedDll = Join-Path $installDir "QART.dll"

    if (!(Test-Path $installedDll)) {
        throw "Installazione incompleta: QART.dll non risulta copiata in $installDir."
    }

    $manifestXml = @"
<?xml version="1.0" encoding="utf-8"?>
<RevitAddIns>
  <AddIn Type="Application">
    <Name>QART BIM Composer</Name>
    <Assembly>$installedDll</Assembly>
    <AddInId>7F9C0B1D-9346-4A21-8E0C-99CB8B37D7C2</AddInId>
    <FullClassName>QART.QartRibbonApp</FullClassName>
    <VendorId>QART</VendorId>
    <VendorDescription>QART BIM Composer v0.9 Beta</VendorDescription>
  </AddIn>
</RevitAddIns>
"@

    Set-Content -LiteralPath $manifestPath -Value $manifestXml -Encoding UTF8

    Unblock-QartFiles -Path $installDir
    Unblock-File -LiteralPath $manifestPath -ErrorAction SilentlyContinue
    Write-QartLog "Manifest creato: $manifestPath"

    $dllCount =
        (Get-ChildItem -LiteralPath $installDir -Filter "*.dll" -File -ErrorAction SilentlyContinue |
         Measure-Object).Count

    if ($dllCount -lt 3) {
        throw "Installazione incompleta: nella cartella installata risultano poche DLL ($dllCount). Riestrai lo zip e riprova."
    }

    Write-QartLog "DLL installate: $dllCount"
    Write-QartLog "Installazione completata correttamente."

    Write-Host ""
    Write-Host "QART BIM Composer installato correttamente per Revit $RevitYear." -ForegroundColor Green
    Write-Host "File installati in: $installDir"
    Write-Host "Log installazione: $script:logPath"
    Write-Host "Riavvia Revit $RevitYear."
    Read-Host "Premi INVIO per chiudere"
}
catch {
    if ($script:logPath) {
        Write-QartLog ("ERRORE: " + $_.Exception.Message)
    }

    Write-Host ""
    Write-Host "Installazione non riuscita." -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Cosa fare:" -ForegroundColor Yellow
    Write-Host "1. Estrai completamente lo zip in una cartella locale, non avviare dallo zip." -ForegroundColor Yellow
    Write-Host "2. Chiudi Revit e riprova." -ForegroundColor Yellow
    Write-Host "3. Se Windows blocca i file: tasto destro sullo zip > Proprieta > Sblocca, poi estrai di nuovo." -ForegroundColor Yellow
    if ($script:logPath) {
        Write-Host "Log installazione: $script:logPath" -ForegroundColor Yellow
    }
    Read-Host "Premi INVIO per chiudere"
    exit 1
}
