import type { ToolResultContent } from '../tools/common.js';
import type { ServerToolStructuredResult } from '../gateway/protocol.js';
import type { ResolvedToolRuntimeRoute } from '../service/tool_resolver.js';
import {
  RuntimeProcessEvent,
  RuntimeProcessLogRef,
  sampleProcessEventsForMetadata,
} from './process_events.js';

export interface ToolExecutionEntry {
  toolCallId: string;
  name: string;
  label?: string;
  args: Record<string, unknown>;
  result?: string;
  rawResult?: ToolResultContent | string;
  status: string;
  runtimeRoute?: 'worker-local' | 'main-process-proxy' | 'disabled';
  workerRoutingHint?: 'local' | 'main-process-proxy' | 'disabled';
  blockedReason?: string | null;
  policySources?: string[];
  processEvents?: RuntimeProcessEvent[];
  processLogRef?: RuntimeProcessLogRef;
}

export function toStructuredToolResult(
  result: ToolResultContent | string | undefined,
): ServerToolStructuredResult | undefined {
  if (!result || typeof result === 'string') {
    return undefined;
  }
  if (result.type === 'text') {
    return { type: 'text', text: result.text };
  }
  if (result.type === 'json') {
    return { type: 'json', data: result.data };
  }
  if (result.type === 'image') {
    return {
      type: 'image',
      url: result.url,
      mimeType: result.mimeType,
      text: result.text,
      width: result.width,
      height: result.height,
      bytes: result.bytes,
      originalWidth: result.originalWidth,
      originalHeight: result.originalHeight,
      originalBytes: result.originalBytes,
      resized: result.resized,
    };
  }
  if (result.type === 'images') {
    return {
      type: 'images',
      text: result.text,
      images: result.images,
    };
  }
  return undefined;
}

export function buildToolRouteMap(
  toolManifest: ResolvedToolRuntimeRoute[] = [],
): Map<string, ResolvedToolRuntimeRoute> {
  return new Map(toolManifest.map(item => [item.name, item]));
}

export function buildToolExecutionMetadata(
  toolExecutions: ToolExecutionEntry[],
): Record<string, unknown> {
  if (toolExecutions.length === 0) {
    return {};
  }
  return {
    skillExecutions: toolExecutions.map(te => ({
      name: te.name,
      label: te.label || te.name,
      status: te.status === 'done' ? 'done' : 'error',
      args: te.args,
      result: te.result,
      rawResult: toStructuredToolResult(te.rawResult),
      toolCallId: te.toolCallId,
      latestProcessEvent: te.processEvents?.[te.processEvents.length - 1],
      processEvents: sampleProcessEventsForMetadata(te.processEvents || [], 50),
      processLogRef: te.processLogRef,
    })),
  };
}
