/**
 * Compact chat messages into a summarizer-friendly transcript.
 *
 * Raw tool_use / tool_result blocks can each carry kilobytes of JSON
 * (stack traces, encoded args, HTML responses). Feeding those into the
 * summarizer LLM wastes input tokens and crowds out actual dialogue.
 *
 * This module flattens each Message into one or more text lines:
 *   - text blocks pass through (truncated to MAX_TEXT_CHARS)
 *   - tool_use → `tool[name](key1, key2, …)`
 *   - tool_result → `→ ok: <first line>` or `→ err: <first line>`
 *
 * Output is a plain string ready to drop into the summarizer prompt.
 */

import type { ContentBlock, Message, ToolResultBlock, ToolUseBlock } from '../chat/types';

const MAX_TEXT_CHARS = 1200;
const MAX_TOOL_RESULT_CHARS = 200;
const MAX_INPUT_KEYS = 8;

export function compressMessagesForSummarizer(messages: Message[]): string {
  const lines: string[] = [];
  for (const m of messages) {
    for (const block of m.blocks) {
      const rendered = renderBlock(m.role, block);
      if (rendered) lines.push(rendered);
    }
  }
  return lines.join('\n');
}

function renderBlock(role: 'user' | 'assistant', block: ContentBlock): string | null {
  if (block.type === 'text') {
    const text = truncate(block.text.trim(), MAX_TEXT_CHARS);
    if (!text) return null;
    return `${role}: ${text}`;
  }
  if (block.type === 'tool_use') {
    return `${role}: ${renderToolUse(block)}`;
  }
  if (block.type === 'tool_result') {
    return `${role}: ${renderToolResult(block)}`;
  }
  return null;
}

function renderToolUse(block: ToolUseBlock): string {
  const keys = block.input && typeof block.input === 'object'
    ? Object.keys(block.input as Record<string, unknown>).slice(0, MAX_INPUT_KEYS)
    : [];
  const argsStr = keys.length > 0 ? `(${keys.join(', ')})` : '()';
  return `tool[${block.name}]${argsStr}`;
}

function renderToolResult(block: ToolResultBlock): string {
  const firstLine = (block.content ?? '').split(/\r?\n/, 1)[0] ?? '';
  const head = truncate(firstLine, MAX_TOOL_RESULT_CHARS);
  return block.is_error ? `→ err: ${head}` : `→ ok: ${head}`;
}

function truncate(s: string, max: number): string {
  if (s.length <= max) return s;
  return s.slice(0, max) + '…';
}
