$p = '19mNqNXIoZ4c3EriFNfzfkgpGNOvLjpOqqZnTFXKnzjxWJ5zURjgJQQJ99CBACAAAAAamI5kAAASAZDOAMPp'
$t = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(':' + $p))
$h = @{ Authorization = 'Basic ' + $t }
$base = 'https://dev.azure.com/CN-Squad/Invista%20FIDC%20-%20Nexus/_apis'

# Buscar os 10 builds mais recentes do projeto (qualquer pipeline, branch devops)
$builds = Invoke-RestMethod -Uri "$base/build/builds?branchName=refs/heads/devops&`$top=10&api-version=7.0" -Headers $h
Write-Host "Builds recentes na branch devops:"
$builds.value | Select-Object id,
  @{n='pipeline';e={$_.definition.name}},
  @{n='status';e={$_.status}},
  @{n='result';e={if($_.result){$_.result}else{'(running)'}}},
  @{n='queued';e={$_.queueTime}} |
  Format-Table

# Pegar o mais recente do mfe-shell
$shell = $builds.value | Where-Object { $_.definition.name -eq 'mfe-shell' } | Select-Object -First 1
if ($shell) {
  $buildId = $shell.id
  Write-Host "=== mfe-shell build mais recente: $buildId ==="
  if ($shell.validationResults) {
    Write-Host "VALIDATION ERRORS:"
    $shell.validationResults | ForEach-Object { Write-Host "  [$($_.result)] $($_.message)" }
  }
  $tl = Invoke-RestMethod -Uri "$base/build/builds/$buildId/timeline?api-version=7.0" -Headers $h
  if ($tl.records.Count -gt 0) {
    $tl.records | Where-Object { $_.result -eq 'failed' } |
      Select-Object type, name, result, errorCount | Format-Table
    $failedStep = $tl.records | Where-Object { $_.result -eq 'failed' -and $_.type -eq 'Task' } | Select-Object -First 1
    if ($failedStep -and $failedStep.log) {
      Write-Host "LOG: $($failedStep.name)"
      $logContent = Invoke-RestMethod -Uri "$($failedStep.log.url)?api-version=7.0" -Headers $h
      $logContent -split "`n" | Select-Object -Last 40 | ForEach-Object { Write-Host $_ }
    }
  } else {
    Write-Host "Timeline vazia."
  }
}
