$ErrorActionPreference = "Stop"

$base = if ($env:RAIL_API_BASE_URL) { $env:RAIL_API_BASE_URL } else { "http://localhost:8088" }
$frontend = if ($env:RAIL_FRONTEND_URL) { $env:RAIL_FRONTEND_URL } else { "http://localhost:8088" }

Write-Host "Checking backend health via $base..."
Invoke-RestMethod "$base/actuator/health" | ConvertTo-Json -Depth 10

Write-Host "Starting visual full-chain demo run..."
$run = (Invoke-RestMethod "$base/api/v1/demo/runs" -Method POST -ContentType "application/json" -Body "{}").data
$run | ConvertTo-Json -Depth 10

Write-Host "Waiting for visual run completion..."
$snapshot = $null
for ($i = 0; $i -lt 90; $i++) {
  Start-Sleep -Seconds 1
  $snapshot = (Invoke-RestMethod "$base/api/v1/demo/runs/$($run.run_id)").data
  if ($snapshot.status -in @("completed", "failed", "cancelled")) {
    break
  }
}

if ($null -eq $snapshot) {
  throw "No demo run snapshot received"
}

$summary = [ordered]@{
  run_id = $snapshot.run_id
  status = $snapshot.status
  progress = $snapshot.progress
  event_count = $snapshot.events.Count
  step_count = $snapshot.steps.Count
  completed_step_count = @($snapshot.steps | Where-Object { $_.status -eq "completed" }).Count
  summary = $snapshot.summary
}
$summary | ConvertTo-Json -Depth 20

if ($snapshot.status -ne "completed") {
  throw "Visual full-chain demo did not complete. Status: $($snapshot.status)"
}

if (@($snapshot.steps | Where-Object { $_.status -eq "completed" }).Count -ne 12) {
  throw "Visual full-chain demo did not complete all 12 stages"
}

$stepSnapshotNames = @($snapshot.step_snapshots.psobject.Properties.Name)
if ($stepSnapshotNames.Count -ne 12) {
  throw "Expected 12 step snapshots, received $($stepSnapshotNames.Count)"
}

$expectedPayloadTypes = @(
  "run_initialization", "task_detail", "uav_dispatch", "resource_ingestion",
  "preprocess_pipeline", "inference_workspace", "rule_evaluation", "alarm_generation",
  "workorder_dispatch", "workorder_closure", "sample_feedback", "run_summary"
)
$actualPayloadTypes = @($snapshot.step_snapshots.psobject.Properties | ForEach-Object { $_.Value.visual_payload.type })
foreach ($payloadType in $expectedPayloadTypes) {
  if ($payloadType -notin $actualPayloadTypes) {
    throw "Missing visual payload type: $payloadType"
  }
}

$sequences = @($snapshot.events | ForEach-Object { [int]$_.sequence })
for ($i = 1; $i -lt $sequences.Count; $i++) {
  if ($sequences[$i] -le $sequences[$i - 1]) {
    throw "Run events are not strictly ordered by sequence"
  }
}

if ($snapshot.entity_index.resource_ids.Count -lt 3 -or $snapshot.entity_index.sample_ids.Count -lt 1) {
  throw "Run entity index is incomplete"
}

Write-Host "Fetching overview..."
Invoke-RestMethod "$base/api/v1/stats/overview" | ConvertTo-Json -Depth 20

Write-Host "Fetching workorders..."
$workorders = (Invoke-RestMethod "$base/api/v1/workorders").data.workorders
[ordered]@{
  workorder_count = $workorders.Count
  latest_status = if ($workorders.Count -gt 0) { $workorders[0].status } else { "" }
} | ConvertTo-Json -Depth 10

Write-Host "Checking frontend..."
(Invoke-WebRequest -UseBasicParsing $frontend).StatusCode
