param(
  [string]$Version = "0.1.0-experimental.10",
  [string]$BridgeVersion = "0.1.0-experimental.5"
)

$ErrorActionPreference = "Stop"
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
$project = Join-Path $repoRoot "companion\src\Lumi.Companion.App\Lumi.Companion.App.csproj"
$outputRoot = Join-Path $repoRoot "companion\installer\output"
$publishRoot = Join-Path $outputRoot "publish"
$stageRoot = Join-Path $outputRoot "package"
$archive = Join-Path $outputRoot "Lumi.Companion-win-x64.zip"
$installer = Join-Path $outputRoot "Lumi.Companion-Setup.exe"

& (Join-Path $PSScriptRoot "build-obs-bridge.ps1") -BridgeVersion $BridgeVersion
Remove-Item $publishRoot, $stageRoot -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $publishRoot, $stageRoot | Out-Null
$localDotnet = Join-Path $HOME ".dotnet-sdk\dotnet.exe"
$dotnet = if (Test-Path $localDotnet) { $localDotnet } else { (Get-Command dotnet.exe -ErrorAction Stop).Source }
$publishArguments = @("publish", "`"$project`"", "-c", "Release", "-r", "win-x64", "--self-contained", "true", "--disable-build-servers", "-o", "`"$publishRoot`"",
  "-p:PublishSingleFile=true", "-p:IncludeNativeLibrariesForSelfExtract=true", "-p:DebugType=None", "-p:Version=$Version")
$published = Start-Process -FilePath $dotnet -ArgumentList $publishArguments -NoNewWindow -Wait -PassThru
if ($published.ExitCode) { throw "Companion publish failed." }

$bridgeDiagnostic = Join-Path $outputRoot "obs-bridge-package-diagnostic.json"
Remove-Item $bridgeDiagnostic -Force -ErrorAction SilentlyContinue
$diagnosed = Start-Process -FilePath (Join-Path $publishRoot "Lumi.Companion.App.exe") -ArgumentList @("--diagnose-obs-bridge", "`"$bridgeDiagnostic`"") -Wait -PassThru
if ($diagnosed.ExitCode -ne 0) {
  $detail = if (Test-Path $bridgeDiagnostic) { Get-Content $bridgeDiagnostic -Raw } else { "No diagnostic result was written." }
  throw "Published OBS integration payload failed its executable-level check: $detail"
}
Remove-Item $bridgeDiagnostic -Force -ErrorAction SilentlyContinue

Copy-Item (Join-Path $publishRoot "Lumi.Companion.App.exe") $stageRoot
Copy-Item (Join-Path $publishRoot "components") $stageRoot -Recurse
Remove-Item $archive -Force -ErrorAction SilentlyContinue
Compress-Archive -Path (Join-Path $stageRoot "*") -DestinationPath $archive -CompressionLevel Optimal

$isccCandidates = @(
  (Join-Path $env:LOCALAPPDATA "Programs\Inno Setup 6\ISCC.exe"),
  (Join-Path ${env:ProgramFiles(x86)} "Inno Setup 6\ISCC.exe"),
  (Join-Path $env:ProgramFiles "Inno Setup 6\ISCC.exe")
)
$iscc = $isccCandidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1
if (-not $iscc) { throw "Inno Setup 6 is required to build the durable per-user Companion installer." }
Remove-Item $installer -Force -ErrorAction SilentlyContinue
$compileArguments = @(
  "`"/DAppVersion=$Version`"",
  "`"/DSourceRoot=$publishRoot`"",
  "`"/DOutputRoot=$outputRoot`"",
  "`"$(Join-Path $repoRoot "companion\installer\Lumi.Companion.iss")`""
)
$compiled = Start-Process -FilePath $iscc -ArgumentList $compileArguments -NoNewWindow -Wait -PassThru
if ($compiled.ExitCode -ne 0 -or -not (Test-Path $installer)) { throw "Companion installer compilation failed." }

$file = Get-Item $archive
$sha = (Get-FileHash $archive -Algorithm SHA256).Hash.ToLowerInvariant()
$setupFile = Get-Item $installer
$setupSha = (Get-FileHash $installer -Algorithm SHA256).Hash.ToLowerInvariant()
Write-Host "Published Lumi Companion $Version"
Write-Host "Artifact: $archive"
Write-Host "Bytes: $($file.Length)"
Write-Host "SHA256: $sha"
Write-Host "Installer: $installer"
Write-Host "Installer bytes: $($setupFile.Length)"
Write-Host "Installer SHA256: $setupSha"
