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 function TrimReason(value)
  local text = tostring(value or "")
  text = text:gsub("^%s+", "")
  text = text:gsub("%s+$", "")
  return text
end

INTERNAL_API.LIDCOUNCIL_ClassifyInboundRejectReason_Impl = function(reason)
  local resolvedReason = string.lower(TrimReason(reason))
  if string.find(resolvedReason, "incoming_rate_limited_", 1, true) == 1
    or string.find(resolvedReason, "_rate_limited", 1, true) ~= nil
  then
    return "rate_limited"
  end
  if resolvedReason == "stale_session_bound_message"
    or string.find(resolvedReason, "stale_", 1, true) == 1
  then
    return "stale"
  end
  if resolvedReason == "protocol_handler_error" or resolvedReason == "inbound_admission_unavailable" then
    return "handler_failure"
  end
  if resolvedReason == "unknown_incoming_opcode" then
    return "unknown_opcode"
  end
  if resolvedReason == "missing_incoming_sender"
    or resolvedReason == "missing_incoming_opcode"
    or string.find(resolvedReason, "incoming_payload_", 1, true) == 1
    or string.find(resolvedReason, "truncated_", 1, true) == 1
    or string.find(resolvedReason, "missing_", 1, true) == 1
    or string.find(resolvedReason, "invalid_", 1, true) == 1
  then
    return "malformed"
  end
  return "admission_drop"
end

INTERNAL_API.LIDCOUNCIL_GetInboundRejectDecisionAction_Impl = function(reason)
  local category = INTERNAL_API.LIDCOUNCIL_ClassifyInboundRejectReason_Impl(reason)
  if category == "rate_limited" then
    return "rejected_rate_limited", category
  elseif category == "stale" then
    return "ignored_stale_payload", category
  elseif category == "handler_failure" then
    return "rejected_handler_failure", category
  elseif category == "unknown_opcode" then
    return "rejected_unknown_opcode", category
  elseif category == "admission_drop" then
    return "rejected_admission", category
  end
  return "rejected_malformed_payload", "malformed"
end

INTERNAL_API.LIDCOUNCIL_AppendInboundRejectClassificationValidationChecks_Impl = function(addCheck)
  if type(addCheck) ~= "function" then
    return
  end
  local classify = INTERNAL_API.LIDCOUNCIL_ClassifyInboundRejectReason_Impl
  local resolveAction = INTERNAL_API.LIDCOUNCIL_GetInboundRejectDecisionAction_Impl
  addCheck("inbound reject classifies transport rate limit", "rate_limited", classify("incoming_rate_limited_bulk"))
  addCheck("inbound reject classifies profile request rate limit", "rate_limited", classify("inbound_psubpatch_req_rate_limited"))
  addCheck("inbound reject classifies malformed payload", "malformed", classify("incoming_payload_below_opcode_minimum"))
  addCheck("inbound reject classifies stale session", "stale", classify("stale_session_bound_message"))
  addCheck("inbound reject classifies handler failure", "handler_failure", classify("protocol_handler_error"))
  addCheck("inbound reject classifies unknown opcode", "unknown_opcode", classify("unknown_incoming_opcode"))
  addCheck("inbound reject classifies policy admission drop", "admission_drop", classify("session_not_admitted"))
  addCheck("inbound rate limit decision is not malformed", "rejected_rate_limited/rate_limited", table.concat({
    resolveAction("inbound_psubpatch_req_rate_limited"),
  }, "/"))
end

INTERNAL_API.LIDCOUNCIL_IncrementInboundStaleSessionDropTotal_Impl = function(telemetry, reason)
  telemetry = type(telemetry) == "table" and telemetry or {}
  if TrimReason(reason) == "stale_session_bound_message" then
    telemetry.staleSessionBoundDropTotal = math.max(0, tonumber(telemetry.staleSessionBoundDropTotal) or 0) + 1
  end
  return math.max(0, tonumber(telemetry.staleSessionBoundDropTotal) or 0)
end

INTERNAL_API.LIDCOUNCIL_CreateInboundTelemetryOps_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}
  local TrimText = type(deps.TrimText) == "function" and deps.TrimText or TrimReason
  local NormalizeCharacterKey = type(deps.NormalizeCharacterKey) == "function"
    and deps.NormalizeCharacterKey
    or TrimText
  local GetNow = type(deps.GetNow) == "function" and deps.GetNow or function()
    return (type(GetServerTime) == "function" and GetServerTime()) or (time and time() or 0)
  end
  local telemetry = {
    receivedTotal = 0,
    receivedBytes = 0,
    dispatchedTotal = 0,
    rejectedTotal = 0,
    rejectedContractTotal = 0,
    unknownOpcodeTotal = 0,
    staleSessionBoundDropTotal = 0,
    handlerErrorTotal = 0,
    byKind = {},
    stageByKind = {},
    dispatchedByKind = {},
    bytesByKind = {},
    rejectedByKind = {},
    rejectedByReason = {},
    rejectedContractByKind = {},
    unknownOpcodeByKind = {},
    handlerErrorByKind = {},
    bySender = {},
    rollingWindow = {},
    dispatchedRollingWindow = {},
    rollingWindowSeconds = 10,
    retentionSeconds = 90,
    maxPayloadBytes = 1024,
    maxPayloadFields = 40,
    maxTrackedSenders = 40,
    maxTrackedKeys = 32,
    lastReceivedAt = 0,
    lastDispatchedAt = 0,
    lastDispatchedSender = "",
    lastRejectedAt = 0,
    lastRejectedReason = "",
    lastRejectedContractKind = "",
    lastRejectedContractAt = 0,
    lastUnknownOpcode = "",
    lastUnknownOpcodeAt = 0,
    lastHandlerErrorAt = 0,
    lastHandlerErrorKind = "",
    lastHandlerErrorSender = "",
    lastHandlerErrorDetail = "",
  }
  local ops = {}

  ops.normalizeTrackedKey = function(value, fallback)
    local key = string.upper(TrimText(value))
    if key == "" or #key > 64 then
      key = fallback or "UNKNOWN"
    end
    return key
  end

  ops.resolveBoundedKey = function(bucket, key, fallback)
    if type(bucket) ~= "table" then
      return fallback
    end
    if bucket[key] ~= nil then
      return key
    end
    local tracked = 0
    for _ in pairs(bucket) do
      tracked = tracked + 1
    end
    if tracked >= math.max(1, tonumber(telemetry.maxTrackedKeys) or 32) then
      return fallback
    end
    return key
  end

  ops.prune = function(now)
    local currentTime = math.max(0, tonumber(now) or GetNow())
    local rollingCutoff = currentTime - math.max(1, tonumber(telemetry.rollingWindowSeconds) or 10)
    local retainedWindow = {}
    for _, sample in ipairs(telemetry.rollingWindow) do
      if type(sample) == "table" and math.max(0, tonumber(sample.at) or 0) >= rollingCutoff then
        retainedWindow[#retainedWindow + 1] = sample
      end
    end
    telemetry.rollingWindow = retainedWindow
    local retainedDispatchedWindow = {}
    for _, sample in ipairs(telemetry.dispatchedRollingWindow) do
      if type(sample) == "table" and math.max(0, tonumber(sample.at) or 0) >= rollingCutoff then
        retainedDispatchedWindow[#retainedDispatchedWindow + 1] = sample
      end
    end
    telemetry.dispatchedRollingWindow = retainedDispatchedWindow

    local senderCutoff = currentTime - math.max(1, tonumber(telemetry.retentionSeconds) or 90)
    for senderKey, entry in pairs(telemetry.bySender) do
      if type(entry) ~= "table" or math.max(0, tonumber(entry.updatedAt) or 0) < senderCutoff then
        telemetry.bySender[senderKey] = nil
      end
    end
  end

  ops.record = function(kind, sender, byteCount)
    local now = GetNow()
    ops.prune(now)
    local resolvedKind = ops.normalizeTrackedKey(kind, "UNKNOWN")
    resolvedKind = ops.resolveBoundedKey(telemetry.byKind, resolvedKind, "OTHER")
    local bytes = math.max(0, tonumber(byteCount) or 0)
    telemetry.receivedTotal = (tonumber(telemetry.receivedTotal) or 0) + 1
    telemetry.receivedBytes = (tonumber(telemetry.receivedBytes) or 0) + bytes
    telemetry.byKind[resolvedKind] = (tonumber(telemetry.byKind[resolvedKind]) or 0) + 1
    telemetry.bytesByKind[resolvedKind] = (tonumber(telemetry.bytesByKind[resolvedKind]) or 0) + bytes
    telemetry.lastReceivedAt = now
    telemetry.rollingWindow[#telemetry.rollingWindow + 1] = { at = now, bytes = bytes }

    local senderKey = string.lower(NormalizeCharacterKey(sender))
    if senderKey == "" then
      senderKey = "unknown"
    end
    if telemetry.bySender[senderKey] == nil then
      local trackedSenders = 0
      for _ in pairs(telemetry.bySender) do
        trackedSenders = trackedSenders + 1
      end
      if trackedSenders >= math.max(1, tonumber(telemetry.maxTrackedSenders) or 40) then
        senderKey = "other"
      end
    end
    local senderEntry = type(telemetry.bySender[senderKey]) == "table"
      and telemetry.bySender[senderKey]
      or { messages = 0, bytes = 0, rejected = 0, handlerErrors = 0, updatedAt = now }
    senderEntry.messages = math.max(0, tonumber(senderEntry.messages) or 0) + 1
    senderEntry.bytes = math.max(0, tonumber(senderEntry.bytes) or 0) + bytes
    senderEntry.updatedAt = now
    telemetry.bySender[senderKey] = senderEntry
    return resolvedKind, senderKey
  end

  ops.recordStage = function(kind, stage)
    local now = GetNow()
    ops.prune(now)
    local resolvedKind = ops.normalizeTrackedKey(kind, "UNKNOWN")
    resolvedKind = ops.resolveBoundedKey(telemetry.stageByKind, resolvedKind, "OTHER")
    local stageKey = ops.normalizeTrackedKey(stage, "UNKNOWN")
    local stageCounts = type(telemetry.stageByKind[resolvedKind]) == "table"
      and telemetry.stageByKind[resolvedKind]
      or {}
    stageKey = ops.resolveBoundedKey(stageCounts, stageKey, "OTHER")
    stageCounts[stageKey] = math.max(0, tonumber(stageCounts[stageKey]) or 0) + 1
    telemetry.stageByKind[resolvedKind] = stageCounts
  end

  ops.recordDispatched = function(kind, sender, byteCount)
    local now = GetNow()
    ops.prune(now)
    local resolvedKind = ops.normalizeTrackedKey(kind, "UNKNOWN")
    resolvedKind = ops.resolveBoundedKey(telemetry.dispatchedByKind, resolvedKind, "OTHER")
    local resolvedSender = NormalizeCharacterKey(sender)
    local bytes = math.max(0, tonumber(byteCount) or 0)
    telemetry.dispatchedTotal = (tonumber(telemetry.dispatchedTotal) or 0) + 1
    telemetry.dispatchedByKind[resolvedKind] = (tonumber(telemetry.dispatchedByKind[resolvedKind]) or 0) + 1
    telemetry.lastDispatchedAt = now
    telemetry.lastDispatchedSender = resolvedSender
    telemetry.dispatchedRollingWindow[#telemetry.dispatchedRollingWindow + 1] = {
      at = now,
      bytes = bytes,
      sender = resolvedSender,
      kind = resolvedKind,
    }

    local senderKey = string.lower(resolvedSender)
    local senderEntry = telemetry.bySender[senderKey]
    if type(senderEntry) == "table" then
      senderEntry.sender = resolvedSender
      senderEntry.dispatched = math.max(0, tonumber(senderEntry.dispatched) or 0) + 1
      senderEntry.lastDispatchedAt = now
    end
  end

  ops.recordRejected = function(kind, sender, reason)
    local now = GetNow()
    ops.prune(now)
    local resolvedKind = ops.normalizeTrackedKey(kind, "UNKNOWN")
    resolvedKind = ops.resolveBoundedKey(telemetry.rejectedByKind, resolvedKind, "OTHER")
    local reasonKey = TrimText(reason)
    if reasonKey == "" then
      reasonKey = "unknown_reject"
    elseif #reasonKey > 96 then
      reasonKey = string.sub(reasonKey, 1, 96)
    end
    INTERNAL_API.LIDCOUNCIL_IncrementInboundStaleSessionDropTotal_Impl(telemetry, reasonKey)
    reasonKey = ops.resolveBoundedKey(telemetry.rejectedByReason, reasonKey, "other_reject")
    telemetry.rejectedTotal = (tonumber(telemetry.rejectedTotal) or 0) + 1
    telemetry.rejectedByKind[resolvedKind] = (tonumber(telemetry.rejectedByKind[resolvedKind]) or 0) + 1
    telemetry.rejectedByReason[reasonKey] = (tonumber(telemetry.rejectedByReason[reasonKey]) or 0) + 1
    telemetry.lastRejectedAt = now
    telemetry.lastRejectedReason = reasonKey

    local senderKey = string.lower(NormalizeCharacterKey(sender))
    local senderEntry = telemetry.bySender[senderKey]
    if type(senderEntry) == "table" then
      senderEntry.rejected = math.max(0, tonumber(senderEntry.rejected) or 0) + 1
      senderEntry.updatedAt = now
    end
  end

  ops.recordContractRejected = function(kind)
    local now = GetNow()
    ops.prune(now)
    local resolvedKind = ops.normalizeTrackedKey(kind, "UNKNOWN")
    resolvedKind = ops.resolveBoundedKey(telemetry.rejectedContractByKind, resolvedKind, "OTHER")
    telemetry.rejectedContractTotal = (tonumber(telemetry.rejectedContractTotal) or 0) + 1
    telemetry.rejectedContractByKind[resolvedKind] = (tonumber(telemetry.rejectedContractByKind[resolvedKind]) or 0) + 1
    telemetry.lastRejectedContractKind = resolvedKind
    telemetry.lastRejectedContractAt = now
  end

  ops.recordUnknownOpcode = function(kind)
    local now = GetNow()
    ops.prune(now)
    local resolvedKind = ops.normalizeTrackedKey(kind, "UNKNOWN")
    resolvedKind = ops.resolveBoundedKey(telemetry.unknownOpcodeByKind, resolvedKind, "OTHER")
    telemetry.unknownOpcodeTotal = (tonumber(telemetry.unknownOpcodeTotal) or 0) + 1
    telemetry.unknownOpcodeByKind[resolvedKind] = (tonumber(telemetry.unknownOpcodeByKind[resolvedKind]) or 0) + 1
    telemetry.lastUnknownOpcode = resolvedKind
    telemetry.lastUnknownOpcodeAt = now
  end

  ops.recordHandlerError = function(kind, sender, detail)
    local now = GetNow()
    ops.prune(now)
    local resolvedKind = ops.normalizeTrackedKey(kind, "UNKNOWN")
    resolvedKind = ops.resolveBoundedKey(telemetry.handlerErrorByKind, resolvedKind, "OTHER")
    local resolvedSender = NormalizeCharacterKey(sender)
    if #resolvedSender > 96 then
      resolvedSender = string.sub(resolvedSender, 1, 96)
    end
    local resolvedDetail = TrimText(detail)
    if #resolvedDetail > 240 then
      resolvedDetail = string.sub(resolvedDetail, 1, 240)
    end

    telemetry.handlerErrorTotal = math.max(0, tonumber(telemetry.handlerErrorTotal) or 0) + 1
    telemetry.handlerErrorByKind[resolvedKind] =
      math.max(0, tonumber(telemetry.handlerErrorByKind[resolvedKind]) or 0) + 1
    telemetry.lastHandlerErrorAt = now
    telemetry.lastHandlerErrorKind = resolvedKind
    telemetry.lastHandlerErrorSender = resolvedSender
    telemetry.lastHandlerErrorDetail = resolvedDetail

    local senderKey = string.lower(resolvedSender)
    local senderEntry = telemetry.bySender[senderKey]
    if type(senderEntry) == "table" then
      senderEntry.handlerErrors = math.max(0, tonumber(senderEntry.handlerErrors) or 0) + 1
      senderEntry.updatedAt = now
    end
  end

  ops.clear = function()
    telemetry.receivedTotal = 0
    telemetry.receivedBytes = 0
    telemetry.dispatchedTotal = 0
    telemetry.rejectedTotal = 0
    telemetry.rejectedContractTotal = 0
    telemetry.unknownOpcodeTotal = 0
    telemetry.staleSessionBoundDropTotal = 0
    telemetry.handlerErrorTotal = 0
    telemetry.byKind = {}
    telemetry.stageByKind = {}
    telemetry.dispatchedByKind = {}
    telemetry.bytesByKind = {}
    telemetry.rejectedByKind = {}
    telemetry.rejectedByReason = {}
    telemetry.rejectedContractByKind = {}
    telemetry.unknownOpcodeByKind = {}
    telemetry.handlerErrorByKind = {}
    telemetry.bySender = {}
    telemetry.rollingWindow = {}
    telemetry.dispatchedRollingWindow = {}
    telemetry.lastReceivedAt = 0
    telemetry.lastDispatchedAt = 0
    telemetry.lastDispatchedSender = ""
    telemetry.lastRejectedAt = 0
    telemetry.lastRejectedReason = ""
    telemetry.lastRejectedContractKind = ""
    telemetry.lastRejectedContractAt = 0
    telemetry.lastUnknownOpcode = ""
    telemetry.lastUnknownOpcodeAt = 0
    telemetry.lastHandlerErrorAt = 0
    telemetry.lastHandlerErrorKind = ""
    telemetry.lastHandlerErrorSender = ""
    telemetry.lastHandlerErrorDetail = ""
  end

  ops.activitySnapshot = function(recentSeconds)
    local now = GetNow()
    ops.prune(now)
    local rollingBytes = 0
    local recentCutoff = now - math.max(1, tonumber(recentSeconds) or 2)
    local recentSenders = {}
    local seenSenders = {}
    local recentSendersTruncated = false
    for index = #telemetry.dispatchedRollingWindow, 1, -1 do
      local sample = telemetry.dispatchedRollingWindow[index]
      rollingBytes = rollingBytes + math.max(0, tonumber(type(sample) == "table" and sample.bytes or 0) or 0)
      local sender = NormalizeCharacterKey(type(sample) == "table" and sample.sender or "")
      local senderKey = string.lower(sender)
      if math.max(0, tonumber(type(sample) == "table" and sample.at or 0) or 0) >= recentCutoff
        and sender ~= ""
        and not seenSenders[senderKey]
      then
        seenSenders[senderKey] = true
        if #recentSenders < 3 then
          recentSenders[#recentSenders + 1] = sender
        else
          recentSendersTruncated = true
        end
      end
    end
    return {
      messageRatePerSecond = #telemetry.dispatchedRollingWindow
        / math.max(1, tonumber(telemetry.rollingWindowSeconds) or 10),
      byteRatePerSecond = rollingBytes / math.max(1, tonumber(telemetry.rollingWindowSeconds) or 10),
      lastDispatchedAt = math.max(0, tonumber(telemetry.lastDispatchedAt) or 0),
      lastDispatchedSender = NormalizeCharacterKey(telemetry.lastDispatchedSender),
      recentSenders = recentSenders,
      recentSendersTruncated = recentSendersTruncated,
      active = math.max(0, tonumber(telemetry.lastDispatchedAt) or 0) >= recentCutoff
        and #telemetry.dispatchedRollingWindow > 0,
    }
  end

  ops.snapshot = function()
    ops.prune(GetNow())
    local rollingBytes = 0
    for _, sample in ipairs(telemetry.rollingWindow) do
      rollingBytes = rollingBytes + math.max(0, tonumber(type(sample) == "table" and sample.bytes or 0) or 0)
    end
    local function CopyCounterMap(source)
      local copy = {}
      for key, value in pairs(type(source) == "table" and source or {}) do
        copy[key] = math.max(0, tonumber(value) or 0)
      end
      return copy
    end
    local stageByKind = {}
    for kind, stageCounts in pairs(telemetry.stageByKind) do
      stageByKind[kind] = CopyCounterMap(stageCounts)
    end
    local rejectionCategories = {
      rate_limited = 0,
      malformed = 0,
      admission_drop = 0,
      stale = 0,
      handler_failure = 0,
      unknown_opcode = 0,
    }
    for reason, count in pairs(telemetry.rejectedByReason) do
      local category = INTERNAL_API.LIDCOUNCIL_ClassifyInboundRejectReason_Impl(reason)
      rejectionCategories[category] = math.max(0, tonumber(rejectionCategories[category]) or 0)
        + math.max(0, tonumber(count) or 0)
    end
    local senderTotals = {}
    for senderKey, entry in pairs(telemetry.bySender) do
      if type(entry) == "table" then
        senderTotals[senderKey] = {
          messages = math.max(0, tonumber(entry.messages) or 0),
          bytes = math.max(0, tonumber(entry.bytes) or 0),
          rejected = math.max(0, tonumber(entry.rejected) or 0),
          handlerErrors = math.max(0, tonumber(entry.handlerErrors) or 0),
          dispatched = math.max(0, tonumber(entry.dispatched) or 0),
          lastDispatchedAt = math.max(0, tonumber(entry.lastDispatchedAt) or 0),
          sender = NormalizeCharacterKey(entry.sender or senderKey),
          updatedAt = math.max(0, tonumber(entry.updatedAt) or 0),
        }
      end
    end
    local activity = ops.activitySnapshot(2)
    return {
      receivedTotal = math.max(0, tonumber(telemetry.receivedTotal) or 0),
      receivedBytes = math.max(0, tonumber(telemetry.receivedBytes) or 0),
      dispatchedTotal = math.max(0, tonumber(telemetry.dispatchedTotal) or 0),
      rejectedTotal = math.max(0, tonumber(telemetry.rejectedTotal) or 0),
      rejectedContractTotal = math.max(0, tonumber(telemetry.rejectedContractTotal) or 0),
      unknownOpcodeTotal = math.max(0, tonumber(telemetry.unknownOpcodeTotal) or 0),
      staleSessionBoundDropTotal = math.max(0, tonumber(telemetry.staleSessionBoundDropTotal) or 0),
      handlerErrorTotal = math.max(0, tonumber(telemetry.handlerErrorTotal) or 0),
      byKind = CopyCounterMap(telemetry.byKind),
      stageByKind = stageByKind,
      dispatchedByKind = CopyCounterMap(telemetry.dispatchedByKind),
      bytesByKind = CopyCounterMap(telemetry.bytesByKind),
      rejectedByKind = CopyCounterMap(telemetry.rejectedByKind),
      rejectedByReason = CopyCounterMap(telemetry.rejectedByReason),
      rejectionCategories = rejectionCategories,
      rejectedContractByKind = CopyCounterMap(telemetry.rejectedContractByKind),
      unknownOpcodeByKind = CopyCounterMap(telemetry.unknownOpcodeByKind),
      handlerErrorByKind = CopyCounterMap(telemetry.handlerErrorByKind),
      bySender = senderTotals,
      messageRatePerSecond = #telemetry.rollingWindow / math.max(1, tonumber(telemetry.rollingWindowSeconds) or 10),
      byteRatePerSecond = rollingBytes / math.max(1, tonumber(telemetry.rollingWindowSeconds) or 10),
      dispatchedMessageRatePerSecond = math.max(0, tonumber(activity.messageRatePerSecond) or 0),
      dispatchedByteRatePerSecond = math.max(0, tonumber(activity.byteRatePerSecond) or 0),
      windowSeconds = math.max(1, tonumber(telemetry.rollingWindowSeconds) or 10),
      maxPayloadBytes = math.max(1, tonumber(telemetry.maxPayloadBytes) or 1024),
      maxPayloadFields = math.max(1, tonumber(telemetry.maxPayloadFields) or 40),
      lastReceivedAt = math.max(0, tonumber(telemetry.lastReceivedAt) or 0),
      lastDispatchedAt = math.max(0, tonumber(telemetry.lastDispatchedAt) or 0),
      lastDispatchedSender = NormalizeCharacterKey(telemetry.lastDispatchedSender),
      lastRejectedAt = math.max(0, tonumber(telemetry.lastRejectedAt) or 0),
      lastRejectedReason = TrimText(telemetry.lastRejectedReason),
      lastRejectedContractKind = TrimText(telemetry.lastRejectedContractKind),
      lastRejectedContractAt = math.max(0, tonumber(telemetry.lastRejectedContractAt) or 0),
      lastUnknownOpcode = TrimText(telemetry.lastUnknownOpcode),
      lastUnknownOpcodeAt = math.max(0, tonumber(telemetry.lastUnknownOpcodeAt) or 0),
      lastHandlerErrorAt = math.max(0, tonumber(telemetry.lastHandlerErrorAt) or 0),
      lastHandlerErrorKind = TrimText(telemetry.lastHandlerErrorKind),
      lastHandlerErrorSender = TrimText(telemetry.lastHandlerErrorSender),
      lastHandlerErrorDetail = TrimText(telemetry.lastHandlerErrorDetail),
    }
  end

  return telemetry, ops
end
