# Copyright (c) 2026 ttldtor.
# SPDX-License-Identifier: BSL-1.0
# Internal CTest driver for portals.mvp-measurement; not a benchmark CLI.
# Caller supplies PROGRAM (MVP executable) and OUTPUT_DIRECTORY (existing build
# directory). Runs finite headless idle/load/encoding checks with 20-second child
# deadlines, writes mvp-*.json, and fails CMake on bad exits or invalid results.
# Run through CTest in a tools-and-tests-enabled build; no help flag is defined.
if(NOT DEFINED PROGRAM OR NOT DEFINED OUTPUT_DIRECTORY)
  message(FATAL_ERROR "PROGRAM and OUTPUT_DIRECTORY are required")
endif()

function(run_case name)
  set(path "${OUTPUT_DIRECTORY}/mvp-${name}.json")
  execute_process(COMMAND "${PROGRAM}" --output "${path}" ${ARGN}
    RESULT_VARIABLE result TIMEOUT 20 ERROR_VARIABLE errors)
  if(NOT result EQUAL 0)
    message(FATAL_ERROR "${name}: exit ${result}: ${errors}")
  endif()
  file(READ "${path}" value)
  string(JSON complete GET "${value}" complete)
  if(NOT complete)
    message(FATAL_ERROR "${name}: incomplete result")
  endif()
  set(case_json "${value}" PARENT_SCOPE)
endfunction()

run_case(idle --rate 0 --warmup-ms 200 --duration-ms 150)
string(JSON frames GET "${case_json}" window accepted_frames)
string(JSON bytes GET "${case_json}" window confirmed_bytes)
string(JSON ingress GET "${case_json}" dashboard_display_ingress_ms count)
string(JSON control GET "${case_json}" runner_input_control_ns p95)
string(JSON committed GET "${case_json}" warmup_had_completed_frame)
if(NOT frames EQUAL 0 OR NOT bytes EQUAL 0 OR NOT ingress EQUAL 0 OR NOT control STREQUAL "" OR NOT committed)
  message(FATAL_ERROR "idle: warmup leaked into the observation or N/A was fabricated")
endif()

run_case(load --rate 10000 --warmup-ms 100 --duration-ms 250 --diagnostics enabled --sample-capacity 1)
string(JSON overflow GET "${case_json}" phase_samples_ns render overflow)
string(JSON p95 GET "${case_json}" phase_samples_ns render p95)
string(JSON ohlc GET "${case_json}" acceptance lossless_ohlc)
string(JSON coherent GET "${case_json}" acceptance coherent)
string(JSON accounting GET "${case_json}" runner_accounting_matches)
string(JSON begin GET "${case_json}" window begin generated)
string(JSON end GET "${case_json}" window end generated)
string(JSON wall GET "${case_json}" window wall_ns)
if(NOT overflow GREATER 0 OR NOT p95 STREQUAL "" OR NOT ohlc OR NOT coherent OR NOT accounting OR
   NOT begin GREATER 0 OR NOT end GREATER begin OR wall LESS 250000000)
  message(FATAL_ERROR "load: overflow, real window, model agreement or accounting failed")
endif()

run_case(encoding --encoding-only)
string(JSON oracle GET "${case_json}" oracle_verified)
string(JSON frames GET "${case_json}" frames)
if(NOT oracle OR frames LESS 2)
  message(FATAL_ERROR "encoding: independent oracle was not verified")
endif()
