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

$result = [ordered]@{
  ok = $false
  status = "skipped"
  reason = ""
  scan_path = $exe
  created_at = (Get-Date).ToString("s")
  defender_available = $false
  mp_preference_available = $false
  file_exists = (Test-Path $exe)
  sha256 = ""
}

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

try {
  $cmd = Get-Command Start-MpScan -ErrorAction SilentlyContinue
  if ($null -ne $cmd) { $result.defender_available = $true }
} catch {}

try {
  $pref = Get-MpPreference -ErrorAction SilentlyContinue
  if ($null -ne $pref) { $result.mp_preference_available = $true }
} catch {}

if (-not (Test-Path $exe)) {
  $result.status = "skipped"
  $result.reason = "EXE not found. Build first, then run this script."
} elseif (-not $result.defender_available) {
  $result.status = "skipped"
  $result.reason = "Microsoft Defender PowerShell cmdlets are not available on this PC."
} elseif ($env:NEXA_DEFENDER_SCAN -ne "1") {
  $result.status = "skipped"
  $result.reason = "Set NEXA_DEFENDER_SCAN=1 before build to run a custom Microsoft Defender scan."
  $result.ok = $true
} else {
  try {
    Start-MpScan -ScanType CustomScan -ScanPath $exe -ErrorAction Stop
    $result.status = "completed"
    $result.reason = "Microsoft Defender custom scan command completed. Check Windows Security protection history for final verdict if needed."
    $result.ok = $true
  } catch {
    $result.status = "failed"
    $result.reason = $_.Exception.Message
  }
}

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