import { InvalidUtf8TextDocumentError, TextDocumentControlCharacterError } from "../services/blob-storage/file-security-errors.js";
import { ALLOWED_TEXT_DOCUMENT_MIME_TYPES, normalizeMimeType } from "@inkeep/agents-core/constants/allowed-file-formats";

//#region src/domains/run/utils/text-document-attachments.ts
function isDisallowedTextControlCharacter(codePoint) {
	return codePoint >= 0 && codePoint <= 8 || codePoint === 11 || codePoint === 12 || codePoint >= 14 && codePoint <= 31 || codePoint === 127;
}
function hasDisallowedControlCharacters(value) {
	for (const char of value) {
		const codePoint = char.codePointAt(0);
		if (codePoint === void 0 || isDisallowedTextControlCharacter(codePoint)) return true;
	}
	return false;
}
function isTextDocumentMimeType(mimeType) {
	return ALLOWED_TEXT_DOCUMENT_MIME_TYPES.has(normalizeMimeType(mimeType ?? ""));
}
function getDefaultTextDocumentFilename(mimeType) {
	switch (normalizeMimeType(mimeType)) {
		case "text/markdown": return "unnamed.md";
		case "text/html": return "unnamed.html";
		case "text/csv": return "unnamed.csv";
		case "text/x-log": return "unnamed.log";
		case "application/json": return "unnamed.json";
		default: return "unnamed.txt";
	}
}
function decodeTextDocumentBytes(data) {
	let decoded;
	try {
		decoded = new TextDecoder("utf-8", { fatal: true }).decode(data);
	} catch {
		throw new InvalidUtf8TextDocumentError();
	}
	if (hasDisallowedControlCharacters(decoded)) throw new TextDocumentControlCharacterError();
	return decoded.replace(/\r\n?/g, "\n");
}
function buildTextAttachmentBlock(params) {
	const mimeType = normalizeMimeType(params.mimeType);
	const filename = params.filename?.trim() || getDefaultTextDocumentFilename(mimeType);
	return [
		`<attached_file filename=${JSON.stringify(filename)} media_type=${JSON.stringify(mimeType)}>`,
		params.content,
		"</attached_file>"
	].join("\n");
}

//#endregion
export { buildTextAttachmentBlock, decodeTextDocumentBytes, getDefaultTextDocumentFilename, isTextDocumentMimeType };