const require_utils_responseData = require('../utils/responseData.cjs');
const require_utils_errors_ErrorHandler = require('../utils/errors/ErrorHandler.cjs');
const require_services_dictionary_service = require('../services/dictionary.service.cjs');
const require_services_tag_service = require('../services/tag.service.cjs');
const require_utils_AI_aiSdk = require('../utils/AI/aiSdk.cjs');
const require_utils_AI_askDocQuestion_askDocQuestion = require('../utils/AI/askDocQuestion/askDocQuestion.cjs');
const require_utils_AI_auditDictionary_index = require('../utils/AI/auditDictionary/index.cjs');
const require_utils_AI_auditDictionaryField_index = require('../utils/AI/auditDictionaryField/index.cjs');
const require_utils_AI_auditDictionaryMetadata_index = require('../utils/AI/auditDictionaryMetadata/index.cjs');
const require_utils_AI_auditTag_index = require('../utils/AI/auditTag/index.cjs');
const require_utils_AI_autocomplete_index = require('../utils/AI/autocomplete/index.cjs');
const require_utils_AI_customQuery_index = require('../utils/AI/customQuery/index.cjs');
const require_utils_AI_translateJSON_index = require('../utils/AI/translateJSON/index.cjs');
const require_utils_filtersAndPagination_getDiscussionFiltersAndPagination = require('../utils/filtersAndPagination/getDiscussionFiltersAndPagination.cjs');
const require_models_discussion_model = require('../models/discussion.model.cjs');

//#region src/controllers/ai.controller.ts
const customQuery = async (req, res, _next) => {
	const { aiOptions, tagsKeys,...rest } = req.body;
	let aiConfig;
	try {
		aiConfig = await require_utils_AI_aiSdk.getAIConfig(res, {
			userOptions: aiOptions,
			defaultOptions: require_utils_AI_customQuery_index.aiDefaultOptions,
			accessType: ["registered_user", "apiKey"]
		});
	} catch (_error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AI_ACCESS_DENIED");
		return;
	}
	try {
		const auditResponse = await require_utils_AI_customQuery_index.customQuery({
			...rest,
			aiConfig,
			applicationContext: aiOptions?.applicationContext
		});
		if (!auditResponse) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "QUERY_FAILED");
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: auditResponse });
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
const translateJSON = async (req, res, _next) => {
	const { project } = res.locals;
	const { aiOptions, tagsKeys,...rest } = req.body;
	let aiConfig;
	try {
		aiConfig = await require_utils_AI_aiSdk.getAIConfig(res, {
			userOptions: aiOptions,
			defaultOptions: require_utils_AI_translateJSON_index.aiDefaultOptions,
			accessType: ["registered_user", "apiKey"]
		});
	} catch (_error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AI_ACCESS_DENIED");
		return;
	}
	try {
		let tags = [];
		if (project?.organizationId && tagsKeys) tags = await require_services_tag_service.getTagsByKeys(tagsKeys, project.organizationId);
		const auditResponse = await require_utils_AI_translateJSON_index.translateJSON({
			...rest,
			aiConfig,
			applicationContext: aiOptions?.applicationContext,
			tags
		});
		if (!auditResponse) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AUDIT_FAILED");
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: auditResponse });
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Retrieves a list of dictionaries based on filters and pagination.
*/
const auditContentDeclaration = async (req, res, _next) => {
	const { project } = res.locals;
	const { fileContent, filePath, aiOptions, locales, defaultLocale, tagsKeys } = req.body;
	let aiConfig;
	try {
		aiConfig = await require_utils_AI_aiSdk.getAIConfig(res, {
			userOptions: aiOptions,
			defaultOptions: require_utils_AI_auditDictionary_index.aiDefaultOptions,
			accessType: ["registered_user", "apiKey"]
		});
	} catch (_error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AI_ACCESS_DENIED");
		return;
	}
	try {
		let tags = [];
		if (project?.organizationId) tags = await require_services_tag_service.getTagsByKeys(tagsKeys, project.organizationId);
		const auditResponse = await require_utils_AI_auditDictionary_index.auditDictionary({
			fileContent,
			filePath,
			aiConfig,
			applicationContext: aiOptions?.applicationContext,
			locales,
			defaultLocale,
			tags
		});
		if (!auditResponse) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AUDIT_FAILED");
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: auditResponse });
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Retrieves a list of dictionaries based on filters and pagination.
*/
const auditContentDeclarationField = async (req, res, _next) => {
	const { project } = res.locals;
	const { fileContent, aiOptions, locales, tagsKeys, keyPath } = req.body;
	let aiConfig;
	try {
		aiConfig = await require_utils_AI_aiSdk.getAIConfig(res, {
			userOptions: aiOptions,
			defaultOptions: require_utils_AI_auditDictionaryField_index.aiDefaultOptions,
			accessType: ["registered_user", "apiKey"]
		});
	} catch (_error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AI_ACCESS_DENIED");
		return;
	}
	try {
		let tags = [];
		if (project?.organizationId) tags = await require_services_tag_service.getTagsByKeys(tagsKeys, project.organizationId);
		const auditResponse = await require_utils_AI_auditDictionaryField_index.auditDictionaryField({
			fileContent,
			aiConfig,
			applicationContext: aiOptions?.applicationContext,
			locales,
			tags,
			keyPath
		});
		if (!auditResponse) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AUDIT_FAILED");
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: auditResponse });
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Retrieves a list of dictionaries based on filters and pagination.
*/
const auditContentDeclarationMetadata = async (req, res, _next) => {
	const { organization } = res.locals;
	const { fileContent, aiOptions } = req.body;
	let aiConfig;
	try {
		aiConfig = await require_utils_AI_aiSdk.getAIConfig(res, {
			userOptions: aiOptions,
			defaultOptions: require_utils_AI_auditDictionaryMetadata_index.aiDefaultOptions,
			accessType: ["registered_user", "apiKey"]
		});
	} catch (_error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AI_ACCESS_DENIED");
		return;
	}
	try {
		const tags = await require_services_tag_service.findTags({ organizationId: organization?.id }, 0, 1e3);
		const auditResponse = await require_utils_AI_auditDictionaryMetadata_index.auditDictionaryMetadata({
			fileContent,
			aiConfig,
			applicationContext: aiOptions?.applicationContext,
			tags
		});
		if (!auditResponse) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AUDIT_FAILED");
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: auditResponse });
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Retrieves a list of dictionaries based on filters and pagination.
*/
const auditTag = async (req, res, _next) => {
	const { project } = res.locals;
	const { aiOptions, tag } = req.body;
	let aiConfig;
	try {
		aiConfig = await require_utils_AI_aiSdk.getAIConfig(res, {
			userOptions: aiOptions,
			defaultOptions: require_utils_AI_auditTag_index.aiDefaultOptions,
			accessType: ["registered_user", "apiKey"]
		});
	} catch (_error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AI_ACCESS_DENIED");
		return;
	}
	try {
		let dictionaries = [];
		if (project?.organizationId) dictionaries = await require_services_dictionary_service.getDictionariesByTags([tag.key], project.id);
		const auditResponse = await require_utils_AI_auditTag_index.auditTag({
			aiConfig,
			dictionaries,
			tag,
			applicationContext: aiOptions?.applicationContext
		});
		if (!auditResponse) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AUDIT_FAILED");
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: auditResponse });
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
const askDocQuestion = async (req, res, _next) => {
	const { messages = [], discussionId } = req.body;
	const { user, project, organization } = res.locals;
	let aiConfig;
	try {
		aiConfig = await require_utils_AI_aiSdk.getAIConfig(res, {
			userOptions: {},
			defaultOptions: require_utils_AI_askDocQuestion_askDocQuestion.aiDefaultOptions,
			accessType: ["public"]
		});
	} catch (_error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AI_ACCESS_DENIED");
		return;
	}
	res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
	res.setHeader("Cache-Control", "no-cache, no-transform");
	res.setHeader("Connection", "keep-alive");
	res.setHeader("X-Accel-Buffering", "no");
	res.flushHeaders?.();
	res.write(": connected\n\n");
	res.flush?.();
	require_utils_AI_askDocQuestion_askDocQuestion.askDocQuestion(messages, aiConfig, { onMessage: (chunk) => {
		res.write(`data: ${JSON.stringify({ chunk })}\n\n`);
		res.flush?.();
	} }).then(async (fullResponse) => {
		const lastUserMessageContent = messages.findLast((message) => message.role === "user")?.content;
		if ((lastUserMessageContent ? lastUserMessageContent.split(" ").length : 0) > 2) await require_models_discussion_model.DiscussionModel.findOneAndUpdate({ discussionId }, { $set: {
			discussionId,
			userId: user?.id,
			projectId: project?.id,
			organizationId: organization?.id,
			messages: [...messages.map((msg) => ({
				role: msg.role,
				content: msg.content,
				timestamp: msg.timestamp
			})), {
				role: "assistant",
				content: fullResponse.response,
				relatedFiles: fullResponse.relatedFiles,
				timestamp: /* @__PURE__ */ new Date()
			}]
		} }, {
			upsert: true,
			new: true
		});
		res.write(`data: ${JSON.stringify({
			done: true,
			response: fullResponse
		})}\n\n`);
		res.end();
	}).catch((err) => {
		res.write(`event: error\ndata: ${JSON.stringify({ message: err.message })}\n\n`);
		res.end();
	});
};
const autocomplete = async (req, res, _next) => {
	try {
		const { text, aiOptions, contextBefore, currentLine, contextAfter } = req.body;
		let aiConfig;
		try {
			aiConfig = await require_utils_AI_aiSdk.getAIConfig(res, {
				userOptions: aiOptions,
				defaultOptions: require_utils_AI_autocomplete_index.aiDefaultOptions,
				accessType: ["public"]
			});
		} catch (_error) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "AI_ACCESS_DENIED");
			return;
		}
		const responseData = require_utils_responseData.formatResponse({ data: await require_utils_AI_autocomplete_index.autocomplete({
			text,
			aiConfig,
			applicationContext: aiOptions?.applicationContext,
			contextBefore,
			currentLine,
			contextAfter
		}) ?? {
			autocompletion: "",
			tokenUsed: 0
		} });
		res.json(responseData);
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};
/**
* Retrieves a list of discussions with filters and pagination.
* Only the owner or admins can access. By default, users only see their own.
*/
const getDiscussions = async (req, res, _next) => {
	const { user, roles } = res.locals;
	const { filters, sortOptions, pageSize, skip, page, getNumberOfPages } = require_utils_filtersAndPagination_getDiscussionFiltersAndPagination.getDiscussionFiltersAndPagination(req, res);
	const includeMessages = req.query?.includeMessages !== "false";
	if (!user) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "USER_NOT_DEFINED");
		return;
	}
	try {
		const projection = includeMessages ? {} : { messages: 0 };
		const discussions = await require_models_discussion_model.DiscussionModel.find(filters, projection).sort(sortOptions).skip(skip).limit(pageSize).lean();
		const numberOfMessagesById = {};
		if (!includeMessages && discussions.length > 0) {
			const ids = discussions.map((d) => d._id);
			const counts = await require_models_discussion_model.DiscussionModel.aggregate([{ $match: { _id: { $in: ids } } }, { $project: { numberOfMessages: { $size: { $ifNull: ["$messages", []] } } } }]);
			for (const c of counts) numberOfMessagesById[String(c._id)] = c.numberOfMessages ?? 0;
		}
		const allOwnedByUser = discussions.every((d) => String(d.userId) === String(user.id));
		if (!(roles.includes("admin") || allOwnedByUser)) {
			require_utils_errors_ErrorHandler.ErrorHandler.handleGenericErrorResponse(res, "PERMISSION_DENIED");
			return;
		}
		const totalItems = await require_models_discussion_model.DiscussionModel.countDocuments(filters);
		const responseData = require_utils_responseData.formatPaginatedResponse({
			data: discussions.map((d) => ({
				...d,
				id: String(d._id ?? d.id),
				numberOfMessages: includeMessages ? Array.isArray(d.messages) ? d.messages.length : 0 : numberOfMessagesById[String(d._id ?? d.id)] ?? 0
			})),
			page,
			pageSize,
			totalPages: getNumberOfPages(totalItems),
			totalItems
		});
		res.json(responseData);
		return;
	} catch (error) {
		require_utils_errors_ErrorHandler.ErrorHandler.handleAppErrorResponse(res, error);
		return;
	}
};

//#endregion
exports.askDocQuestion = askDocQuestion;
exports.auditContentDeclaration = auditContentDeclaration;
exports.auditContentDeclarationField = auditContentDeclarationField;
exports.auditContentDeclarationMetadata = auditContentDeclarationMetadata;
exports.auditTag = auditTag;
exports.autocomplete = autocomplete;
exports.customQuery = customQuery;
exports.getDiscussions = getDiscussions;
exports.translateJSON = translateJSON;
//# sourceMappingURL=ai.controller.cjs.map