type RuntimeGlobals = typeof globalThis & {
  process?: Pick<NodeJS.Process, 'env'>
}

function runtimeGlobals(): RuntimeGlobals {
  return globalThis as RuntimeGlobals
}

function readPositiveInt(
  key: string,
  fallback: number,
  min: number,
  max: number,
): number {
  const raw = String(runtimeGlobals().process?.env?.[key] ?? '').trim()
  if (!raw)
    return fallback
  const n = Number(raw)
  if (!Number.isFinite(n) || n <= 0)
    return fallback
  return Math.max(min, Math.min(max, Math.floor(n)))
}

export const MAX_EXPANDED_TOOL_OUTPUT_LINES = readPositiveInt(
  'DIMCODE_TOOL_OUTPUT_MAX_LINES',
  2000,
  1,
  50_000,
)

export const INITIAL_EXPANDED_TOOL_OUTPUT_LINES = Math.min(
  MAX_EXPANDED_TOOL_OUTPUT_LINES,
  readPositiveInt(
    'DIMCODE_TOOL_OUTPUT_INITIAL_LINES',
    200,
    20,
    MAX_EXPANDED_TOOL_OUTPUT_LINES,
  ),
)

export const LOAD_MORE_TOOL_OUTPUT_LINES = Math.min(
  MAX_EXPANDED_TOOL_OUTPUT_LINES,
  readPositiveInt(
    'DIMCODE_TOOL_OUTPUT_LOAD_MORE_LINES',
    200,
    20,
    MAX_EXPANDED_TOOL_OUTPUT_LINES,
  ),
)

export function clampExpandedToolOutputLines(count: number): number {
  if (!Number.isFinite(count) || count <= 0)
    return INITIAL_EXPANDED_TOOL_OUTPUT_LINES
  return Math.max(
    1,
    Math.min(MAX_EXPANDED_TOOL_OUTPUT_LINES, Math.floor(count)),
  )
}
