$ErrorActionPreference = "Stop"

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

function Start-FullChainRun {
  return (Invoke-RestMethod "$base/api/v1/demo/runs" -Method POST -ContentType "application/json" -Body "{}").data
}

function Wait-RunTerminal([string]$runId, [int]$attempts = 90) {
  for ($i = 0; $i -lt $attempts; $i++) {
    Start-Sleep -Milliseconds 500
    $snapshot = (Invoke-RestMethod "$base/api/v1/demo/runs/$runId").data
    if ($snapshot.status -in @("completed", "failed", "cancelled")) {
      return $snapshot
    }
  }
  throw "Run $runId did not reach a terminal state"
}

Write-Host "Starting full-chain interaction test..."
$run = Start-FullChainRun
$snapshot = Wait-RunTerminal $run.run_id
if ($snapshot.status -ne "completed") {
  throw "Interaction run failed: $($snapshot.status)"
}

$preprocess = (Invoke-RestMethod "$base/api/v1/demo/runs/$($run.run_id)/steps/preprocess.running").data
if ($preprocess.snapshot.visual_payload.processors.Count -ne 6) {
  throw "Preprocess snapshot does not contain six processors"
}

$resourceId = $snapshot.entity_index.resource_ids[0]
$resultId = $snapshot.entity_index.ai_result_ids[0]
$alarmId = $snapshot.entity_index.alarm_ids[0]
$workorderId = $snapshot.entity_index.workorder_ids[0]
$sampleId = $snapshot.entity_index.sample_ids[0]

$resource = (Invoke-RestMethod "$base/api/v1/inspection/resources/$resourceId/preview").data
if ($resource.resource_id -ne $resourceId) { throw "Resource preview lookup failed" }

$evidence = (Invoke-RestMethod "$base/api/v1/analysis/results/$resultId/evidence").data
if ($evidence.ai_result_id -ne $resultId) { throw "AI evidence lookup failed" }

$alarmEvidence = (Invoke-RestMethod "$base/api/v1/alarms/$alarmId/evidence-chain").data
if ($alarmEvidence.alarm.alarm_id -ne $alarmId) { throw "Alarm evidence chain lookup failed" }

$redispatchBody = @{ assignee = "综合巡检班组"; reason = "交互测试重新派发"; operator = "测试人员" } | ConvertTo-Json
$redispatch = (Invoke-RestMethod "$base/api/v1/workorders/$workorderId/redispatch" -Method POST -ContentType "application/json" -Body $redispatchBody).data
if ($redispatch.status -ne "created") { throw "Workorder redispatch failed" }

$reviewBody = @{ action = "approve"; result = "复核通过"; comment = "交互测试闭环"; operator = "测试人员" } | ConvertTo-Json
$review = (Invoke-RestMethod "$base/api/v1/workorders/$workorderId/review" -Method POST -ContentType "application/json" -Body $reviewBody).data
if ($review.status -ne "closed") { throw "Workorder review failed" }

$sampleBody = @{ decision = "excluded"; priority = "normal"; reason = "交互测试排除"; operator = "测试人员" } | ConvertTo-Json
$sample = (Invoke-RestMethod "$base/api/v1/samples/$sampleId/decision" -Method POST -ContentType "application/json" -Body $sampleBody).data
if ($sample.labeling_status -ne "excluded") { throw "Sample decision failed" }

$export = (Invoke-RestMethod "$base/api/v1/demo/runs/$($run.run_id)/export").data
if ($export.run.run_id -ne $run.run_id) { throw "Run export failed" }

Write-Host "Checking cancellation and node retry..."
$retryRun = Start-FullChainRun
Invoke-RestMethod "$base/api/v1/demo/runs/$($retryRun.run_id)/cancel" -Method POST -ContentType "application/json" -Body "{}" | Out-Null
$cancelled = Wait-RunTerminal $retryRun.run_id
if ($cancelled.status -ne "cancelled") { throw "Run cancellation failed" }

$cancelledStep = @($cancelled.steps | Where-Object { $_.status -eq "cancelled" })[0]
if ($null -eq $cancelledStep) { throw "No cancelled business step was recorded" }
$retryBody = @{
  reason = "交互测试恢复"
  operator = "测试人员"
  expected_attempt = [int]$cancelledStep.attempt
  idempotency_key = "$($retryRun.run_id)-retry"
} | ConvertTo-Json
$retry = (Invoke-RestMethod "$base/api/v1/demo/runs/$($retryRun.run_id)/steps/$($cancelledStep.key)/retry" -Method POST -ContentType "application/json" -Body $retryBody).data
if ($retry.status -ne "running") { throw "Node retry was not accepted" }

$retriedSnapshot = Wait-RunTerminal $retryRun.run_id
if ($retriedSnapshot.status -ne "completed") { throw "Retried run did not complete" }

[ordered]@{
  run_id = $run.run_id
  event_count = $snapshot.events.Count
  step_snapshot_count = @($snapshot.step_snapshots.psobject.Properties.Name).Count
  entity_counts = [ordered]@{
    resources = $snapshot.entity_index.resource_ids.Count
    results = $snapshot.entity_index.ai_result_ids.Count
    alarms = $snapshot.entity_index.alarm_ids.Count
    workorders = $snapshot.entity_index.workorder_ids.Count
    samples = $snapshot.entity_index.sample_ids.Count
  }
  retry_run_id = $retryRun.run_id
  retry_step = $cancelledStep.key
  retry_status = $retriedSnapshot.status
} | ConvertTo-Json -Depth 10

Write-Host "Full-chain interaction test passed."
