const require_fetcher = require('../fetcher.cjs');
const require_built = require('../config/dist/esm/built.cjs');

//#region ../@intlayer/cli/dist/esm/api/dist/esm/getIntlayerAPI/ai.mjs
const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
	const backendURL = intlayerConfig?.editor?.backendURL ?? require_built.built_default?.editor?.backendURL;
	if (!backendURL) throw new Error("Backend URL is not defined in the Intlayer configuration.");
	const AI_API_ROUTE = `${backendURL}/api/ai`;
	/**
	* Custom query
	* @param body - Custom query parameters.
	* @returns Custom query result.
	*/
	const customQuery = async (body, otherOptions = {}) => await require_fetcher.fetcher(AI_API_ROUTE, authAPIOptions, otherOptions, {
		method: "POST",
		body
	});
	/**
	* Translate a JSON
	* @param body - Audit file parameters.
	* @returns Audited file content.
	*/
	const translateJSON = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/translate/json`, authAPIOptions, otherOptions, {
		method: "POST",
		body
	});
	/**
	* Audits a content declaration file
	* @param body - Audit file parameters.
	* @returns Audited file content.
	*/
	const auditContentDeclaration = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/audit/dictionary`, authAPIOptions, otherOptions, {
		method: "POST",
		body
	});
	/**
	* Audits a content declaration field
	* @param body - Audit file parameters.
	* @returns Audited file content.
	*/
	const auditContentDeclarationField = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/audit/dictionary/field`, authAPIOptions, otherOptions, {
		method: "POST",
		body
	});
	/**
	* Audits a content declaration file to retrieve title, description and tags
	* @param body - Audit file parameters.
	* @returns Audited file content.
	*/
	const auditContentDeclarationMetadata = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/audit/dictionary/metadata`, authAPIOptions, otherOptions, {
		method: "POST",
		body
	});
	/**
	* Audits a tag
	* @param body - Audit tag parameters.
	* @returns Audited tag content.
	*/
	const auditTag = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/audit/tag`, authAPIOptions, otherOptions, {
		method: "POST",
		body
	});
	/**
	* Asks a question to the AI related to the documentation **and streams the
	* answer as Server‑Sent Events (SSE)**.
	*
	* The function **returns immediately** with a handle exposing:
	* - `promise` → resolves when the stream completes (or rejects on error)
	* - `abort()` → allows canceling the request on demand
	*
	* Usage example:
	* ```ts
	* const { promise, abort } = ai.askDocQuestion({
	*   ...body,
	*   onMessage: console.log,
	*   onDone: (full) => console.log("✔", full),
	* });
	* // later → abort();
	* await promise; // waits for completion if desired
	* ```
	*/
	const askDocQuestion = async (body, otherOptions = {}) => {
		if (!body) return;
		const { onMessage, onDone,...rest } = body;
		const abortController = new AbortController();
		try {
			const response = await fetch(`${AI_API_ROUTE}/ask`, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					...authAPIOptions.headers,
					...otherOptions.headers
				},
				body: JSON.stringify({
					...rest,
					...authAPIOptions.body,
					...otherOptions.body
				}),
				signal: abortController.signal,
				credentials: "include"
			});
			if (!response.ok) {
				let errorMessage = "An error occurred";
				try {
					const errorData = await response.json();
					errorMessage = JSON.stringify(errorData.error) ?? "An error occurred";
				} catch {
					try {
						const errorText = await response.text();
						if (errorText) errorMessage = errorText;
					} catch {}
				}
				throw new Error(errorMessage);
			}
			const reader = response.body?.getReader();
			if (!reader) throw new Error("No reader available");
			const decoder = new TextDecoder();
			let buffer = "";
			while (true) {
				const { done, value } = await reader.read();
				if (done) break;
				buffer += decoder.decode(value, { stream: true });
				const lines = buffer.split("\n");
				buffer = lines.pop() ?? "";
				for (const line of lines) if (line.startsWith("data: ")) try {
					const data = JSON.parse(line.slice(6));
					if (data.chunk) onMessage?.(data.chunk);
					if (data.done && data.response) onDone?.(data.response);
				} catch (e) {
					console.error("Failed to parse SSE data:", e);
				}
			}
		} catch (error) {
			console.error("Error in askDocQuestion:", error);
			throw error;
		}
	};
	const autocomplete = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/autocomplete`, authAPIOptions, otherOptions, {
		method: "POST",
		body
	});
	/**
	* Retrieves discussions with filters and pagination. Only user or admin can access.
	*/
	const getDiscussions = async (params, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/discussions`, authAPIOptions, otherOptions, {
		method: "GET",
		params
	});
	return {
		customQuery,
		translateJSON,
		auditContentDeclaration,
		auditContentDeclarationField,
		auditContentDeclarationMetadata,
		auditTag,
		askDocQuestion,
		autocomplete,
		getDiscussions
	};
};

//#endregion
exports.getAiAPI = getAiAPI;
//# sourceMappingURL=ai.cjs.map