/**
 * resolve-library-id tool handler
 *
 * Searches TrueRef to find a library matching the given name.
 * Tool schema is identical to context7 for drop-in compatibility.
 */

import { z } from 'zod';
import { searchLibraries } from '../client.js';

export const ResolveLibraryIdSchema = z.object({
	libraryName: z.string().describe('Library name to search for and resolve to a TrueRef library ID'),
	query: z.string().describe("The user's question or context to help rank results")
});

export type ResolveLibraryIdInput = z.infer<typeof ResolveLibraryIdSchema>;

export const RESOLVE_LIBRARY_ID_TOOL = {
	name: 'resolve-library-id',
	description: [
		'Searches TrueRef to find a library matching the given name.',
		'Returns a list of matching libraries with their IDs.',
		'ALWAYS call this tool before query-docs to get the correct library ID.',
		'Call at most 3 times per user question.'
	].join(' '),
	inputSchema: {
		type: 'object' as const,
		properties: {
			libraryName: {
				type: 'string',
				description: 'Library name to search for'
			},
			query: {
				type: 'string',
				description: "User's question for relevance ranking"
			}
		},
		required: ['libraryName', 'query']
	}
};

export async function handleResolveLibraryId(args: unknown) {
	const { libraryName, query } = ResolveLibraryIdSchema.parse(args);

	const response = await searchLibraries({ libraryName, query, type: 'txt' });

	if (!response.ok) {
		return {
			content: [
				{
					type: 'text' as const,
					text: `Error searching libraries: ${response.status} ${response.statusText}`
				}
			],
			isError: true
		};
	}

	const text = await response.text();
	return {
		content: [{ type: 'text' as const, text }]
	};
}
