$ErrorActionPreference = "Stop"

$baseUrl = if ($env:RAIL_WEB_BASE_URL) { $env:RAIL_WEB_BASE_URL.TrimEnd("/") } else { "http://localhost:8088" }
$apiUrl = "$baseUrl/api/v1"

Write-Host "Checking navigation routes..."
$routes = @(
    "/overview", "/gis", "/runs", "/tasks", "/resources",
    "/analysis", "/alarms", "/workorders", "/algorithm-assets", "/operations",
    "/planning", "/routes", "/uav-operations", "/archives"
)

foreach ($route in $routes) {
    $response = Invoke-WebRequest -UseBasicParsing -Uri "$baseUrl$route" -TimeoutSec 20
    if ($response.StatusCode -ne 200) {
        throw "Route $route returned HTTP $($response.StatusCode)"
    }
}

Write-Host "Checking page data endpoints..."
$endpointChecks = @(
    @{ Path = "/stats/overview"; Property = $null },
    @{ Path = "/demo/runs"; Property = "runs" },
    @{ Path = "/inspection/tasks"; Property = "tasks" },
    @{ Path = "/inspection/resources"; Property = "resources" },
    @{ Path = "/analysis/jobs"; Property = "jobs" },
    @{ Path = "/analysis/results"; Property = "results" },
    @{ Path = "/alarms?includeSuppressed=true"; Property = "alarms" },
    @{ Path = "/workorders"; Property = "workorders" },
    @{ Path = "/samples"; Property = "samples" },
    @{ Path = "/models"; Property = "models" },
    @{ Path = "/platform/events"; Property = "events" },
    @{ Path = "/capabilities/completion"; Property = "capabilities" },
    @{ Path = "/inspection/plans"; Property = "plans" },
    @{ Path = "/inspection/objects"; Property = "objects" },
    @{ Path = "/routes"; Property = "routes" },
    @{ Path = "/uav/connections"; Property = "connections" },
    @{ Path = "/uav/devices"; Property = "devices" },
    @{ Path = "/uav/missions"; Property = "missions" },
    @{ Path = "/preprocess/jobs"; Property = "jobs" },
    @{ Path = "/gis/features"; Property = "features" },
    @{ Path = "/notifications"; Property = "notifications" },
    @{ Path = "/archive-packages"; Property = "archives" }
)

$summary = @()
foreach ($check in $endpointChecks) {
    $response = Invoke-RestMethod -Uri "$apiUrl$($check.Path)" -TimeoutSec 30
    if ($response.code -ne "0") {
        throw "Endpoint $($check.Path) returned application code $($response.code)"
    }
    $count = 1
    if ($check.Property) {
        $items = $response.data.($check.Property)
        if ($null -eq $items) {
            throw "Endpoint $($check.Path) did not return $($check.Property)"
        }
        $count = @($items).Count
    }
    $summary += [pscustomobject]@{ endpoint = $check.Path; count = $count }
}

Write-Host "Checking task status operations..."
$taskBody = @{
    external_task_id = "NAVIGATION-TEST"
    line_id = "line-test"
    mileage_start = "K10+000"
    mileage_end = "K11+000"
    route_id = "route-navigation-test"
    scene_set = @("人员入侵")
    priority = "normal"
    planned_start_time = (Get-Date).ToUniversalTime().AddMinutes(10).ToString("o")
} | ConvertTo-Json
$task = Invoke-RestMethod -Method Post -Uri "$apiUrl/inspection/tasks" -ContentType "application/json" -Body $taskBody -TimeoutSec 30
$taskId = $task.data.task_id
if (-not $taskId) { throw "Task creation did not return task_id" }

$missionBody = @{
    task_id = $taskId
    vendor = "DJI"
    vendor_mission_id = "mission-navigation-test"
    status = "flying"
    uav_id = "UAV-TEST"
    timestamp = (Get-Date).ToUniversalTime().ToString("o")
    position = @{ longitude = 116.1; latitude = 39.1 }
} | ConvertTo-Json -Depth 4
$mission = Invoke-RestMethod -Method Post -Uri "$apiUrl/uav/callbacks/mission-status" -ContentType "application/json" -Body $missionBody -TimeoutSec 30
if ($mission.data.status -ne "flying") { throw "Mission status update failed" }

$cancel = Invoke-RestMethod -Method Post -Uri "$apiUrl/inspection/tasks/$taskId/cancel" -ContentType "application/json" -Body "{}" -TimeoutSec 30
if ($cancel.data.status -ne "cancelled") { throw "Task cancellation failed" }

Write-Host "Checking alarm decision operation..."
$alarmsResponse = Invoke-RestMethod -Uri "$apiUrl/alarms?includeSuppressed=true" -TimeoutSec 30
$alarmId = @($alarmsResponse.data.alarms | Where-Object { $_.status -ne "closed" } | Select-Object -First 1).alarm_id
if ($alarmId) {
    $confirmBody = @{ action = "confirm"; reason = "页面操作回归"; operator = "测试人员" } | ConvertTo-Json
    $confirmed = Invoke-RestMethod -Method Post -Uri "$apiUrl/alarms/$alarmId/decision" -ContentType "application/json" -Body $confirmBody -TimeoutSec 30
    if ($confirmed.data.status -ne "confirmed") { throw "Alarm confirmation failed" }
}

$result = [ordered]@{
    route_count = $routes.Count
    endpoint_count = $endpointChecks.Count
    created_task_id = $taskId
    task_final_status = $cancel.data.status
    alarm_decision_checked = [bool]$alarmId
    endpoints = $summary
}
$result | ConvertTo-Json -Depth 5
Write-Host "Navigation page test passed."
