Set-Location $PSScriptRoot\..
$ErrorActionPreference = "Continue"
$exe = Join-Path $PWD "dist\NexaOffice_WorkSuite\NexaOffice_WorkSuite.exe"
$out = Join-Path $PWD "data\code_signing_latest.json"
New-Item -ItemType Directory -Force -Path (Join-Path $PWD "data") | Out-Null

$result = [ordered]@{
  ok = $true
  status = "skipped"
  reason = "NEXA_SIGN_PFX is not set. Unsigned development build."
  exe_path = $exe
  file_exists = (Test-Path $exe)
  created_at = (Get-Date).ToString("s")
  timestamp_url = $env:NEXA_TIMESTAMP_URL
  sha256_before = ""
  sha256_after = ""
}

if (Test-Path $exe) {
  try { $result.sha256_before = (Get-FileHash -Algorithm SHA256 $exe).Hash.ToLowerInvariant() } catch {}
}

if (-not (Test-Path $exe)) {
  $result.status = "skipped"
  $result.reason = "EXE not found. Build first, then sign."
} elseif ([string]::IsNullOrWhiteSpace($env:NEXA_SIGN_PFX)) {
  # keep ok=true so normal dev builds are not blocked
} elseif (-not (Test-Path $env:NEXA_SIGN_PFX)) {
  $result.ok = $false
  $result.status = "failed"
  $result.reason = "NEXA_SIGN_PFX path does not exist."
} else {
  try {
    $signtool = (Get-Command signtool.exe -ErrorAction SilentlyContinue)
    if ($null -eq $signtool) {
      $result.ok = $false
      $result.status = "failed"
      $result.reason = "signtool.exe was not found. Install Windows SDK or sign manually."
    } else {
      $ts = $env:NEXA_TIMESTAMP_URL
      if ([string]::IsNullOrWhiteSpace($ts)) { $ts = "http://timestamp.digicert.com" }
      $args = @("sign", "/fd", "SHA256", "/f", $env:NEXA_SIGN_PFX, "/tr", $ts, "/td", "SHA256")
      if (-not [string]::IsNullOrWhiteSpace($env:NEXA_SIGN_PASSWORD)) {
        $args += @("/p", $env:NEXA_SIGN_PASSWORD)
      }
      $args += @($exe)
      & $signtool.Source @args | Out-String | Write-Host
      if ($LASTEXITCODE -eq 0) {
        $result.status = "signed"
        $result.reason = "EXE signed with signtool."
        $result.ok = $true
      } else {
        $result.status = "failed"
        $result.reason = "signtool returned exit code $LASTEXITCODE."
        $result.ok = $false
      }
    }
  } catch {
    $result.ok = $false
    $result.status = "failed"
    $result.reason = $_.Exception.Message
  }
}

if (Test-Path $exe) {
  try { $result.sha256_after = (Get-FileHash -Algorithm SHA256 $exe).Hash.ToLowerInvariant() } catch {}
}

($result | ConvertTo-Json -Depth 5) | Tee-Object -FilePath $out
if ($result.ok) { exit 0 }
exit 1
