import type { NetaClawSubagentTask } from './subagent.js';
import type { SubagentWorkerResult } from '../subagent/process_protocol.js';

export interface NormalizedSubagentToolResult {
  name: string;
  label?: string;
  result: string;
  toolCallId?: string;
}

export interface SubagentEvidenceSummary {
  kind: 'file-count' | 'tool-preview';
  title: string;
  summary: string;
  files?: string[];
  count?: number;
  previews?: string[];
}

export function normalizeSubagentToolResults(
  toolResults?: SubagentWorkerResult['toolResults']
): NormalizedSubagentToolResult[] {
  if (!Array.isArray(toolResults)) {
    return [];
  }

  return toolResults
    .filter(item => item && typeof item.name === 'string')
    .map(item => ({
      name: item.name,
      label: typeof item.label === 'string' ? item.label : undefined,
      result: typeof item.result === 'string' ? item.result : String(item.result ?? ''),
      toolCallId: typeof item.toolCallId === 'string' ? item.toolCallId : undefined,
    }))
    .filter(item => item.result.trim().length > 0);
}

export function buildSubagentEvidenceSummary(
  task: Pick<NetaClawSubagentTask, 'goal' | 'context'>,
  toolResults?: SubagentWorkerResult['toolResults']
): SubagentEvidenceSummary | null {
  const normalizedResults = normalizeSubagentToolResults(toolResults);
  if (normalizedResults.length === 0) {
    return null;
  }

  const taskText = `${task.goal}\n${task.context ?? ''}`.toLowerCase();
  const combinedEvidence = normalizedResults.map(item => item.result).join('\n');
  const wantsImages = /(image|images|picture|pictures|photo|photos|图片|照片|图像)/i.test(taskText);
  const wantsXlsx = /(xlsx|excel|电子表格|表格)/i.test(taskText);

  if (wantsImages) {
    const files = extractUniqueFilenamesByExtensions(
      combinedEvidence,
      ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'tif', 'svg']
    );
    if (files.length > 0) {
      return createFileCountSummary('图片文件', files);
    }
  }

  if (wantsXlsx) {
    const files = extractUniqueFilenamesByExtensions(combinedEvidence, ['xlsx']);
    if (files.length > 0) {
      return createFileCountSummary('.xlsx 文件', files);
    }
  }

  const previews = normalizedResults
    .slice(0, 3)
    .map(item => {
      const preview = item.result.replace(/\s+/g, ' ').trim().slice(0, 240);
      return `- ${item.name}: ${preview}`;
    })
    .filter(line => line.trim().length > 0);

  if (previews.length === 0) {
    return null;
  }

  return {
    kind: 'tool-preview',
    title: '工具证据摘要',
    summary: [
      '子代理已完成工具检查，但未输出最终结论。以下是可用工具证据摘要：',
      ...previews,
    ].join('\n'),
    previews,
  };
}

function createFileCountSummary(label: string, files: string[]): SubagentEvidenceSummary {
  const listedFiles = files.slice(0, 20).map(file => `- ${file}`);
  const omittedCount = files.length - listedFiles.length;
  return {
    kind: 'file-count',
    title: `${label}统计`,
    count: files.length,
    files,
    summary: [
      `根据工具结果统计，${label}共 ${files.length} 个。`,
      ...listedFiles,
      omittedCount > 0 ? `- ...另有 ${omittedCount} 个未列出` : '',
    ].filter(Boolean).join('\n'),
  };
}

function extractUniqueFilenamesByExtensions(text: string, extensions: string[]): string[] {
  const extensionPattern = extensions
    .map(extension => extension.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
    .join('|');
  const regex = new RegExp(`[^\\s\\r\\n\\\\/:*?"<>|]+\\.(${extensionPattern})\\b`, 'gi');
  const seen = new Set<string>();
  const files: string[] = [];

  for (const match of text.matchAll(regex)) {
    const filename = match[0].trim();
    const key = filename.toLowerCase();
    if (seen.has(key)) {
      continue;
    }
    seen.add(key);
    files.push(filename);
  }

  return files;
}
