export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
export type JsonRecord = Record<string, JsonValue>;

export interface PromptObservationTask {
  prompt: string;
  basePrompt: string;
}

export interface PromptObservationOptions {
  lite?: boolean;
  userPromptForDisplay: (prompt: string) => string;
}

export function safePreview(value: unknown, maxChars: number): string {
  const text = String(value ?? "");
  if (text.length <= maxChars) return text;
  return `${text.slice(0, Math.max(0, maxChars - 20))}\n...<truncated>`;
}

export function textPreview(value: unknown, maxChars: number): JsonRecord {
  const text = String(value ?? "");
  const truncated = text.length > maxChars;
  return {
    text: truncated ? safePreview(text, maxChars) : text,
    chars: text.length,
    truncated,
    omittedChars: truncated ? text.length - Math.max(0, maxChars - 20) : 0,
  };
}

export function codeQueuePromptResponseFields(task: PromptObservationTask, options: PromptObservationOptions): JsonRecord {
  const displayPrompt = task.basePrompt || options.userPromptForDisplay(task.prompt);
  const previewLimit = options.lite === true ? 360 : 2000;
  return {
    prompt: task.prompt,
    basePrompt: task.basePrompt,
    displayPrompt,
    promptPreview: textPreview(task.prompt, previewLimit),
    basePromptPreview: textPreview(task.basePrompt, previewLimit),
    displayPromptPreview: textPreview(displayPrompt, previewLimit),
    promptChars: task.prompt.length,
    basePromptChars: task.basePrompt.length,
    displayPromptChars: displayPrompt.length,
  };
}
