use anyhow::{Context, Result};
use uuid::Uuid;
use crate::config::Config;
use crate::store::hierarchy::Hierarchy;
use crate::store::node::Node;
use crate::store::{InsertPosition, NodeKind, Store};
fn resolve_target<'a>(h: &'a Hierarchy, target: Option<Uuid>) -> Option<(Node, InsertPosition)> {
let target = target?;
let node = h.get(target)?;
match node.kind {
NodeKind::Book | NodeKind::Chapter | NodeKind::Subchapter => {
Some((node.clone(), InsertPosition::End))
}
NodeKind::Paragraph => {
let parent = node.parent_id.and_then(|p| h.get(p))?;
Some((parent.clone(), InsertPosition::After(target)))
}
_ => None,
}
}
pub(super) fn insert_paragraph(
store: &Store,
cfg: &Config,
h: &Hierarchy,
book_id: Uuid,
target: Option<Uuid>,
title: &str,
body: &str,
) -> Result<Uuid> {
let (parent, position) = resolve_target(h, target).or_else(|| {
h.get(book_id).map(|b| (b.clone(), InsertPosition::End))
}).context("no valid insertion parent (Facts book missing?)")?;
let title = if title.trim().is_empty() { "Untitled" } else { title.trim() };
let mut node = store
.create_node(cfg, h, NodeKind::Paragraph, title, Some(&parent), None, position)
.context("create paragraph node")?;
if let Some(rel) = &node.file {
let abs = store.project_root().join(rel);
crate::io_atomic::write(&abs, body.as_bytes()).context("write paragraph .typ body")?;
}
store
.update_paragraph_content(&mut node, body.as_bytes())
.context("write paragraph body (reembeds)")?;
Ok(node.id)
}