export interface ActivityLogMetadata {
  workerId?: string | null;
  mode?: string | null;
  /** Physical backend behind a proxy worker (gateway-resolved), if known. */
  backendId?: string | null;
}

const TOOL_SUMMARY_KEYS = [
  'file_path',
  'output_path',
  'path',
  'image_path',
  'text_path',
  'pdf_path',
  'input_glob',
  'pattern',
  'url',
  'query',
  'username',
  'tweet',
  'name',
] as const;

export function formatActivityLogMetadata(metadata?: ActivityLogMetadata): string {
  if (!metadata) return '';
  const segments: string[] = [];
  if (metadata.workerId) segments.push(`[worker:${metadata.workerId}]`);
  if (metadata.mode) segments.push(`[mode:${metadata.mode}]`);
  if (metadata.backendId) segments.push(`[backend:${metadata.backendId}]`);
  return segments.join(' ');
}

export function formatActivityLogEntry(entry: string, metadata?: ActivityLogMetadata): string {
  const prefix = formatActivityLogMetadata(metadata);
  return prefix ? `${prefix} ${entry}` : entry;
}

export function parseActivityLogMetadata(line: string): ActivityLogMetadata {
  const workerMatch = /\[worker:([^\]]+)\]/.exec(line);
  const modeMatch = /\[mode:([^\]]+)\]/.exec(line);
  const backendMatch = /\[backend:([^\]]+)\]/.exec(line);
  return {
    workerId: workerMatch?.[1] ?? null,
    mode: modeMatch?.[1] ?? null,
    backendId: backendMatch?.[1] ?? null,
  };
}

export function summarizeToolInput(toolName: string, input: Record<string, unknown>): string {
  if (toolName === 'Bash') {
    return truncateLogText(String(input['command'] ?? ''), 140);
  }

  for (const key of TOOL_SUMMARY_KEYS) {
    const value = input[key];
    if (typeof value === 'string' && value.trim()) {
      return truncateLogText(value, 180);
    }
  }

  if (Array.isArray(input['file_paths'])) {
    const filePaths = (input['file_paths'] as unknown[]).filter((value): value is string => typeof value === 'string');
    if (filePaths.length > 0) {
      return truncateLogText(filePaths.slice(0, 3).join(', '), 180);
    }
  }

  return truncateLogText(JSON.stringify(input), 180);
}

export function truncateLogText(text: string, limit: number = 220): string {
  const normalized = text.replace(/\s+/g, ' ').trim();
  if (normalized.length <= limit) return normalized;
  return `${normalized.slice(0, limit - 3)}...`;
}

/**
 * Format a wall-clock duration for activity.log. Sub-second values keep
 * "Nms" precision (useful for cache hits / fast tools). Anything ≥ 1s
 * collapses to "N.Ns" for readability ("12.4s" instead of "12376ms").
 */
export function formatDuration(ms: number): string {
  if (!Number.isFinite(ms) || ms < 0) return '?';
  if (ms < 1000) return `${Math.round(ms)}ms`;
  return `${(ms / 1000).toFixed(1)}s`;
}
