/** Parsed function call extracted from a message */
export interface FunctionCall {
  functionName: string;
  arguments: string;
  startIndex: number;
  endIndex: number;
  status: 'running' | 'completed';
  authStatus?: 'pending' | 'approved' | 'denied';
  duration?: number;
}

const FUNCTION_CALL_PATTERN = /<\|{(\w+)}\|>\s*([\s\S]*?)(?=<\|{\w+}\|>|$)/g;

/** Extract function calls from a message content string */
export function parseFunctionCalls(content: string): FunctionCall[] {
  const calls: FunctionCall[] = [];
  let match: RegExpExecArray | null;

  FUNCTION_CALL_PATTERN.lastIndex = 0;
  while ((match = FUNCTION_CALL_PATTERN.exec(content)) !== null) {
    const [full, functionName, args] = match;
    calls.push({
      functionName,
      arguments: args.trim(),
      startIndex: match.index,
      endIndex: match.index + full.length,
      status: 'completed',
    });
  }

  return calls;
}

/** Format a duration in seconds to a human-readable string */
export function formatDuration(seconds: number): string {
  if (seconds < 1) return `${Math.round(seconds * 1000)}ms`;
  if (seconds < 60) return `${seconds.toFixed(1)}s`;
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}m ${s}s`;
}
