use std::path::{Path, PathBuf};
use tera::{Context, Tera};
use tracing::debug;
use crate::report::errors::Result;
use crate::report::models::ReportData;
use crate::report::templates::MARKDOWN_REPORT;
pub const REPORT_MD: &str = "report.md";
const TOP_AUTHOR_LIMIT: usize = 10;
pub fn write_markdown(data: &ReportData, output_dir: &Path) -> Result<PathBuf> {
let mut ctx = Context::new();
ctx.insert("generated_at", &data.generated_at);
ctx.insert("period_start", &data.period_start);
ctx.insert("period_end", &data.period_end);
ctx.insert("total_commits", &data.total_commits);
ctx.insert("total_authors", &data.total_authors);
let top_authors: Vec<_> = data.authors.iter().take(TOP_AUTHOR_LIMIT).collect();
ctx.insert("top_authors", &top_authors);
ctx.insert("repositories", &data.repositories);
let mut cats: Vec<(String, usize)> = data
.category_breakdown
.iter()
.map(|(k, v)| (k.clone(), *v))
.collect();
cats.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
ctx.insert("category_breakdown", &cats);
let rendered = Tera::one_off(MARKDOWN_REPORT, &ctx, true)?;
let path = output_dir.join(REPORT_MD);
std::fs::write(&path, rendered)?;
debug!(path = %path.display(), "wrote report.md");
Ok(path)
}