-- LidCouncil_ReleasePreflight.lua
-- Bounded, in-memory aggregation of the addon's deterministic validation suites.

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_SUITES = 8
local MAX_PROBLEMS = 16
local MAX_SUITE_PROBLEMS = 5
local MAX_TEXT_LENGTH = 180
local MAX_DURATION_SECONDS = 3600
local MAX_TIME_VALUE_SECONDS = 1000000000000
local MAX_VALIDATION_COUNT = 1000000
local DEFAULT_SLOW_SUITE_SECONDS = 0.50
local DEFAULT_PREFLIGHT_COOLDOWN_SECONDS = 2.0
local RELEASE_PREFLIGHT_REPORT_VERSION = 1

local function BoundText(value, limit)
  local text = tostring(value or "")
  local maxLength = math.max(1, tonumber(limit) or MAX_TEXT_LENGTH)
  if #text > maxLength then
    return string.sub(text, 1, maxLength)
  end
  return text
end

local function BoundTextSafely(value, limit, fallback)
  local bounded, text = pcall(BoundText, value, limit)
  if bounded then
    return text
  end
  return BoundText(fallback or "", limit)
end

local function CopyTextList(source, limit)
  local result = {}
  for index, value in ipairs(type(source) == "table" and source or {}) do
    if index > math.max(1, tonumber(limit) or MAX_PROBLEMS) then
      break
    end
    result[#result + 1] = BoundText(value, MAX_TEXT_LENGTH)
  end
  return result
end

local function NormalizeFiniteNumber(value, maximum)
  local numberValue = tonumber(value)
  if type(numberValue) ~= "number" or numberValue ~= numberValue or numberValue == -math.huge then
    return 0
  end
  if numberValue == math.huge then
    return maximum
  end
  return math.min(maximum, math.max(0, numberValue))
end

local function NormalizeCount(value)
  return math.floor(NormalizeFiniteNumber(value, MAX_VALIDATION_COUNT))
end

local function NormalizeTimeValue(value)
  local numberValue = tonumber(value)
  if type(numberValue) ~= "number"
      or numberValue ~= numberValue
      or numberValue < 0
      or numberValue == math.huge then
    return 0
  end
  return math.min(MAX_TIME_VALUE_SECONDS, numberValue)
end

local function NormalizeDuration(value)
  return NormalizeFiniteNumber(value, MAX_DURATION_SECONDS)
end

local function CopyReport(report)
  report = type(report) == "table" and report or {}
  local copy = {
    version = math.max(1, NormalizeCount(report.version or RELEASE_PREFLIGHT_REPORT_VERSION)),
    ran = report.ran == true,
    ready = report.ready == true,
    blocked = report.blocked == true,
    blockedReason = BoundText(report.blockedReason, 64),
    blockedDetail = BoundText(report.blockedDetail, MAX_TEXT_LENGTH),
    severity = BoundText(report.severity, 16),
    generatedAt = NormalizeTimeValue(report.generatedAt),
    suiteCount = NormalizeCount(report.suiteCount),
    passedSuites = NormalizeCount(report.passedSuites),
    failedSuites = NormalizeCount(report.failedSuites),
    total = NormalizeCount(report.total),
    passed = NormalizeCount(report.passed),
    failed = NormalizeCount(report.failed),
    warnings = NormalizeCount(report.warnings),
    durationSeconds = NormalizeDuration(report.durationSeconds),
    slowSuiteCount = NormalizeCount(report.slowSuiteCount),
    slowSuiteThresholdSeconds = NormalizeDuration(report.slowSuiteThresholdSeconds),
    cooldownSeconds = NormalizeDuration(report.cooldownSeconds),
    retryAfterSeconds = NormalizeDuration(report.retryAfterSeconds),
    suites = {},
    problems = CopyTextList(report.problems, MAX_PROBLEMS),
  }
  for index, suite in ipairs(type(report.suites) == "table" and report.suites or {}) do
    if index > MAX_SUITES then
      break
    end
    copy.suites[#copy.suites + 1] = {
      key = BoundText(type(suite) == "table" and suite.key or "", 64),
      label = BoundText(type(suite) == "table" and suite.label or "", 96),
      ready = type(suite) == "table" and suite.ready == true,
      executed = type(suite) == "table" and suite.executed == true,
      total = NormalizeCount(type(suite) == "table" and suite.total or 0),
      passed = NormalizeCount(type(suite) == "table" and suite.passed or 0),
      failed = NormalizeCount(type(suite) == "table" and suite.failed or 0),
      warnings = NormalizeCount(type(suite) == "table" and suite.warnings or 0),
      durationSeconds = NormalizeDuration(type(suite) == "table" and suite.durationSeconds or 0),
      slow = type(suite) == "table" and suite.slow == true,
      version = NormalizeCount(type(suite) == "table" and suite.version or 0),
      error = BoundText(type(suite) == "table" and suite.error or "", MAX_TEXT_LENGTH),
      problems = CopyTextList(type(suite) == "table" and suite.problems or {}, MAX_SUITE_PROBLEMS),
    }
  end
  return copy
end

local function CollectSuiteProblems(rawReport)
  rawReport = type(rawReport) == "table" and rawReport or {}
  local problems = {}
  for _, problem in ipairs(type(rawReport.problems) == "table" and rawReport.problems or {}) do
    if #problems >= MAX_SUITE_PROBLEMS then
      break
    end
    problems[#problems + 1] = BoundText(problem, MAX_TEXT_LENGTH)
  end
  for _, check in ipairs(type(rawReport.checks) == "table" and rawReport.checks or {}) do
    if #problems >= MAX_SUITE_PROBLEMS then
      break
    end
    if type(check) == "table" and check.passed ~= true and check.severity ~= "warning" then
      local name = BoundText(check.name or check.label or check.key or "unnamed check", 120)
      local actual = BoundText(check.actual or check.detail or "", 56)
      problems[#problems + 1] = name .. (actual ~= "" and (" (" .. actual .. ")") or "")
    end
  end
  return problems
end

INTERNAL_API.LIDCOUNCIL_CreateReleasePreflightHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}
  local BuildSuites = deps.BuildSuites
  local CanRun = deps.CanRun
  local GetNow = deps.GetNow
  local GetClock = type(deps.GetClock) == "function" and deps.GetClock or GetNow
  local RawGet = rawget
  local slowSuiteThresholdSeconds = math.max(
    0.05,
    math.min(10, tonumber(deps.SlowSuiteThresholdSeconds) or DEFAULT_SLOW_SUITE_SECONDS)
  )
  local cooldownSeconds = math.max(
    0,
    math.min(30, tonumber(deps.CooldownSeconds) or DEFAULT_PREFLIGHT_COOLDOWN_SECONDS)
  )
  local running = false
  local lastCompletedAt
  local lastClockValue = 0

  local function CreateReportState(ran, severity, generatedAt)
    return {
      version = RELEASE_PREFLIGHT_REPORT_VERSION,
      ran = ran == true,
      ready = false,
      blocked = false,
      blockedReason = "",
      blockedDetail = "",
      severity = type(severity) == "string" and severity or "not_run",
      generatedAt = NormalizeTimeValue(generatedAt),
      suiteCount = 0,
      passedSuites = 0,
      failedSuites = 0,
      total = 0,
      passed = 0,
      failed = 0,
      warnings = 0,
      durationSeconds = 0,
      slowSuiteCount = 0,
      slowSuiteThresholdSeconds = slowSuiteThresholdSeconds,
      cooldownSeconds = cooldownSeconds,
      retryAfterSeconds = 0,
      suites = {},
      problems = {},
    }
  end

  local function CreateSuiteState(key, label)
    return {
      key = BoundText(key, 64),
      label = BoundText(label, 96),
      ready = false,
      executed = false,
      total = 0,
      passed = 0,
      failed = 0,
      warnings = 0,
      durationSeconds = 0,
      slow = false,
      version = 0,
      error = "",
      problems = {},
    }
  end

  local report = CreateReportState(false, "not_run", 0)

  local function ReadNow()
    if type(GetNow) ~= "function" then
      return 0
    end
    local nowOk, value = pcall(GetNow)
    return nowOk and NormalizeTimeValue(value) or 0
  end

  local function ReadClock()
    if type(GetClock) ~= "function" then
      return lastClockValue
    end
    local clockOk, value = pcall(GetClock)
    if not clockOk then
      return lastClockValue
    end
    local clockValue = NormalizeTimeValue(value)
    if clockValue < lastClockValue then
      return lastClockValue
    end
    lastClockValue = clockValue
    return clockValue
  end

  local function BuildBlockedAttempt(reason, detail, retryAfterSeconds)
    local blockedDetail = BoundText(detail, MAX_TEXT_LENGTH)
    local blockedReport = CreateReportState(true, "blocked", ReadNow())
    blockedReport.blocked = true
    blockedReport.blockedReason = BoundText(reason, 64)
    blockedReport.blockedDetail = blockedDetail
    blockedReport.retryAfterSeconds = NormalizeDuration(retryAfterSeconds)
    blockedReport.problems = blockedDetail ~= "" and { blockedDetail } or {}
    return CopyReport(blockedReport)
  end

  local function AddSuiteResult(definition, executed, suiteOk, rawReport, executionError, durationSeconds)
    definition = type(definition) == "table" and definition or {}
    rawReport = type(rawReport) == "table" and rawReport or {}
    local total = NormalizeCount(rawReport.total or rawReport.checkCount)
    local passed = NormalizeCount(rawReport.passed or rawReport.passedCount)
    local failed = NormalizeCount(rawReport.failed or rawReport.errorCount)
    local warnings = NormalizeCount(rawReport.warnings or rawReport.warningCount)
    total = NormalizeCount(math.max(total, passed + failed + warnings))
    local ready = executed == true and suiteOk == true and failed == 0 and total > 0
    if not ready and failed == 0 then
      failed = 1
      total = NormalizeCount(math.max(total, passed + warnings + failed))
    end
    local normalizedDuration = NormalizeDuration(durationSeconds)
    local suite = CreateSuiteState(definition.key, definition.label)
    suite.ready = ready
    suite.executed = executed == true
    suite.total = total
    suite.passed = passed
    suite.failed = failed
    suite.warnings = warnings
    suite.durationSeconds = normalizedDuration
    suite.slow = normalizedDuration >= slowSuiteThresholdSeconds
    suite.version = NormalizeCount(rawReport.version)
    suite.error = BoundText(executionError, MAX_TEXT_LENGTH)
    suite.problems = CollectSuiteProblems(rawReport)
    if suite.error ~= "" and #suite.problems < MAX_SUITE_PROBLEMS then
      suite.problems[#suite.problems + 1] = suite.error
    end
    report.suites[#report.suites + 1] = suite
    report.suiteCount = NormalizeCount(report.suiteCount + 1)
    report.total = NormalizeCount(report.total + suite.total)
    report.passed = NormalizeCount(report.passed + suite.passed)
    report.failed = NormalizeCount(report.failed + suite.failed)
    report.warnings = NormalizeCount(report.warnings + suite.warnings)
    if suite.slow then
      report.slowSuiteCount = NormalizeCount(report.slowSuiteCount + 1)
    end
    if ready then
      report.passedSuites = NormalizeCount(report.passedSuites + 1)
      return
    end
    report.failedSuites = NormalizeCount(report.failedSuites + 1)
    if #report.problems < MAX_PROBLEMS then
      local problem = suite.label ~= "" and suite.label or suite.key
      local detail = suite.problems[1] or suite.error
      report.problems[#report.problems + 1] = BoundText(
        problem .. (detail ~= "" and (": " .. detail) or ""),
        MAX_TEXT_LENGTH
      )
    end
  end

  local function AddSuiteResultSafely(definition, executed, suiteOk, rawReport, executionError, durationSeconds)
    local added, addError = pcall(
      AddSuiteResult,
      definition,
      executed,
      suiteOk,
      rawReport,
      executionError,
      durationSeconds
    )
    if added then
      return true
    end

    local errorDetail = BoundTextSafely(addError, MAX_TEXT_LENGTH, "unknown normalization error")
    local fallbackDetail = BoundText(
      "suite result normalization failed" .. (errorDetail ~= "" and (": " .. errorDetail) or ""),
      MAX_TEXT_LENGTH
    )
    local fallbackAdded, fallbackError = pcall(
      AddSuiteResult,
      {
        key = "preflight_suite_result",
        label = "Release preflight suite result",
      },
      false,
      false,
      {},
      fallbackDetail,
      0
    )
    if not fallbackAdded then
      error(BoundTextSafely(fallbackError, MAX_TEXT_LENGTH, "suite result fallback failed"), 0)
    end
    return false
  end

  local function RunSuiteDefinition(definition)
    local suiteStartedAt = ReadClock()
    local executed, suiteOk, suiteReport = pcall(function()
      local runner = type(definition) == "table" and definition.run or nil
      if type(runner) ~= "function" then
        return false, { total = 1, failed = 1, problems = { "suite runner unavailable" } }
      end
      return runner()
    end)
    AddSuiteResultSafely(
      definition,
      executed,
      executed and suiteOk == true,
      executed and suiteReport or {},
      executed and "" or suiteOk,
      NormalizeDuration(ReadClock() - suiteStartedAt)
    )
  end

  local function ProcessSuiteDefinitions(suiteDefinitions)
    local foundDefinition = false
    for index = 1, MAX_SUITES + 1 do
      local readOk, definition = pcall(RawGet, suiteDefinitions, index)
      if not readOk then
        AddSuiteResultSafely({
          key = "preflight_suite_builder",
          label = "Release preflight suite builder",
        }, false, false, {}, BoundTextSafely(
          definition,
          MAX_TEXT_LENGTH,
          "suite definition list could not be read"
        ))
        return
      end
      if definition == nil then
        if not foundDefinition then
          AddSuiteResultSafely({
            key = "preflight_suite_builder",
            label = "Release preflight suite builder",
          }, false, false, {}, "suite list is empty")
        end
        return
      end
      if index > MAX_SUITES then
        AddSuiteResultSafely({
          key = "preflight_suite_limit",
          label = "Release preflight suite limit",
        }, false, false, {}, "suite list exceeds " .. tostring(MAX_SUITES))
        return
      end

      foundDefinition = true
      if type(definition) ~= "table" then
        AddSuiteResultSafely({
          key = "preflight_suite_definition",
          label = "Release preflight suite definition",
        }, false, false, {}, "suite definition " .. tostring(index) .. " is not a table")
      else
        RunSuiteDefinition(definition)
      end
    end
  end

  local function ExecuteRun(runStartedAt)
    report = CreateReportState(true, "running", ReadNow())

    if type(CanRun) == "function" then
      local gateExecuted, allowed, reason, detail = pcall(CanRun)
      if not gateExecuted or allowed ~= true then
        report.blocked = true
        report.blockedReason = BoundText(gateExecuted and reason or "safety_check_failed", 64)
        report.blockedDetail = BoundText(gateExecuted and detail or allowed, MAX_TEXT_LENGTH)
        if report.blockedReason == "" then
          report.blockedReason = "preflight_blocked"
        end
        if report.blockedDetail == "" then
          report.blockedDetail = "Release preflight safety conditions were not met."
        end
        report.severity = "blocked"
        report.problems[1] = report.blockedDetail
        report.durationSeconds = NormalizeDuration(ReadClock() - runStartedAt)
        return CopyReport(report)
      end
    end

    local built, suiteDefinitions = pcall(type(BuildSuites) == "function" and BuildSuites or function()
      return {}
    end)
    if not built or type(suiteDefinitions) ~= "table" then
      AddSuiteResultSafely({
        key = "preflight_suite_builder",
        label = "Release preflight suite builder",
      }, false, false, {}, built and "invalid_suite_list" or suiteDefinitions)
    else
      local processed, processError = pcall(ProcessSuiteDefinitions, suiteDefinitions)
      if not processed then
        AddSuiteResultSafely({
          key = "preflight_suite_builder",
          label = "Release preflight suite builder",
        }, false, false, {}, BoundTextSafely(
          processError,
          MAX_TEXT_LENGTH,
          "suite definition traversal failed"
        ))
      end
    end

    report.durationSeconds = NormalizeDuration(ReadClock() - runStartedAt)
    report.ready = report.failedSuites == 0
    if report.failedSuites > 0 then
      report.severity = "error"
    elseif report.warnings > 0 or report.slowSuiteCount > 0 then
      report.severity = "warning"
    else
      report.severity = "healthy"
    end
    return CopyReport(report)
  end

  local function BuildEngineFailure(runStartedAt, failure)
    local failureText = BoundTextSafely(
      failure,
      MAX_TEXT_LENGTH,
      "release preflight engine failed without a readable error"
    )
    if failureText == "" then
      failureText = "release preflight engine returned an invalid result"
    end
    report = CreateReportState(true, "error", ReadNow())
    report.suiteCount = 1
    report.failedSuites = 1
    report.total = 1
    report.failed = 1
    report.durationSeconds = NormalizeDuration(ReadClock() - runStartedAt)
    local engineSuite = CreateSuiteState("preflight_engine", "Release preflight engine")
    engineSuite.total = 1
    engineSuite.failed = 1
    engineSuite.version = RELEASE_PREFLIGHT_REPORT_VERSION
    engineSuite.error = failureText
    engineSuite.problems = { failureText }
    report.suites = { engineSuite }
    report.problems = { failureText }
    return CopyReport(report)
  end

  local function Run()
    local runStartedAt = ReadClock()
    if running then
      return BuildBlockedAttempt(
        "preflight_running",
        "Release preflight is already running.",
        0
      )
    end
    if lastCompletedAt ~= nil and cooldownSeconds > 0 then
      local elapsedSeconds = math.max(0, runStartedAt - lastCompletedAt)
      if elapsedSeconds < cooldownSeconds then
        local retryAfterSeconds = NormalizeDuration(cooldownSeconds - elapsedSeconds)
        return BuildBlockedAttempt(
          "preflight_cooldown",
          string.format("Release preflight ran recently. Retry in %.2f seconds.", retryAfterSeconds),
          retryAfterSeconds
        )
      end
    end

    running = true
    local executed, result = pcall(ExecuteRun, runStartedAt)
    running = false
    local completedAt = ReadClock()
    if not executed or type(result) ~= "table" then
      lastCompletedAt = completedAt
      return BuildEngineFailure(
        runStartedAt,
        executed and "release preflight engine returned an invalid result" or result
      )
    end
    if result.blocked ~= true then
      lastCompletedAt = completedAt
    end
    return result
  end

  local function Clear()
    if running then
      return BuildBlockedAttempt(
        "preflight_running",
        "Release preflight status cannot be cleared while a run is active.",
        0
      )
    end
    lastCompletedAt = nil
    lastClockValue = 0
    report = CreateReportState(false, "not_run", 0)
    return CopyReport(report)
  end

  return {
    Run = Run,
    Clear = Clear,
    SanitizeReport = function(source)
      return CopyReport(source)
    end,
    GetStatus = function()
      return CopyReport(report)
    end,
  }
end

local function RunNamedValidation(apiName, options)
  local validator = type(API) == "table" and API[apiName] or nil
  if type(validator) ~= "function" then
    return false, {
      total = 1,
      failed = 1,
      problems = { tostring(apiName) .. " unavailable" },
    }
  end
  return validator(options)
end

local function RunStartupHealthSuite()
  local runHealth = type(API) == "table" and API.LIDCOUNCIL_RunStartupHealthCheck or nil
  local runValidation = type(API) == "table" and API.LIDCOUNCIL_RunStartupHealthValidation or nil
  if type(runHealth) ~= "function" or type(runValidation) ~= "function" then
    return false, {
      total = 1,
      failed = 1,
      problems = { "startup health APIs unavailable" },
    }
  end
  local health = runHealth(false)
  health = type(health) == "table" and health or {}
  local validationOk, validation = runValidation()
  validation = type(validation) == "table" and validation or {}
  local validationTotal = math.max(0, tonumber(validation.checks or validation.total) or 0)
  local validationPassed = math.max(0, tonumber(validation.passed) or 0)
  local validationFailed = math.max(0, tonumber(validation.failed) or 0)
  local checks = {}
  for _, check in ipairs(type(health.checks) == "table" and health.checks or {}) do
    if #checks >= 32 then
      break
    end
    checks[#checks + 1] = {
      name = type(check) == "table" and check.label or "Startup health check",
      passed = type(check) == "table" and (check.passed == true or check.severity == "warning") or false,
      severity = type(check) == "table" and check.severity or "",
      actual = type(check) == "table" and check.detail or "",
    }
  end
  checks[#checks + 1] = {
    name = "Startup health validator self-test",
    passed = validationOk == true,
    actual = tostring(validationPassed) .. "/" .. tostring(validationTotal),
  }
  return health.ready == true and validationOk == true, {
    version = math.max(1, tonumber(health.version) or 1),
    total = math.max(0, tonumber(health.checkCount) or 0) + validationTotal,
    passed = math.max(0, tonumber(health.passedCount) or 0) + validationPassed,
    failed = math.max(0, tonumber(health.errorCount) or 0) + validationFailed,
    warnings = math.max(0, tonumber(health.warningCount) or 0),
    checks = checks,
    problems = health.problems,
  }
end

local function GetPreflightTime()
  if type(GetTime) == "function" then
    return NormalizeTimeValue(GetTime())
  end
  return NormalizeTimeValue(time and time() or 0)
end

local function GetPreflightClock()
  if type(GetTimePreciseSec) == "function" then
    return NormalizeTimeValue(GetTimePreciseSec())
  end
  return GetPreflightTime()
end

local function ClassifyReleasePreflightSafetyStatus(inCombat, session, queue)
  local status = {
    allowed = false,
    reason = "",
    detail = "",
    sessionId = "",
    sessionStatus = "",
    queuePending = 0,
    transferPending = 0,
    deltaAcksPending = 0,
    snapshotTargetsPending = 0,
  }

  if inCombat == true then
    status.reason = "combat_lockdown"
    status.detail = "Leave combat before running release preflight."
    return status
  end

  if type(session) == "table" then
    status.sessionId = BoundText(session.id, 64)
    status.sessionStatus = string.upper(BoundText(session.status, 24))
    status.reason = "active_loot_session"
    status.detail = "Stop the " .. (status.sessionStatus ~= "" and status.sessionStatus or "open")
      .. " loot session before running release preflight."
    return status
  end

  queue = type(queue) == "table" and queue or {}
  local transferStatus = type(queue.profileTransferStatus) == "table" and queue.profileTransferStatus or {}
  local snapshotBatch = type(queue.profileSnapshotBatch) == "table" and queue.profileSnapshotBatch or {}
  status.queuePending = math.max(0, tonumber(queue.pending) or 0)
  status.transferPending = math.max(
    math.max(0, tonumber(transferStatus.active) or 0),
    math.max(0, tonumber(transferStatus.awaitingAcknowledgement) or 0),
    math.max(0, tonumber(transferStatus.pendingAcknowledgementTimeoutRevalidations) or 0)
  )
  status.deltaAcksPending = math.max(0, tonumber(queue.pendingProfileDeltaAcks) or 0)
  status.snapshotTargetsPending = math.max(0, tonumber(snapshotBatch.pendingTargets) or 0)
  local communicationBusy = queue.busy == true
    or queue.running == true
    or status.queuePending > 0
    or status.transferPending > 0
    or status.deltaAcksPending > 0
    or status.snapshotTargetsPending > 0
    or snapshotBatch.running == true
  if communicationBusy then
    status.reason = "communication_busy"
    status.detail = "Wait for synchronization traffic to become idle before running release preflight"
      .. " (queue " .. tostring(status.queuePending)
      .. ", transfers " .. tostring(status.transferPending)
      .. ", delta ACKs " .. tostring(status.deltaAcksPending)
      .. ", snapshot targets " .. tostring(status.snapshotTargetsPending) .. ")."
    return status
  end

  status.allowed = true
  status.detail = "No active loot session or pending synchronization traffic."
  return status
end

local function BuildReleasePreflightSafetyStatus()
  if type(InCombatLockdown) ~= "function" then
    return {
      allowed = false,
      reason = "combat_state_unavailable",
      detail = "The combat-lockdown API is unavailable.",
    }
  end
  local combatOk, inCombat = pcall(InCombatLockdown)
  if not combatOk then
    return {
      allowed = false,
      reason = "combat_state_unavailable",
      detail = "The combat-lockdown state could not be read.",
    }
  end
  if inCombat then
    return ClassifyReleasePreflightSafetyStatus(true)
  end

  local getActiveSession = type(API) == "table" and API.LIDCOUNCIL_GetActiveLootSession or nil
  if type(getActiveSession) ~= "function" then
    return {
      allowed = false,
      reason = "session_state_unavailable",
      detail = "The active loot-session API is unavailable.",
    }
  end
  local sessionOk, session = pcall(getActiveSession)
  if not sessionOk then
    return {
      allowed = false,
      reason = "session_state_unavailable",
      detail = "The active loot-session state could not be read.",
    }
  end
  if type(session) == "table" then
    return ClassifyReleasePreflightSafetyStatus(false, session)
  end

  local getQueueStatus = type(API) == "table" and API.LIDCOUNCIL_GetSessionCommQueueStatus or nil
  if type(getQueueStatus) ~= "function" then
    return {
      allowed = false,
      reason = "communication_state_unavailable",
      detail = "The communication queue diagnostics API is unavailable.",
    }
  end
  local queueOk, queue = pcall(getQueueStatus)
  if not queueOk or type(queue) ~= "table" then
    return {
      allowed = false,
      reason = "communication_state_unavailable",
      detail = "The communication queue state could not be read.",
    }
  end
  return ClassifyReleasePreflightSafetyStatus(false, nil, queue)
end

local function GetReleasePreflightSafetyStatus()
  local executed, status = pcall(BuildReleasePreflightSafetyStatus)
  if executed and type(status) == "table" then
    return status
  end
  return {
    allowed = false,
    reason = "safety_check_failed",
    detail = BoundText(status, MAX_TEXT_LENGTH),
  }
end

local releasePreflight = INTERNAL_API.LIDCOUNCIL_CreateReleasePreflightHelpers_Impl({
  GetNow = GetPreflightTime,
  GetClock = GetPreflightClock,
  SlowSuiteThresholdSeconds = DEFAULT_SLOW_SUITE_SECONDS,
  CooldownSeconds = DEFAULT_PREFLIGHT_COOLDOWN_SECONDS,
  CanRun = function()
    local status = GetReleasePreflightSafetyStatus()
    return status.allowed == true, status.reason, status.detail
  end,
  BuildSuites = function()
    return {
      {
        key = "startup_health",
        label = "Startup health",
        run = RunStartupHealthSuite,
      },
      {
        key = "comm_protocol",
        label = "Communication protocol",
        run = function()
          return RunNamedValidation("LIDCOUNCIL_RunDeveloperCommProtocolValidation")
        end,
      },
      {
        key = "comm_transport",
        label = "Communication transport",
        run = function()
          return RunNamedValidation("LIDCOUNCIL_RunDeveloperCommOutboundTransportValidation")
        end,
      },
      {
        key = "profile_sync",
        label = "Profile synchronization",
        run = function()
          return RunNamedValidation("LIDCOUNCIL_RunDeveloperProfileSyncValidation", {
            includeCommunicationSuites = false,
            persistReport = false,
          })
        end,
      },
      {
        key = "profile_host_override",
        label = "Host override contract",
        run = function()
          return RunNamedValidation("LIDCOUNCIL_RunProfileHostOverrideContractValidation")
        end,
      },
      {
        key = "profile_transfer_packages",
        label = "Shared profile packages",
        run = function()
          return RunNamedValidation("LIDCOUNCIL_RunProfileTransferPackageValidation")
        end,
      },
      {
        key = "preflight_engine",
        label = "Release preflight aggregator",
        run = function()
          return RunNamedValidation("LIDCOUNCIL_RunReleasePreflightValidation")
        end,
      },
    }
  end,
})

local function RunReleasePreflight()
  local report = releasePreflight.Run()
  return type(report) == "table" and report.ready == true, report
end

local function GetReleasePreflightStatus()
  return releasePreflight.GetStatus()
end

local function ClearReleasePreflightStatus()
  return releasePreflight.Clear()
end

API.LIDCOUNCIL_RunReleasePreflight = RunReleasePreflight
API.LIDCOUNCIL_GetReleasePreflightStatus = GetReleasePreflightStatus
API.LIDCOUNCIL_ClearReleasePreflightStatus = ClearReleasePreflightStatus
API.LIDCOUNCIL_GetReleasePreflightSafetyStatus = GetReleasePreflightSafetyStatus
INTERNAL_API.LIDCOUNCIL_RunReleasePreflight_Impl = RunReleasePreflight
INTERNAL_API.LIDCOUNCIL_GetReleasePreflightStatus_Impl = GetReleasePreflightStatus
INTERNAL_API.LIDCOUNCIL_ClassifyReleasePreflightSafetyStatus_Impl = ClassifyReleasePreflightSafetyStatus
