$ErrorActionPreference = "Stop"

Add-Type -AssemblyName System.Windows.Forms

function Info($Message) {
  [System.Windows.Forms.MessageBox]::Show($Message, "PlyCompiler", "OK", "Information") | Out-Null
}

function Fail($Message) {
  [System.Windows.Forms.MessageBox]::Show($Message, "PlyCompiler", "OK", "Error") | Out-Null
}

function Has-Msvc {
  $roots = @(
    "C:\Program Files\Microsoft Visual Studio\2022\BuildTools",
    "C:\Program Files\Microsoft Visual Studio\2022\Community",
    "C:\Program Files\Microsoft Visual Studio\2022\Professional",
    "C:\Program Files\Microsoft Visual Studio\2022\Enterprise"
  )
  foreach ($root in $roots) {
    if (Test-Path (Join-Path $root "VC\Tools\MSVC")) {
      $cl = Get-ChildItem (Join-Path $root "VC\Tools\MSVC") -Recurse -Filter cl.exe -ErrorAction SilentlyContinue |
        Where-Object { $_.FullName -like "*\bin\Hostx64\x64\cl.exe" } |
        Select-Object -First 1
      if ($cl) { return $true }
    }
  }
  return $false
}

if (Has-Msvc) {
  Info "Microsoft C++ Build Tools ya esta instalado. Abre PlyCompiler de nuevo e intenta compilar otra vez."
  exit 0
}

$log = Join-Path $env:TEMP "PlyCompiler-BuildTools-install.log"
$override = "--quiet --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools --add Microsoft.VisualStudio.Component.VC.CMake.Project --includeRecommended"

try {
  $winget = Get-Command winget.exe -ErrorAction SilentlyContinue
  if ($winget) {
    Info "Se instalara Microsoft Visual Studio Build Tools con C++. Este proceso puede tardar varios minutos. Acepta los permisos de Windows si aparecen."
    $args = @(
      "install",
      "--id", "Microsoft.VisualStudio.2022.BuildTools",
      "-e",
      "--source", "winget",
      "--accept-package-agreements",
      "--accept-source-agreements",
      "--override", $override
    )
    $p = Start-Process -FilePath $winget.Source -ArgumentList $args -Wait -PassThru -WindowStyle Normal
    if ($p.ExitCode -ne 0) { throw "winget termino con codigo $($p.ExitCode)." }
  } else {
    Info "Se descargara el instalador oficial de Microsoft Build Tools. Este proceso puede tardar varios minutos."
    $installer = Join-Path $env:TEMP "vs_BuildTools.exe"
    Invoke-WebRequest -Uri "https://aka.ms/vs/17/release/vs_BuildTools.exe" -OutFile $installer
    $args = @("--quiet", "--wait", "--norestart", "--add", "Microsoft.VisualStudio.Workload.VCTools", "--includeRecommended", "--log", $log)
    $p = Start-Process -FilePath $installer -ArgumentList $args -Wait -PassThru -WindowStyle Normal
    if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { throw "El instalador termino con codigo $($p.ExitCode)." }
  }

  if (Has-Msvc) {
    Info "Listo. Microsoft C++ Build Tools quedo instalado. Cierra y abre PlyCompiler de nuevo antes de compilar."
    exit 0
  }

  Fail "La instalacion termino, pero PlyCompiler aun no detecta C++ Build Tools. Reinicia Windows e intenta abrir PlyCompiler de nuevo."
  exit 1
} catch {
  Fail "No se pudo preparar el entorno automaticamente.`n`nDetalle: $($_.Exception.Message)`n`nInstalacion manual: instala Visual Studio Build Tools 2022 y selecciona Desktop development with C++."
  exit 1
}
