$ErrorActionPreference = "Continue"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$pack = Join-Path $root "files\packs\TexasInstruments.MSPM0G1X0X_G3X0X_DFP.1.3.1.pack"
$checks = @(
  @{ Name = "Python"; Command = "python"; Args = @("--version"); Required = $true },
  @{ Name = "pyOCD"; Command = "pyocd"; Args = @("--version"); Required = $true },
  @{ Name = "Arm GCC"; Command = "arm-none-eabi-gcc"; Args = @("--version"); Required = $true },
  @{ Name = "mingw32-make"; Command = "mingw32-make"; Args = @("--version"); Required = $true },
  @{ Name = "CMake"; Command = "cmake"; Args = @("--version"); Required = $false },
  @{ Name = "Ninja"; Command = "ninja"; Args = @("--version"); Required = $false },
  @{ Name = "STM32CubeProgrammer"; Command = "STM32_Programmer_CLI"; Args = @("--version"); Required = $false }
)

Write-Host "Hardware Lab environment check" -ForegroundColor Cyan
Write-Host "Kit root: $root"
Write-Host ""

foreach ($check in $checks) {
  $cmd = Get-Command $check.Command -ErrorAction SilentlyContinue
  if (-not $cmd) {
    $level = if ($check.Required) { "MISSING" } else { "optional missing" }
    $color = if ($check.Required) { "Red" } else { "Yellow" }
    Write-Host ("[{0}] {1}" -f $level, $check.Name) -ForegroundColor $color
    continue
  }

  Write-Host ("[OK] {0}: {1}" -f $check.Name, $cmd.Source) -ForegroundColor Green
  try {
    & $check.Command @($check.Args) 2>&1 | Select-Object -First 2 | ForEach-Object { Write-Host "     $_" }
  } catch {
    Write-Host "     version check failed: $($_.Exception.Message)" -ForegroundColor Yellow
  }
}

Write-Host ""
if (Test-Path -LiteralPath $pack) {
  Write-Host "[OK] MSPM0 DFP pack: $pack" -ForegroundColor Green
} else {
  Write-Host "[MISSING] MSPM0 DFP pack: $pack" -ForegroundColor Red
}

$sdkRoots = @()
if (Test-Path -LiteralPath "C:\ti") {
  $sdkRoots = Get-ChildItem -LiteralPath "C:\ti" -Directory -Filter "mspm0_sdk_*" -ErrorAction SilentlyContinue |
    Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName "imports.mak") } |
    Select-Object -ExpandProperty FullName
}

if ($sdkRoots.Count -gt 0) {
  Write-Host "[OK] MSPM0 SDK candidates:" -ForegroundColor Green
  $sdkRoots | ForEach-Object { Write-Host "     $_" }
} else {
  Write-Host "[MISSING] No C:\ti\mspm0_sdk_*\imports.mak found" -ForegroundColor Red
}

Write-Host ""
Write-Host "Next: run start-hardware-lab-backend.cmd, then open https://nuedc-components-atlas-public.pages.dev/hardware-lab"
