import type { AgentMessage } from "@jaeswift/jae-agent-core";

export function exportSessionAsMarkdown(messages: AgentMessage[], title: string): void {
	const lines: string[] = [
		`# ${title || "JAE Session Export"}`,
		``,
		`*Exported: ${new Date().toLocaleString()}*`,
		``,
		`---`,
		``,
	];

	for (const msg of messages) {
		if (msg.role === "user") {
			const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
			lines.push(`## 👤 User`, ``, content, ``, `---`, ``);
		} else if (msg.role === "assistant") {
			const m = msg as any;
			const textBlocks = Array.isArray(m.content)
				? m.content
						.filter((b: any) => b.type === "text")
						.map((b: any) => b.text)
						.join("\n")
				: m.content || "";
			lines.push(`## 🤖 Assistant`, ``, textBlocks, ``, `---`, ``);
		}
	}

	const blob = new Blob([lines.join("\n")], { type: "text/markdown" });
	const url = URL.createObjectURL(blob);
	const a = document.createElement("a");
	a.href = url;
	a.download = `jae-session-${Date.now()}.md`;
	a.click();
	URL.revokeObjectURL(url);
}

export function exportSessionAsJson(messages: AgentMessage[], title: string): void {
	const data = { title, exportedAt: new Date().toISOString(), messages };
	const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
	const url = URL.createObjectURL(blob);
	const a = document.createElement("a");
	a.href = url;
	a.download = `jae-session-${Date.now()}.json`;
	a.click();
	URL.revokeObjectURL(url);
}
