/**
 * Result formatters for search responses.
 *
 * These produce human-readable (Markdown) strings for use in REST API
 * responses and MCP tool outputs.
 */

import type { LibrarySearchResult, SnippetSearchResult } from './search.service';

// ---------------------------------------------------------------------------
// Library search formatter  (`resolve-library-id`)
// ---------------------------------------------------------------------------

/**
 * Format library search results for the `resolve-library-id` MCP tool.
 */
export function formatLibraryResults(results: LibrarySearchResult[]): string {
	if (results.length === 0) {
		return 'No libraries found matching your search.';
	}

	return results
		.map((r, i) => {
			const repo = r.repository;
			const versions = r.versions.map((v) => v.tag).join(', ') || 'default branch';
			return [
				`${i + 1}. ${repo.title}`,
				`   Library ID: ${repo.id}`,
				`   Description: ${repo.description ?? 'No description'}`,
				`   Snippets: ${repo.totalSnippets ?? 0} | Trust Score: ${(repo.trustScore ?? 0).toFixed(1)}/10`,
				`   Available Versions: ${versions}`
			].join('\n');
		})
		.join('\n\n');
}

// ---------------------------------------------------------------------------
// Snippet search formatter  (`query-docs`)
// ---------------------------------------------------------------------------

/**
 * Format snippet search results for the `query-docs` MCP tool.
 *
 * @param results - Ranked snippet search results.
 * @param rules   - Optional repository rules injected before the snippets.
 */
export function formatSnippetResults(results: SnippetSearchResult[], rules?: string[]): string {
	const parts: string[] = [];

	// Prepend repository rules when present.
	if (rules?.length) {
		parts.push('## Library Rules\n' + rules.map((r) => `- ${r}`).join('\n'));
	}

	for (const { snippet } of results) {
		if (snippet.type === 'code') {
			parts.push(
				[
					snippet.title ? `### ${snippet.title}` : '',
					snippet.breadcrumb ? `*${snippet.breadcrumb}*` : '',
					`\`\`\`${snippet.language ?? ''}\n${snippet.content}\n\`\`\``
				]
					.filter(Boolean)
					.join('\n')
			);
		} else {
			parts.push(
				[
					snippet.title ? `### ${snippet.title}` : '',
					snippet.breadcrumb ? `*${snippet.breadcrumb}*` : '',
					snippet.content
				]
					.filter(Boolean)
					.join('\n')
			);
		}
	}

	return parts.join('\n\n---\n\n');
}
