export interface AgentObserverRuntimeConfig {
  nodeId: string;
  lane: string;
  reconnectDelayMs: number;
  batchMaxEvents: number;
  liveBufferLimit: number;
  identityWindowLimit: number;
  reducerEventLimit: number;
  reducerEntityLimit: number;
  treeNodeLimit: number;
  inspectorEventTailLimit: number;
  virtualListWindowLimit: number;
  changeHighlightMs: number;
  staleAfterMs: number;
  reducedMotion: "respect-system";
}

export function agentObserverRuntimeConfig(): AgentObserverRuntimeConfig | null {
  const value = window.HWLAB_CLOUD_WEB_CONFIG?.agentObserver;
  if (!value) return null;
  const config = {
    nodeId: text(value.nodeId),
    lane: text(value.lane),
    reconnectDelayMs: positive(value.reconnectDelayMs),
    batchMaxEvents: positive(value.batchMaxEvents),
    liveBufferLimit: positive(value.liveBufferLimit),
    identityWindowLimit: positive(value.identityWindowLimit),
    reducerEventLimit: positive(value.reducerEventLimit),
    reducerEntityLimit: positive(value.reducerEntityLimit),
    treeNodeLimit: positive(value.treeNodeLimit),
    inspectorEventTailLimit: positive(value.inspectorEventTailLimit),
    virtualListWindowLimit: positive(value.virtualListWindowLimit),
    changeHighlightMs: nonNegative(value.changeHighlightMs),
    staleAfterMs: positive(value.staleAfterMs),
    reducedMotion: value.reducedMotion
  };
  if (Object.values(config).some((entry) => entry === null) || config.reducedMotion !== "respect-system") return null;
  return config as AgentObserverRuntimeConfig;
}

function positive(value: unknown): number | null {
  const number = Number(value);
  return Number.isInteger(number) && number > 0 ? number : null;
}

function nonNegative(value: unknown): number | null {
  const number = Number(value);
  return Number.isInteger(number) && number >= 0 ? number : null;
}

function text(value: unknown): string | null {
  return typeof value === "string" && value.trim() ? value.trim() : null;
}
