import type { NormalizedFetchResponse, NormalizedSearchResponse } from "./providers/types.ts";

export function truncateText(text: string, maxCharacters = 4000) {
  if (text.length <= maxCharacters) {
    return text;
  }
  return `${text.slice(0, Math.max(0, maxCharacters - 1))}…`;
}

export function formatSearchOutput(response: NormalizedSearchResponse) {
  if (response.results.length === 0) {
    return `No web results via ${response.providerName}.`;
  }

  const lines = [
    `Found ${response.results.length} web result${response.results.length === 1 ? "" : "s"} via ${response.providerName}:`,
  ];

  for (const [index, result] of response.results.entries()) {
    lines.push(`${index + 1}. ${result.title ?? "(untitled)"}`);
    lines.push(`   URL: ${result.url}`);

    const meta = [result.publishedDate, result.author].filter(Boolean);
    if (meta.length > 0) {
      lines.push(`   Meta: ${meta.join(" • ")}`);
    }

    if (typeof result.score === "number") {
      lines.push(`   Score: ${result.score}`);
    }
  }

  return lines.join("\n");
}

export interface FetchFormatOptions {
  maxCharactersPerResult?: number;
}

export function formatFetchOutput(response: NormalizedFetchResponse, options: FetchFormatOptions = {}) {
  const maxCharactersPerResult = options.maxCharactersPerResult ?? 4000;
  const lines = [
    `Fetched ${response.results.length} URL${response.results.length === 1 ? "" : "s"} via ${response.providerName}:`,
  ];

  for (const result of response.results) {
    lines.push("");
    lines.push(`URL: ${result.url}`);

    if (result.error) {
      lines.push("Status: failed");
      lines.push(`Error: ${result.error}`);
      continue;
    }

    lines.push("Status: ok");
    if (result.title) {
      lines.push(`Title: ${result.title}`);
    }
    if (result.summary) {
      lines.push(`Summary: ${result.summary}`);
    }
    if (result.highlights?.length) {
      lines.push("Highlights:");
      for (const highlight of result.highlights) {
        lines.push(`- ${highlight}`);
      }
    }
    if (result.text) {
      lines.push("Text:");
      lines.push(truncateText(result.text, maxCharactersPerResult));
    }
  }

  return lines.join("\n");
}
