$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-CMake {
  $paths = @(
    "C:\Program Files\CMake\bin\cmake.exe",
    "C:\Program Files\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe",
    "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe",
    "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe",
    "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe"
  )
  foreach ($p in $paths) {
    if (Test-Path $p) { return $true }
  }
  return $false
}

if (Has-CMake) {
  Info "CMake ya esta instalado. Abre PlyCompiler de nuevo e intenta compilar otra vez."
  exit 0
}

try {
  $winget = Get-Command winget.exe -ErrorAction SilentlyContinue
  if ($winget) {
    Info "Se instalara CMake desde winget. Acepta los permisos de Windows si aparecen."
    $args = @(
      "install",
      "--id", "Kitware.CMake",
      "-e",
      "--source", "winget",
      "--accept-package-agreements",
      "--accept-source-agreements"
    )
    $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 "No se encontro winget. Se abrira la pagina oficial de CMake para instalarlo manualmente."
    Start-Process "https://cmake.org/download/"
    exit 0
  }

  if (Has-CMake) {
    Info "Listo. CMake quedo instalado. Cierra y abre PlyCompiler de nuevo antes de compilar."
    exit 0
  }

  Fail "La instalacion termino, pero PlyCompiler aun no detecta CMake. Reinicia Windows e intenta de nuevo."
  exit 1
} catch {
  Fail "No se pudo instalar CMake automaticamente.`n`nDetalle: $($_.Exception.Message)`n`nInstalacion manual: https://cmake.org/download/"
  exit 1
}
