export interface ImageContent {
	type: "image";
	data: string;
	mimeType: string;
}

export const MAX_CHAT_IMAGES = 8;
export const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
export const ALLOWED_IMAGE_MIME = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);

export function imageToDataUrl(image: ImageContent): string {
	return `data:${image.mimeType};base64,${image.data}`;
}

export async function fileToImageContent(file: File): Promise<ImageContent> {
	if (!ALLOWED_IMAGE_MIME.has(file.type)) {
		throw new Error(`不支持的图片类型: ${file.type || "unknown"}`);
	}
	if (file.size > MAX_IMAGE_BYTES) {
		throw new Error(`图片过大（最大 ${Math.round(MAX_IMAGE_BYTES / 1024 / 1024)}MB）`);
	}

	const dataUrl = await new Promise<string>((resolve, reject) => {
		const reader = new FileReader();
		reader.onload = () => resolve(String(reader.result));
		reader.onerror = () => reject(new Error("读取图片失败"));
		reader.readAsDataURL(file);
	});

	const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);
	if (!match) throw new Error("无效图片数据");
	return { type: "image", mimeType: match[1], data: match[2] };
}

export async function clipboardItemsToImages(items: DataTransferItemList): Promise<ImageContent[]> {
	const images: ImageContent[] = [];
	for (const item of items) {
		if (!item.type.startsWith("image/")) continue;
		const file = item.getAsFile();
		if (!file) continue;
		images.push(await fileToImageContent(file));
	}
	return images;
}

export function validateImagePayload(image: ImageContent): ImageContent {
	if (image.type !== "image") throw new Error("无效图片对象");
	if (!ALLOWED_IMAGE_MIME.has(image.mimeType)) {
		throw new Error(`不支持的图片类型: ${image.mimeType}`);
	}
	if (!image.data) throw new Error("图片数据为空");
	const padding = image.data.endsWith("==") ? 2 : image.data.endsWith("=") ? 1 : 0;
	const size = Math.floor((image.data.length * 3) / 4) - padding;
	if (size > MAX_IMAGE_BYTES) {
		throw new Error(`图片过大（最大 ${Math.round(MAX_IMAGE_BYTES / 1024 / 1024)}MB）`);
	}
	return { type: "image", mimeType: image.mimeType, data: image.data };
}
