//! `log.md` — append-only chronological record (plan §4). Entries use a
//! grep-able prefix: `## [YYYY-MM-DD] kind | Title`.

use crate::util;
use anyhow::Result;
use std::path::Path;

pub fn path(wiki_dir: &Path) -> std::path::PathBuf {
    wiki_dir.join("log.md")
}

/// Append a dated entry. Creates the file with a header if missing.
pub fn append(wiki_dir: &Path, kind: &str, title: &str, details: &str) -> Result<()> {
    let p = path(wiki_dir);
    let mut content = if p.exists() {
        util::read_text(&p)?
    } else {
        "# Log\n\nAppend-only record of ingests, queries, and lint passes.\n".to_string()
    };
    if !content.ends_with('\n') {
        content.push('\n');
    }
    content.push_str(&format!("\n## [{}] {} | {}\n", util::today(), kind, title));
    if !details.trim().is_empty() {
        content.push('\n');
        content.push_str(details.trim());
        content.push('\n');
    }
    util::write_text(&p, &content)
}

/// The last `n` entry headers (without bodies), oldest→newest.
pub fn tail(wiki_dir: &Path, n: usize) -> Vec<String> {
    let p = path(wiki_dir);
    let content = match std::fs::read_to_string(&p) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };
    let mut entries: Vec<String> = content
        .lines()
        .filter(|l| l.starts_with("## ["))
        .map(|l| l.trim_start_matches("## ").to_string())
        .collect();
    if entries.len() > n {
        entries = entries.split_off(entries.len() - n);
    }
    entries
}
