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

INTERNAL_API.LIDCOUNCIL_CreateOutboundOpcodeTelemetryHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}
  local stats = type(deps.Stats) == "table" and deps.Stats or {}
  local TrimText = type(deps.TrimText) == "function" and deps.TrimText or function(value)
    return tostring(value or "")
  end
  local EnsureSessionBaseline = type(deps.EnsureSessionBaseline) == "function" and deps.EnsureSessionBaseline or function()
  end

  local function SelectOutboundCommTelemetryOpcodeBucket(kind, byOpcode, maxTrackedOpcodes)
    local resolvedKind = TrimText(kind)
    if resolvedKind == "" then
      resolvedKind = "UNKNOWN"
    end
    byOpcode = type(byOpcode) == "table" and byOpcode or {}
    if type(byOpcode[resolvedKind]) == "table" then
      return resolvedKind, false
    end
    local trackedCount = 0
    for _ in pairs(byOpcode) do
      trackedCount = trackedCount + 1
    end
    if trackedCount >= math.max(1, tonumber(maxTrackedOpcodes) or 48) then
      return "__other__", true
    end
    return resolvedKind, false
  end

  local function RecordOutboundCommOpcodeTelemetry(item, eventName, payloadBytesOverride)
    item = type(item) == "table" and item or {}
    local metadata = type(item.metadata) == "table" and item.metadata or {}
    EnsureSessionBaseline(TrimText(metadata.sessionId))
    local telemetry = type(stats.opcodeTelemetry) == "table" and stats.opcodeTelemetry or {}
    stats.opcodeTelemetry = telemetry
    local byOpcode = type(telemetry.byOpcode) == "table" and telemetry.byOpcode or {}
    telemetry.byOpcode = byOpcode
    local bucketName, overflowed = SelectOutboundCommTelemetryOpcodeBucket(
      item.kind,
      byOpcode,
      telemetry.maxTrackedOpcodes
    )
    local entry
    if overflowed then
      entry = type(telemetry.other) == "table" and telemetry.other or {}
      telemetry.other = entry
    else
      entry = type(byOpcode[bucketName]) == "table" and byOpcode[bucketName] or {}
      byOpcode[bucketName] = entry
    end
    local payloadBytes = math.max(0, tonumber(payloadBytesOverride) or #(tostring(item.payload or "")))
    if eventName == "queued" then
      entry.queuedTotal = math.max(0, tonumber(entry.queuedTotal) or 0) + 1
      entry.bytesQueued = math.max(0, tonumber(entry.bytesQueued) or 0) + payloadBytes
    elseif eventName == "attempted" then
      entry.attempted = math.max(0, tonumber(entry.attempted) or 0) + 1
      entry.bytesAttempted = math.max(0, tonumber(entry.bytesAttempted) or 0) + payloadBytes
    elseif eventName == "sent" then
      entry.sent = math.max(0, tonumber(entry.sent) or 0) + 1
      entry.bytesSent = math.max(0, tonumber(entry.bytesSent) or 0) + payloadBytes
    elseif eventName == "throttled" then
      entry.throttled = math.max(0, tonumber(entry.throttled) or 0) + 1
    elseif eventName == "failed" then
      entry.failed = math.max(0, tonumber(entry.failed) or 0) + 1
    elseif eventName == "payload_rejected" then
      entry.payloadRejected = math.max(0, tonumber(entry.payloadRejected) or 0) + 1
      entry.bytesRejected = math.max(0, tonumber(entry.bytesRejected) or 0) + payloadBytes
    end
    return bucketName, overflowed
  end

  local function GetOutboundCommOpcodeTelemetry()
    local telemetry = type(stats.opcodeTelemetry) == "table" and stats.opcodeTelemetry or {}
    local function buildSnapshot(kind, entry)
      entry = type(entry) == "table" and entry or {}
      return {
        kind = TrimText(kind),
        queuedTotal = math.max(0, tonumber(entry.queuedTotal) or 0),
        attempted = math.max(0, tonumber(entry.attempted) or 0),
        sent = math.max(0, tonumber(entry.sent) or 0),
        throttled = math.max(0, tonumber(entry.throttled) or 0),
        failed = math.max(0, tonumber(entry.failed) or 0),
        payloadRejected = math.max(0, tonumber(entry.payloadRejected) or 0),
        bytesQueued = math.max(0, tonumber(entry.bytesQueued) or 0),
        bytesAttempted = math.max(0, tonumber(entry.bytesAttempted) or 0),
        bytesSent = math.max(0, tonumber(entry.bytesSent) or 0),
        bytesRejected = math.max(0, tonumber(entry.bytesRejected) or 0),
      }
    end
    local opcodes = {}
    for kind, entry in pairs(type(telemetry.byOpcode) == "table" and telemetry.byOpcode or {}) do
      local snapshot = buildSnapshot(kind, entry)
      if snapshot.kind ~= "" then
        opcodes[#opcodes + 1] = snapshot
      end
    end
    local other = buildSnapshot("OTHER", telemetry.other)
    if other.queuedTotal > 0 or other.attempted > 0 or other.sent > 0 or other.payloadRejected > 0 then
      opcodes[#opcodes + 1] = other
    end
    table.sort(opcodes, function(left, right)
      if left.bytesSent ~= right.bytesSent then
        return left.bytesSent > right.bytesSent
      end
      if left.bytesAttempted ~= right.bytesAttempted then
        return left.bytesAttempted > right.bytesAttempted
      end
      if left.queuedTotal ~= right.queuedTotal then
        return left.queuedTotal > right.queuedTotal
      end
      return string.lower(left.kind) < string.lower(right.kind)
    end)
    return {
      maxTrackedOpcodes = math.max(1, tonumber(telemetry.maxTrackedOpcodes) or 48),
      opcodes = opcodes,
    }
  end

  return {
    SelectOutboundCommTelemetryOpcodeBucket = SelectOutboundCommTelemetryOpcodeBucket,
    RecordOutboundCommOpcodeTelemetry = RecordOutboundCommOpcodeTelemetry,
    GetOutboundCommOpcodeTelemetry = GetOutboundCommOpcodeTelemetry,
  }
end
