//! Memo and bundle export helpers.

use serde_json::json;

use crate::research::projections::build_memo_blocks;
use crate::research::types::{
    AuditEvent, GhostNote, NoteLink, ResearchBundleExport, ResearchNote, ResearchWorkspace,
    SourceRecord,
};

pub(crate) fn export_bundle(
    workspace: ResearchWorkspace,
    notes: Vec<ResearchNote>,
    links: Vec<NoteLink>,
    ghosts: Vec<GhostNote>,
    sources: Vec<SourceRecord>,
    audit_events: Vec<AuditEvent>,
) -> ResearchBundleExport {
    let memo_blocks = build_memo_blocks(&notes, &ghosts);
    let markdown_memo = memo_blocks
        .iter()
        .map(|block| {
            format!(
                "## {}\n\n{}\n\nSources: {}\n",
                block.headline,
                block.body,
                block.citation_refs.join(", ")
            )
        })
        .collect::<Vec<_>>()
        .join("\n");

    let json_bundle = json!({
        "workspace": workspace,
        "notes": notes,
        "links": links,
        "ghosts": ghosts,
        "sources": sources,
        "auditEvents": audit_events,
        "memoBlocks": memo_blocks,
    });

    ResearchBundleExport {
        workspace: workspace.clone(),
        notes: notes.clone(),
        links: links.clone(),
        ghosts: ghosts.clone(),
        sources: sources.clone(),
        audit_events: audit_events.clone(),
        markdown_memo,
        json_bundle,
    }
}
