-- Deterministic fixtures for the release-preflight engine.

local EnsureApiRegistry = rawget(_G, "LIDCOUNCIL_EnsureApiRegistry")
local API, INTERNAL_API
if type(EnsureApiRegistry) == "function" then
  API, INTERNAL_API = EnsureApiRegistry()
else
  API = rawget(_G, "LIDCOUNCIL_API")
  if type(API) ~= "table" then
    API = {}
    _G.LIDCOUNCIL_API = API
  end
  if type(API.__internal) ~= "table" then
    API.__internal = {}
  end
  INTERNAL_API = API.__internal
end

local MAX_TEXT_LENGTH = 180
local MAX_DURATION_SECONDS = 3600
local MAX_TIME_VALUE_SECONDS = 1000000000000
local MAX_VALIDATION_COUNT = 1000000
local DEFAULT_PREFLIGHT_COOLDOWN_SECONDS = 2.0
local RELEASE_PREFLIGHT_REPORT_VERSION = 1
local EXPECTED_VALIDATION_CHECKS = 44

local function RunReleasePreflightValidation()
  local CreateReleasePreflightHelpers = INTERNAL_API.LIDCOUNCIL_CreateReleasePreflightHelpers_Impl
  local ClassifyReleasePreflightSafetyStatus =
    INTERNAL_API.LIDCOUNCIL_ClassifyReleasePreflightSafetyStatus_Impl
  if type(CreateReleasePreflightHelpers) ~= "function"
      or type(ClassifyReleasePreflightSafetyStatus) ~= "function" then
    return false, {
      version = RELEASE_PREFLIGHT_REPORT_VERSION,
      total = 1,
      passed = 0,
      failed = 1,
      problems = { "release preflight validation dependencies unavailable" },
    }
  end

  local checks = {}
  local problems = {}
  local fixtureState = {}
  local sanitizeReport

  local function CopyReport(source)
    if type(sanitizeReport) ~= "function" then
      error("release preflight report sanitizer unavailable")
    end
    return sanitizeReport(source)
  end

  local function NormalizeTimeValue(value)
    return CopyReport({ generatedAt = value }).generatedAt
  end

  local function SafeErrorText(value)
    local converted, text = pcall(tostring, value)
    if not converted then
      return "unreadable fixture error"
    end
    text = tostring(text or "")
    if #text > MAX_TEXT_LENGTH then
      return string.sub(text, 1, MAX_TEXT_LENGTH)
    end
    return text
  end

  local function RunFixtureGroup(label, expectedChecks, runner)
    local firstCheckIndex = #checks + 1
    local executed, executionError = pcall(runner)
    local producedChecks = #checks - firstCheckIndex + 1
    for index = firstCheckIndex, #checks do
      if checks[index] ~= true then
        problems[#problems + 1] = label .. " check " .. tostring(index - firstCheckIndex + 1) .. " failed"
      end
    end
    if not executed then
      checks[#checks + 1] = false
      problems[#problems + 1] = label .. " fixture error: " .. SafeErrorText(executionError)
    elseif producedChecks ~= expectedChecks then
      checks[#checks + 1] = false
      problems[#problems + 1] = label .. " produced " .. tostring(producedChecks)
        .. " checks; expected " .. tostring(expectedChecks)
    end
  end

  local function HasSharedReportShape(candidate)
    return type(candidate) == "table"
      and type(candidate.version) == "number"
      and candidate.version >= 1
      and candidate.version <= MAX_VALIDATION_COUNT
      and type(candidate.ran) == "boolean"
      and type(candidate.ready) == "boolean"
      and type(candidate.blocked) == "boolean"
      and type(candidate.blockedReason) == "string"
      and type(candidate.blockedDetail) == "string"
      and type(candidate.severity) == "string"
      and type(candidate.generatedAt) == "number"
      and type(candidate.suiteCount) == "number"
      and type(candidate.passedSuites) == "number"
      and type(candidate.failedSuites) == "number"
      and type(candidate.total) == "number"
      and type(candidate.passed) == "number"
      and type(candidate.failed) == "number"
      and type(candidate.warnings) == "number"
      and type(candidate.durationSeconds) == "number"
      and type(candidate.slowSuiteCount) == "number"
      and type(candidate.slowSuiteThresholdSeconds) == "number"
      and type(candidate.cooldownSeconds) == "number"
      and type(candidate.retryAfterSeconds) == "number"
      and type(candidate.suites) == "table"
      and type(candidate.problems) == "table"
  end

  local function HasSharedSuiteShape(candidate)
    return type(candidate) == "table"
      and type(candidate.key) == "string"
      and type(candidate.label) == "string"
      and type(candidate.ready) == "boolean"
      and type(candidate.executed) == "boolean"
      and type(candidate.total) == "number"
      and type(candidate.passed) == "number"
      and type(candidate.failed) == "number"
      and type(candidate.warnings) == "number"
      and type(candidate.durationSeconds) == "number"
      and type(candidate.slow) == "boolean"
      and type(candidate.version) == "number"
      and type(candidate.error) == "string"
      and type(candidate.problems) == "table"
  end

  local function RunCoreFixtures()
    local clockValues = { 0, 0, 0.1, 0.1, 0.7, 0.7, 0.8, 0.8 }
    local clockIndex = 0
    local validation = CreateReleasePreflightHelpers({
      GetNow = function()
        return 84
      end,
      GetClock = function()
        clockIndex = clockIndex + 1
        return clockValues[clockIndex] or clockValues[#clockValues]
      end,
      SlowSuiteThresholdSeconds = 0.50,
      BuildSuites = function()
        return {
          {
            key = "pass",
            label = "Passing suite",
            run = function()
              return true, { version = 2, total = 2, passed = 2, failed = 0 }
            end,
          },
          {
            key = "warning",
            label = "Warning suite",
            run = function()
              return true, { total = 2, passed = 1, failed = 0, warnings = 1 }
            end,
          },
          {
            key = "error",
            label = "Error suite",
            run = function()
              error("fixture failure")
            end,
          },
        }
      end,
    })
    if type(validation) ~= "table" or type(validation.SanitizeReport) ~= "function" then
      return false, {
        version = RELEASE_PREFLIGHT_REPORT_VERSION,
        total = 1,
        passed = 0,
        failed = 1,
        problems = { "release preflight validation helper unavailable" },
      }
    end

    sanitizeReport = validation.SanitizeReport

    local first = validation.Run()
    local snapshot = validation.GetStatus()
    local initialChecks = {
      first.ran == true and first.ready == false and first.severity == "error",
      first.suiteCount == 3 and first.passedSuites == 2 and first.failedSuites == 1,
      first.total == 5 and first.passed == 3 and first.failed == 1 and first.warnings == 1,
      first.generatedAt == 84 and #first.problems == 1,
      type(first.suites[3]) == "table" and first.suites[3].executed == false,
      math.abs(first.durationSeconds - 0.8) < 0.001 and first.slowSuiteCount == 1,
      type(first.suites[2]) == "table" and first.suites[2].slow == true
        and math.abs(first.suites[2].durationSeconds - 0.6) < 0.001,
    }
    for _, checkPassed in ipairs(initialChecks) do
      checks[#checks + 1] = checkPassed
    end
    snapshot.problems[1] = "mutated"
    checks[#checks + 1] = validation.GetStatus().problems[1] ~= "mutated"
    snapshot.suites[2].durationSeconds = 99
    checks[#checks + 1] = validation.GetStatus().suites[2].durationSeconds < 1
    local cleared = validation.Clear()
    checks[#checks + 1] = cleared.ran == false and cleared.severity == "not_run"
      and cleared.cooldownSeconds == DEFAULT_PREFLIGHT_COOLDOWN_SECONDS
      and cleared.retryAfterSeconds == 0 and #cleared.suites == 0 and #cleared.problems == 0
    local blockedBuilderCalled = false
    local blockedValidation = CreateReleasePreflightHelpers({
      GetNow = function()
        return 85
      end,
      CanRun = function()
        return false, "communication_busy", "fixture queue is busy"
      end,
      BuildSuites = function()
        blockedBuilderCalled = true
        return {}
      end,
    })
    local blocked = blockedValidation.Run()
    checks[#checks + 1] = blocked.ran == true and blocked.ready == false and blocked.blocked == true
    checks[#checks + 1] = blocked.severity == "blocked" and blocked.blockedReason == "communication_busy"
    checks[#checks + 1] = blocked.blockedDetail == "fixture queue is busy" and #blocked.suites == 0
    checks[#checks + 1] = blockedBuilderCalled == false
    local unavailableValidation = CreateReleasePreflightHelpers({
      GetNow = function()
        return 89
      end,
      GetClock = function()
        return 500
      end,
      CooldownSeconds = 0,
    })
    local unavailable = unavailableValidation.Run()
    checks[#checks + 1] = unavailable.ready == false and unavailable.severity == "error"
      and unavailable.suiteCount == 1 and unavailable.failedSuites == 1
      and type(unavailable.suites[1]) == "table"
      and unavailable.suites[1].key == "preflight_suite_builder"
      and unavailable.suites[1].executed == false
      and unavailable.suites[1].failed == 1
    fixtureState.first = first
    fixtureState.cleared = cleared
    fixtureState.blocked = blocked
    fixtureState.unavailable = unavailable
  end

  RunFixtureGroup("core aggregation", 15, RunCoreFixtures)

  local function RunNumericAndClockFixtures()
    local malformedCountValidation = CreateReleasePreflightHelpers({
      GetNow = function()
        return 90
      end,
      GetClock = function()
        return 600
      end,
      CooldownSeconds = 0,
      BuildSuites = function()
        return {
          {
            key = "malformed_counts",
            label = "Malformed validator counts",
            run = function()
              return true, {
                version = math.huge,
                total = math.huge,
                passed = 0 / 0,
                failed = -math.huge,
                warnings = MAX_VALIDATION_COUNT * 2 + 0.75,
              }
            end,
          },
        }
      end,
    })
    local malformedCounts = malformedCountValidation.Run()
    checks[#checks + 1] = malformedCounts.ready == true and malformedCounts.severity == "warning"
      and malformedCounts.total == MAX_VALIDATION_COUNT
      and malformedCounts.passed == 0 and malformedCounts.failed == 0
      and malformedCounts.warnings == MAX_VALIDATION_COUNT
      and malformedCounts.suites[1].version == MAX_VALIDATION_COUNT
    local malformedCopy = CopyReport({
      version = math.huge,
      generatedAt = math.huge,
      suiteCount = math.huge,
      passedSuites = -1,
      failedSuites = 0 / 0,
      total = math.huge,
      passed = -4,
      failed = MAX_VALIDATION_COUNT * 2 + 0.9,
      warnings = 0 / 0,
      durationSeconds = math.huge,
      slowSuiteCount = math.huge,
      slowSuiteThresholdSeconds = 0 / 0,
      cooldownSeconds = -math.huge,
      retryAfterSeconds = math.huge,
      suites = {
        {
          version = math.huge,
          total = math.huge,
          passed = -1,
          failed = 0 / 0,
          warnings = MAX_VALIDATION_COUNT * 2,
          durationSeconds = math.huge,
        },
      },
    })
    checks[#checks + 1] = malformedCopy.version == MAX_VALIDATION_COUNT
      and malformedCopy.suiteCount == MAX_VALIDATION_COUNT
      and malformedCopy.passedSuites == 0 and malformedCopy.failedSuites == 0
      and malformedCopy.total == MAX_VALIDATION_COUNT
      and malformedCopy.passed == 0 and malformedCopy.failed == MAX_VALIDATION_COUNT
      and malformedCopy.warnings == 0 and malformedCopy.slowSuiteCount == MAX_VALIDATION_COUNT
      and malformedCopy.generatedAt == 0
      and malformedCopy.durationSeconds == MAX_DURATION_SECONDS
      and malformedCopy.cooldownSeconds == 0
      and malformedCopy.retryAfterSeconds == MAX_DURATION_SECONDS
      and malformedCopy.suites[1].version == MAX_VALIDATION_COUNT
      and malformedCopy.suites[1].total == MAX_VALIDATION_COUNT
      and malformedCopy.suites[1].passed == 0 and malformedCopy.suites[1].failed == 0
      and malformedCopy.suites[1].warnings == MAX_VALIDATION_COUNT
      and malformedCopy.suites[1].durationSeconds == MAX_DURATION_SECONDS
    checks[#checks + 1] = NormalizeTimeValue(0 / 0) == 0
      and NormalizeTimeValue(math.huge) == 0
      and NormalizeTimeValue(-math.huge) == 0
      and NormalizeTimeValue(-1) == 0
      and NormalizeTimeValue(MAX_TIME_VALUE_SECONDS + 1) == MAX_TIME_VALUE_SECONDS
    local unstableClockValues = {
      700,
      math.huge,
      699,
      0 / 0,
      701,
      701,
      702,
      703,
      702,
      math.huge,
      704,
      704,
      10,
      10,
      10,
      10,
      10,
      11,
    }
    local unstableClockIndex = 0
    local unstableRuns = 0
    local unstableClockValidation = CreateReleasePreflightHelpers({
      GetNow = function()
        return math.huge
      end,
      GetClock = function()
        unstableClockIndex = unstableClockIndex + 1
        return unstableClockValues[unstableClockIndex] or unstableClockValues[#unstableClockValues]
      end,
      CooldownSeconds = 2,
      BuildSuites = function()
        return {
          {
            key = "unstable_clock",
            label = "Unstable clock",
            run = function()
              unstableRuns = unstableRuns + 1
              return true, { total = 1, passed = 1, failed = 0 }
            end,
          },
        }
      end,
    })
    local unstableFirst = unstableClockValidation.Run()
    local unstableBlocked = unstableClockValidation.Run()
    local unstableStillBlocked = unstableClockValidation.Run()
    local unstableRecovered = unstableClockValidation.Run()
    checks[#checks + 1] = unstableFirst.ready == true and unstableFirst.generatedAt == 0
      and unstableFirst.durationSeconds == 0 and unstableFirst.suites[1].durationSeconds == 0
      and unstableRuns == 2
    checks[#checks + 1] = unstableBlocked.blockedReason == "preflight_cooldown"
      and unstableBlocked.retryAfterSeconds == 2
      and unstableStillBlocked.blockedReason == "preflight_cooldown"
      and unstableStillBlocked.retryAfterSeconds == 1
    checks[#checks + 1] = unstableRecovered.ready == true
      and unstableRecovered.generatedAt == 0
      and unstableRecovered.durationSeconds == 1
    unstableClockValidation.Clear()
    local unstableAfterClear = unstableClockValidation.Run()
    local unstableAfterClearBlocked = unstableClockValidation.Run()
    checks[#checks + 1] = unstableAfterClear.ready == true and unstableRuns == 3
      and unstableAfterClearBlocked.blockedReason == "preflight_cooldown"
      and unstableAfterClearBlocked.retryAfterSeconds == 1
    fixtureState.malformedCounts = malformedCounts
    fixtureState.malformedCopy = malformedCopy
    fixtureState.unstableFirst = unstableFirst
    fixtureState.unstableBlocked = unstableBlocked
    fixtureState.unstableRecovered = unstableRecovered
    fixtureState.unstableAfterClear = unstableAfterClear
  end

  RunFixtureGroup("numeric and clock", 7, RunNumericAndClockFixtures)

  local function RunAdmissionFixtures()
    local recursiveBlocked
    local recursiveClearBlocked
    local recursiveValidation
    recursiveValidation = CreateReleasePreflightHelpers({
      GetNow = function()
        return 86
      end,
      GetClock = function()
        return 200
      end,
      CooldownSeconds = 0,
      BuildSuites = function()
        return {
          {
            key = "recursive",
            label = "Recursive-run guard",
            run = function()
              recursiveBlocked = recursiveValidation.Run()
              recursiveClearBlocked = recursiveValidation.Clear()
              return true, { total = 1, passed = 1, failed = 0 }
            end,
          },
        }
      end,
    })
    local recursiveOuter = recursiveValidation.Run()
    local recursiveStatus = recursiveValidation.GetStatus()
    checks[#checks + 1] = recursiveOuter.ready == true and recursiveOuter.blocked == false
    checks[#checks + 1] = type(recursiveBlocked) == "table" and recursiveBlocked.blocked == true
      and recursiveBlocked.blockedReason == "preflight_running"
      and recursiveBlocked.retryAfterSeconds == 0
    checks[#checks + 1] = type(recursiveClearBlocked) == "table"
      and recursiveClearBlocked.blockedReason == "preflight_running"
    checks[#checks + 1] = recursiveStatus.ready == true and recursiveStatus.suiteCount == 1
    local cooldownClock = 300
    local cooldownRuns = 0
    local cooldownValidation = CreateReleasePreflightHelpers({
      GetNow = function()
        return 87
      end,
      GetClock = function()
        return cooldownClock
      end,
      CooldownSeconds = 2,
      BuildSuites = function()
        return {
          {
            key = "cooldown",
            label = "Rapid-rerun cooldown",
            run = function()
              cooldownRuns = cooldownRuns + 1
              return true, { version = cooldownRuns, total = 1, passed = 1, failed = 0 }
            end,
          },
        }
      end,
    })
    local cooldownFirst = cooldownValidation.Run()
    local cooldownBlocked = cooldownValidation.Run()
    local cooldownStoredAfterBlock = cooldownValidation.GetStatus()
    checks[#checks + 1] = cooldownFirst.ready == true and cooldownRuns == 1
    checks[#checks + 1] = cooldownBlocked.blocked == true
      and cooldownBlocked.blockedReason == "preflight_cooldown"
      and cooldownBlocked.cooldownSeconds == 2
      and math.abs(cooldownBlocked.retryAfterSeconds - 2) < 0.001
      and cooldownRuns == 1
    checks[#checks + 1] = cooldownStoredAfterBlock.ready == true
      and cooldownStoredAfterBlock.blocked == false
      and cooldownStoredAfterBlock.suites[1].version == 1
    cooldownClock = 302
    local cooldownAfterDelay = cooldownValidation.Run()
    local cooldownStoredAfterDelay = cooldownValidation.GetStatus()
    checks[#checks + 1] = cooldownAfterDelay.ready == true and cooldownRuns == 2
      and cooldownAfterDelay.suites[1].version == 2
      and cooldownStoredAfterDelay.suites[1].version == 2
    cooldownValidation.Clear()
    local cooldownAfterClear = cooldownValidation.Run()
    checks[#checks + 1] = cooldownAfterClear.ready == true and cooldownRuns == 3
      and cooldownAfterClear.suites[1].version == 3
    fixtureState.recursiveBlocked = recursiveBlocked
    fixtureState.recursiveClearBlocked = recursiveClearBlocked
    fixtureState.cooldownBlocked = cooldownBlocked
    fixtureState.cooldownAfterDelay = cooldownAfterDelay
  end

  RunFixtureGroup("admission control", 9, RunAdmissionFixtures)

  local function RunBuilderIsolationFixtures()
    local builderListMetatableUsed = false
    local builderDefinitionMetatableUsed = false
    local builderBoundaryRecoveryRan = false
    local builderBoundaryValidation = CreateReleasePreflightHelpers({
      GetNow = function()
        return 91
      end,
      GetClock = function()
        return 390
      end,
      CooldownSeconds = 0,
      BuildSuites = function()
        local hostileDefinition = setmetatable({
          key = "hostile_definition",
        }, {
          __index = function()
            builderDefinitionMetatableUsed = true
            error("fixture definition access crash")
          end,
        })
        return setmetatable({
          [1] = hostileDefinition,
          [2] = "invalid definition",
          [3] = {
            key = "builder_boundary_recovery",
            label = "Builder boundary recovery",
            run = function()
              builderBoundaryRecoveryRan = true
              return true, { total = 1, passed = 1, failed = 0 }
            end,
          },
        }, {
          __index = function()
            builderListMetatableUsed = true
            error("fixture suite list index crash")
          end,
          __len = function()
            builderListMetatableUsed = true
            error("fixture suite list length crash")
          end,
        })
      end,
    })
    local builderBoundaryReport = builderBoundaryValidation.Run()
    local builderBoundaryStatus = builderBoundaryValidation.GetStatus()
    checks[#checks + 1] = builderBoundaryReport.ready == false
      and builderBoundaryReport.severity == "error"
      and builderBoundaryReport.suiteCount == 3
      and builderBoundaryReport.passedSuites == 1
      and builderBoundaryReport.failedSuites == 2
      and builderBoundaryReport.total == 3
      and builderBoundaryReport.passed == 1
      and builderBoundaryReport.failed == 2
    checks[#checks + 1] = builderListMetatableUsed == false
      and builderDefinitionMetatableUsed == true
      and builderBoundaryRecoveryRan == true
    checks[#checks + 1] = builderBoundaryReport.suites[1].key == "preflight_suite_result"
      and string.find(
        builderBoundaryReport.suites[1].error,
        "fixture definition access crash",
        1,
        true
      ) ~= nil
      and builderBoundaryReport.suites[2].key == "preflight_suite_definition"
      and builderBoundaryReport.suites[3].key == "builder_boundary_recovery"
      and builderBoundaryReport.suites[3].ready == true
      and builderBoundaryStatus.suites[3].key == "builder_boundary_recovery"
    local isolatedSecondRan = false
    local isolationValidation = CreateReleasePreflightHelpers({
      GetNow = function()
        return 88
      end,
      GetClock = function()
        return 400
      end,
      CooldownSeconds = 0,
      BuildSuites = function()
        return {
          {
            key = "isolated_failure",
            label = setmetatable({}, {
              __tostring = function()
                error(string.rep("fixture suite normalization crash ", 12))
              end,
            }),
            run = function()
              return true, { total = 1, passed = 1, failed = 0 }
            end,
          },
          {
            key = "isolated_recovery",
            label = "Isolated recovery",
            run = function()
              isolatedSecondRan = true
              return true, { total = 1, passed = 1, failed = 0 }
            end,
          },
        }
      end,
    })
    local isolatedReport = isolationValidation.Run()
    local isolatedStatus = isolationValidation.GetStatus()
    checks[#checks + 1] = isolatedReport.ran == true and isolatedReport.ready == false
      and isolatedReport.blocked == false and isolatedReport.severity == "error"
    checks[#checks + 1] = isolatedReport.suiteCount == 2
      and isolatedReport.passedSuites == 1 and isolatedReport.failedSuites == 1
      and isolatedReport.total == 2 and isolatedReport.passed == 1 and isolatedReport.failed == 1
    checks[#checks + 1] = type(isolatedReport.suites[1]) == "table"
      and isolatedReport.suites[1].key == "preflight_suite_result"
      and isolatedReport.suites[1].executed == false
      and string.find(isolatedReport.suites[1].error, "fixture suite normalization crash", 1, true) ~= nil
      and #isolatedReport.suites[1].error <= MAX_TEXT_LENGTH
    checks[#checks + 1] = isolatedSecondRan == true
      and isolatedReport.suites[2].key == "isolated_recovery"
      and isolatedReport.suites[2].ready == true
      and isolatedStatus.suites[2].key == "isolated_recovery"
    fixtureState.builderBoundaryReport = builderBoundaryReport
    fixtureState.builderBoundaryStatus = builderBoundaryStatus
    fixtureState.isolatedReport = isolatedReport
    fixtureState.isolatedStatus = isolatedStatus
  end

  RunFixtureGroup("builder isolation", 7, RunBuilderIsolationFixtures)

  local function RunSchemaFixtures()
    local first = fixtureState.first
    local cleared = fixtureState.cleared
    local blocked = fixtureState.blocked
    local recursiveBlocked = fixtureState.recursiveBlocked
    local recursiveClearBlocked = fixtureState.recursiveClearBlocked
    local cooldownBlocked = fixtureState.cooldownBlocked
    local unavailable = fixtureState.unavailable
    local malformedCounts = fixtureState.malformedCounts
    local malformedCopy = fixtureState.malformedCopy
    local unstableFirst = fixtureState.unstableFirst
    local unstableBlocked = fixtureState.unstableBlocked
    local unstableRecovered = fixtureState.unstableRecovered
    local unstableAfterClear = fixtureState.unstableAfterClear
    local builderBoundaryReport = fixtureState.builderBoundaryReport
    local builderBoundaryStatus = fixtureState.builderBoundaryStatus
    local isolatedReport = fixtureState.isolatedReport
    local isolatedStatus = fixtureState.isolatedStatus
    local cooldownAfterDelay = fixtureState.cooldownAfterDelay
    checks[#checks + 1] = HasSharedReportShape(first)
      and HasSharedReportShape(cleared)
      and HasSharedReportShape(blocked)
      and HasSharedReportShape(recursiveBlocked)
      and HasSharedReportShape(recursiveClearBlocked)
      and HasSharedReportShape(cooldownBlocked)
      and HasSharedReportShape(unavailable)
      and HasSharedReportShape(malformedCounts)
      and HasSharedReportShape(malformedCopy)
      and HasSharedReportShape(unstableFirst)
      and HasSharedReportShape(unstableBlocked)
      and HasSharedReportShape(unstableRecovered)
      and HasSharedReportShape(unstableAfterClear)
      and HasSharedReportShape(builderBoundaryReport)
      and HasSharedReportShape(builderBoundaryStatus)
      and HasSharedReportShape(isolatedReport)
      and HasSharedReportShape(isolatedStatus)
    checks[#checks + 1] = HasSharedSuiteShape(first.suites[1])
      and HasSharedSuiteShape(first.suites[2])
      and HasSharedSuiteShape(first.suites[3])
      and HasSharedSuiteShape(unavailable.suites[1])
      and HasSharedSuiteShape(malformedCounts.suites[1])
      and HasSharedSuiteShape(malformedCopy.suites[1])
      and HasSharedSuiteShape(unstableFirst.suites[1])
      and HasSharedSuiteShape(unstableRecovered.suites[1])
      and HasSharedSuiteShape(cooldownAfterDelay.suites[1])
      and HasSharedSuiteShape(builderBoundaryReport.suites[1])
      and HasSharedSuiteShape(builderBoundaryReport.suites[2])
      and HasSharedSuiteShape(builderBoundaryReport.suites[3])
      and HasSharedSuiteShape(isolatedReport.suites[1])
      and HasSharedSuiteShape(isolatedReport.suites[2])
  end

  RunFixtureGroup("schema contract", 2, RunSchemaFixtures)

  local function RunSafetyFixtures()
    local combatSafety = ClassifyReleasePreflightSafetyStatus(true)
    local sessionSafety = ClassifyReleasePreflightSafetyStatus(false, {
      id = "fixture-session",
      status = "PREPARING",
    })
    local busySafety = ClassifyReleasePreflightSafetyStatus(false, nil, {
      profileTransferStatus = {
        awaitingAcknowledgement = 2,
      },
      pendingProfileDeltaAcks = 1,
      profileSnapshotBatch = {
        pendingTargets = 3,
      },
    })
    local idleSafety = ClassifyReleasePreflightSafetyStatus(false, nil, {})
    checks[#checks + 1] = combatSafety.allowed == false and combatSafety.reason == "combat_lockdown"
    checks[#checks + 1] = sessionSafety.allowed == false and sessionSafety.reason == "active_loot_session"
      and sessionSafety.sessionId == "fixture-session" and sessionSafety.sessionStatus == "PREPARING"
    checks[#checks + 1] = busySafety.allowed == false and busySafety.reason == "communication_busy"
      and busySafety.transferPending == 2 and busySafety.deltaAcksPending == 1
      and busySafety.snapshotTargetsPending == 3
    checks[#checks + 1] = idleSafety.allowed == true and idleSafety.reason == ""
  end

  RunFixtureGroup("safety classification", 4, RunSafetyFixtures)

  if #checks ~= EXPECTED_VALIDATION_CHECKS then
    checks[#checks + 1] = false
    problems[#problems + 1] = "validation produced " .. tostring(#checks - 1)
      .. " checks; expected " .. tostring(EXPECTED_VALIDATION_CHECKS)
  end
  local passed = 0
  for _, checkPassed in ipairs(checks) do
    if checkPassed then
      passed = passed + 1
    end
  end
  return passed == #checks, {
    version = RELEASE_PREFLIGHT_REPORT_VERSION,
    total = #checks,
    passed = passed,
    failed = #checks - passed,
    problems = problems,
  }
end

API.LIDCOUNCIL_RunReleasePreflightValidation = RunReleasePreflightValidation
INTERNAL_API.LIDCOUNCIL_RunReleasePreflightValidation_Impl = RunReleasePreflightValidation
