import { apiClient } from "./client";

export interface ToolDefinitionManifest {
	id: string;
	name: string;
	display_name: string;
	description: string | null;
	category: string | null;
	interface_type: string;
	base_image: string | null;
	base_definition_id: string | null;
	base_version: string;
	manifest: Record<string, unknown>;
	dockerfile_cache: string | null;
	compose_cache: string | null;
	version: string;
	is_base: boolean;
	created_at: string;
	updated_at: string;
}

export interface CreateToolDefinitionRequest {
	name: string;
	display_name: string;
	description?: string;
	category?: string;
	interface_type?: string;
	base_image?: string;
	base_definition_id?: string;
	base_version?: string;
	manifest: Record<string, unknown>;
}

export interface UpdateToolDefinitionRequest {
	display_name?: string;
	description?: string;
	category?: string;
	manifest?: Record<string, unknown>;
	base_version?: string;
}

export interface CompileResult {
	id: string;
	name: string;
	dockerfile: string;
	entrypoint: string;
	compose: string;
	image_tag: string;
}

export const listToolDefinitions = async (
	includeBases = true,
): Promise<ToolDefinitionManifest[]> => {
	const response = await apiClient.get<{
		definitions: ToolDefinitionManifest[];
	}>("/tool-definitions", {
		params: { include_bases: includeBases },
	});
	return response.data.definitions;
};

export const getToolDefinition = async (
	id: string,
): Promise<ToolDefinitionManifest> => {
	const response = await apiClient.get<ToolDefinitionManifest>(
		`/tool-definitions/${id}`,
	);
	return response.data;
};

export const createToolDefinition = async (
	data: CreateToolDefinitionRequest,
): Promise<ToolDefinitionManifest> => {
	const response = await apiClient.post<ToolDefinitionManifest>(
		"/tool-definitions",
		data,
	);
	return response.data;
};

export const updateToolDefinition = async (
	id: string,
	data: UpdateToolDefinitionRequest,
): Promise<ToolDefinitionManifest> => {
	const response = await apiClient.put<ToolDefinitionManifest>(
		`/tool-definitions/${id}`,
		data,
	);
	return response.data;
};

export const deleteToolDefinition = async (
	id: string,
): Promise<{ status: string; id: string }> => {
	const response = await apiClient.delete<{ status: string; id: string }>(
		`/tool-definitions/${id}`,
	);
	return response.data;
};

export const compileToolDefinition = async (
	id: string,
): Promise<CompileResult> => {
	const response = await apiClient.post<CompileResult>(
		`/tool-definitions/${id}/compile`,
	);
	return response.data;
};
