import { normalizeWhitespace, truncateText } from "@best-agent/foundation";
import type { ToolInputValue } from "@best-agent/protocol";

export function formatToolInputForPrompt(input: ToolInputValue): string {
  return typeof input === "string" ? input : JSON.stringify(input);
}

export function truncateForReasoning(value: string, maxLength = 240): string {
  return truncateText(normalizeWhitespace(value), maxLength);
}

export function truncateTitle(value: string): string {
  return truncateText(normalizeWhitespace(value), 60);
}

export function previewDebugText(value: string, maxLength: number): string {
  return value.length <= maxLength ? value : `${value.slice(0, maxLength)}...[truncated]`;
}

export function previewToolInputForDebugLog(input: ToolInputValue): unknown {
  if (typeof input === "string") {
    return previewDebugText(input, 500);
  }
  if (Array.isArray(input)) {
    return input
      .slice(0, 12)
      .map((value) => (typeof value === "string" ? previewDebugText(value, 240) : value));
  }
  if (!input || typeof input !== "object") {
    return input;
  }
  const output: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(input)) {
    if (typeof value === "string") {
      output[key] = previewDebugText(value, 500);
      continue;
    }
    if (Array.isArray(value)) {
      output[key] = value
        .slice(0, 12)
        .map((item) => (typeof item === "string" ? previewDebugText(item, 240) : item));
      continue;
    }
    output[key] = value;
  }
  return output;
}

export function extractInlinePaths(value: string): string[] {
  return value
    .split(/\s+/)
    .map((part) => part.trim())
    .filter((part) => part.includes("/") || part.includes("."));
}

export function sleep(durationMs: number): Promise<void> {
  return new Promise((resolve) => {
    setTimeout(resolve, durationMs);
  });
}
