import { getLogger } from "../../../../logger.js";
import { UnsupportedTextAttachmentSourceError } from "./file-security-errors.js";
import { buildDecodedTextAttachmentBlock, buildUnavailableTextAttachmentBlock } from "../../utils/text-document-attachments.js";
import { fromBlobUri, getBlobStorageProvider, isBlobUri } from "./index.js";
import { normalizeInlineFileBytes } from "./file-content-security.js";
import { normalizeMimeType } from "@inkeep/agents-core/constants/allowed-file-formats";

//#region src/domains/run/services/blob-storage/text-attachment-resolver.ts
const logger = getLogger("text-attachment-resolver");
/**
* Resolve a text-document `FilePart` into its `<attached_file>...</attached_file>`
* block — decoded content on success, `[Attachment unavailable]` fallback on any
* download/decode failure. Accepts both inline-bytes parts (first-turn input) and
* blob-URI parts (post-upload history rebuild).
*/
async function resolveTextAttachmentBlock(part, options = {}) {
	const file = part.file;
	const mimeType = normalizeMimeType(file.mimeType ?? "");
	const filename = typeof part.metadata?.filename === "string" ? part.metadata.filename : void 0;
	const fallback = () => buildUnavailableTextAttachmentBlock({
		mimeType,
		filename
	});
	let bytes;
	if ("bytes" in file && file.bytes) try {
		bytes = (await normalizeInlineFileBytes(file)).data;
	} catch (err) {
		logger.warn({
			err,
			mimeType,
			failureKind: "normalize"
		}, "Failed to normalize inline bytes for text attachment");
		return fallback();
	}
	else if ("uri" in file && file.uri && isBlobUri(file.uri)) {
		let downloaded;
		try {
			downloaded = await getBlobStorageProvider().download(fromBlobUri(file.uri));
		} catch (err) {
			logger.warn({
				err,
				uri: file.uri,
				mimeType,
				failureKind: "download"
			}, "Failed to download text attachment from blob storage");
			return fallback();
		}
		bytes = downloaded.data;
	} else {
		if (options.throwIfUnresolvable) throw new UnsupportedTextAttachmentSourceError(mimeType);
		return fallback();
	}
	try {
		return buildDecodedTextAttachmentBlock({
			data: bytes,
			mimeType,
			filename
		});
	} catch (err) {
		logger.warn({
			err,
			mimeType,
			failureKind: "decode"
		}, "Failed to decode text attachment");
		return fallback();
	}
}

//#endregion
export { resolveTextAttachmentBlock };