import { z } from "zod";
import { fetchImageFromUrl } from "../../services/image.service.ts";

interface ToolResult {
	content: Array<{ type: "text"; text: string }>;
}

function textResult(data: unknown): ToolResult {
	return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
}

function errorResult(message: string): ToolResult {
	return {
		content: [{ type: "text", text: JSON.stringify({ error: message }) }],
	};
}

export const imageToolDefinitions = [
	{
		name: "upload_image_from_url",
		description:
			"Fetch an image from a URL and upload it to storage. Returns the filename to use with create_item or add_candidate.",
		inputSchema: {
			url: z
				.string()
				.describe("URL of the image to fetch (jpeg, png, or webp)"),
		},
	},
];

export function registerImageTools() {
	return {
		upload_image_from_url: async (args: {
			url: string;
		}): Promise<ToolResult> => {
			try {
				const result = await fetchImageFromUrl(args.url);
				return textResult(result);
			} catch (err) {
				return errorResult((err as Error).message);
			}
		},
	};
}
