Skip to main content

weave_content/
lib.rs

1#![deny(unsafe_code)]
2#![deny(clippy::unwrap_used)]
3#![deny(clippy::expect_used)]
4#![allow(clippy::missing_errors_doc)]
5#![allow(clippy::implicit_hasher)]
6#![allow(clippy::struct_field_names)]
7
8pub mod build_cache;
9pub mod cache;
10pub mod domain;
11pub mod entity;
12pub mod html;
13pub mod nulid_gen;
14pub mod output;
15pub mod parser;
16pub mod registry;
17pub mod relationship;
18pub mod tags;
19pub mod timeline;
20pub mod verifier;
21pub mod writeback;
22
23use std::collections::{BTreeMap, HashMap, HashSet};
24
25use crate::entity::Entity;
26use crate::output::{CaseOutput, NodeOutput};
27use crate::parser::{ParseError, ParsedCase, SectionKind};
28use crate::relationship::Rel;
29
30/// Build a case index: scan case files for front matter `id:` and H1 title.
31///
32/// Returns a map of `case_path → (nulid, title)` used to resolve cross-case
33/// references in `## Related Cases` sections.
34pub fn build_case_index(
35    case_files: &[String],
36    content_root: &std::path::Path,
37) -> Result<std::collections::HashMap<String, (String, String)>, i32> {
38    let mut map = std::collections::HashMap::new();
39    for path in case_files {
40        let content = std::fs::read_to_string(path).map_err(|e| {
41            eprintln!("{path}: {e}");
42            1
43        })?;
44        if let Some(case_path) = case_slug_from_path(std::path::Path::new(path), content_root) {
45            let id = extract_front_matter_id(&content).unwrap_or_else(|| {
46                nulid::Nulid::new()
47                    .map(|n| n.to_string())
48                    .unwrap_or_default()
49            });
50            let title = extract_title(&content).unwrap_or_else(|| case_path.clone());
51            map.insert(case_path, (id, title));
52        }
53    }
54    Ok(map)
55}
56
57/// Extract the `id:` value from YAML front matter without full parsing.
58fn extract_front_matter_id(content: &str) -> Option<String> {
59    let content = content.strip_prefix("---\n")?;
60    let end = content.find("\n---")?;
61    let fm = &content[..end];
62    for line in fm.lines() {
63        let trimmed = line.trim();
64        if let Some(id) = trimmed.strip_prefix("id:") {
65            let id = id.trim().trim_matches('"').trim_matches('\'');
66            if !id.is_empty() {
67                return Some(id.to_string());
68            }
69        }
70    }
71    None
72}
73
74/// Extract the first H1 heading (`# Title`) after the front matter closing delimiter.
75fn extract_title(content: &str) -> Option<String> {
76    let content = content.strip_prefix("---\n")?;
77    let end = content.find("\n---")?;
78    let after_fm = &content[end + 4..];
79    for line in after_fm.lines() {
80        if let Some(title) = line.strip_prefix("# ") {
81            let title = title.trim();
82            if !title.is_empty() {
83                return Some(title.to_string());
84            }
85        }
86    }
87    None
88}
89
90/// Derive a case slug from a file path relative to content root.
91///
92/// E.g. `content/cases/id/corruption/2002/foo.md` with content root
93/// `content/` → `id/corruption/2002/foo`.
94pub fn case_slug_from_path(
95    path: &std::path::Path,
96    content_root: &std::path::Path,
97) -> Option<String> {
98    let cases_dir = content_root.join("cases");
99    let rel = path.strip_prefix(&cases_dir).ok()?;
100    let s = rel.to_str()?;
101    Some(s.strip_suffix(".md").unwrap_or(s).to_string())
102}
103
104/// Parse a case file fully: front matter, entities, relationships, timeline.
105/// Returns the parsed case, inline entities, and relationships (including NEXT from timeline).
106///
107/// When a registry is provided, relationship and timeline names are resolved
108/// against both inline events AND the global entity registry.
109pub fn parse_full(
110    content: &str,
111    reg: Option<&registry::EntityRegistry>,
112) -> Result<(ParsedCase, Vec<Entity>, Vec<Rel>), Vec<ParseError>> {
113    let case = parser::parse(content)?;
114    let mut errors = Vec::new();
115
116    let mut all_entities = Vec::new();
117    for section in &case.sections {
118        if matches!(
119            section.kind,
120            SectionKind::Events | SectionKind::Documents | SectionKind::Assets
121        ) {
122            let entities =
123                entity::parse_entities(&section.body, section.kind, section.line, &mut errors);
124            all_entities.extend(entities);
125        }
126    }
127
128    // Build combined name set: inline events + registry entities
129    let mut entity_names: HashSet<&str> = all_entities.iter().map(|e| e.name.as_str()).collect();
130    if let Some(registry) = reg {
131        for name in registry.names() {
132            entity_names.insert(name);
133        }
134    }
135
136    let event_names: HashSet<&str> = all_entities
137        .iter()
138        .filter(|e| e.label == entity::Label::Event)
139        .map(|e| e.name.as_str())
140        .collect();
141
142    let mut all_rels = Vec::new();
143    for section in &case.sections {
144        if section.kind == SectionKind::Relationships {
145            let rels = relationship::parse_relationships(
146                &section.body,
147                section.line,
148                &entity_names,
149                &case.sources,
150                &mut errors,
151            );
152            all_rels.extend(rels);
153        }
154    }
155
156    for section in &case.sections {
157        if section.kind == SectionKind::Timeline {
158            let rels =
159                timeline::parse_timeline(&section.body, section.line, &event_names, &mut errors);
160            all_rels.extend(rels);
161        }
162    }
163
164    if errors.is_empty() {
165        Ok((case, all_entities, all_rels))
166    } else {
167        Err(errors)
168    }
169}
170
171/// Collect registry entities referenced by relationships in this case.
172/// Sets the `slug` field on each entity from the registry's file path.
173pub fn collect_referenced_registry_entities(
174    rels: &[Rel],
175    inline_entities: &[Entity],
176    reg: &registry::EntityRegistry,
177) -> Vec<Entity> {
178    let inline_names: HashSet<&str> = inline_entities.iter().map(|e| e.name.as_str()).collect();
179    let mut referenced = Vec::new();
180    let mut seen_names: HashSet<String> = HashSet::new();
181
182    for rel in rels {
183        for name in [&rel.source_name, &rel.target_name] {
184            if !inline_names.contains(name.as_str())
185                && seen_names.insert(name.clone())
186                && let Some(entry) = reg.get_by_name(name)
187            {
188                let mut entity = entry.entity.clone();
189                entity.slug = reg.slug_for(entry);
190                referenced.push(entity);
191            }
192        }
193    }
194
195    referenced
196}
197
198/// Build a `CaseOutput` from a case file path.
199/// Handles parsing and ID writeback.
200pub fn build_case_output(
201    path: &str,
202    reg: &registry::EntityRegistry,
203) -> Result<output::CaseOutput, i32> {
204    let mut written = HashSet::new();
205    build_case_output_tracked(path, reg, &mut written, &std::collections::HashMap::new())
206}
207
208/// Build a `CaseOutput` from a case file path, tracking which entity files
209/// have already been written back. This avoids re-reading entity files from
210/// disk when multiple cases reference the same shared entity.
211pub fn build_case_output_tracked(
212    path: &str,
213    reg: &registry::EntityRegistry,
214    written_entities: &mut HashSet<std::path::PathBuf>,
215    case_nulid_map: &std::collections::HashMap<String, (String, String)>,
216) -> Result<output::CaseOutput, i32> {
217    let content = match std::fs::read_to_string(path) {
218        Ok(c) => c,
219        Err(e) => {
220            eprintln!("{path}: error reading file: {e}");
221            return Err(2);
222        }
223    };
224
225    let (case, entities, rels) = match parse_full(&content, Some(reg)) {
226        Ok(result) => result,
227        Err(errors) => {
228            for err in &errors {
229                eprintln!("{path}:{err}");
230            }
231            return Err(1);
232        }
233    };
234
235    let referenced_entities = collect_referenced_registry_entities(&rels, &entities, reg);
236
237    // Resolve case NULID
238    let (case_nulid, case_nulid_generated) = match nulid_gen::resolve_id(case.id.as_deref(), 1) {
239        Ok(result) => result,
240        Err(err) => {
241            eprintln!("{path}:{err}");
242            return Err(1);
243        }
244    };
245    let case_nulid_str = case_nulid.to_string();
246
247    // Compute case slug from file path
248    let case_slug = reg
249        .content_root()
250        .and_then(|root| registry::path_to_slug(std::path::Path::new(path), root));
251
252    // Derive case_id from slug (filename-based) or fall back to empty string
253    let case_id = case_slug
254        .as_deref()
255        .and_then(|s| s.rsplit('/').next())
256        .unwrap_or_default();
257
258    let build_result = match output::build_output(
259        case_id,
260        &case_nulid_str,
261        &case.title,
262        &case.summary,
263        &case.tags,
264        case_slug.as_deref(),
265        case.case_type.as_deref(),
266        case.status.as_deref(),
267        case.amounts.as_deref(),
268        &case.sources,
269        &case.related_cases,
270        case_nulid_map,
271        &entities,
272        &rels,
273        &referenced_entities,
274        &case.involved,
275    ) {
276        Ok(out) => out,
277        Err(errors) => {
278            for err in &errors {
279                eprintln!("{path}:{err}");
280            }
281            return Err(1);
282        }
283    };
284
285    let case_output = build_result.output;
286
287    // Write back generated IDs to source case file
288    let mut case_pending = build_result.case_pending;
289    if case_nulid_generated {
290        case_pending.push(writeback::PendingId {
291            line: writeback::find_front_matter_end(&content).unwrap_or(2),
292            id: case_nulid_str.clone(),
293            kind: writeback::WriteBackKind::CaseId,
294        });
295    }
296    if !case_pending.is_empty()
297        && let Some(modified) = writeback::apply_writebacks(&content, &mut case_pending)
298    {
299        if let Err(e) = writeback::write_file(std::path::Path::new(path), &modified) {
300            eprintln!("{e}");
301            return Err(2);
302        }
303        let count = case_pending.len();
304        eprintln!("{path}: wrote {count} generated ID(s) back to file");
305    }
306
307    // Write back generated IDs to entity files
308    if let Some(code) =
309        writeback_registry_entities(&build_result.registry_pending, reg, written_entities)
310    {
311        return Err(code);
312    }
313
314    eprintln!(
315        "{path}: built ({} nodes, {} relationships)",
316        case_output.nodes.len(),
317        case_output.relationships.len()
318    );
319    Ok(case_output)
320}
321
322/// Write back generated IDs to registry entity files.
323/// Tracks already-written paths in `written` to avoid redundant disk reads.
324/// Returns `Some(exit_code)` on error, `None` on success.
325fn writeback_registry_entities(
326    pending: &[(String, writeback::PendingId)],
327    reg: &registry::EntityRegistry,
328    written: &mut HashSet<std::path::PathBuf>,
329) -> Option<i32> {
330    for (entity_name, pending_id) in pending {
331        let Some(entry) = reg.get_by_name(entity_name) else {
332            continue;
333        };
334        let entity_path = &entry.path;
335
336        // Skip if this entity file was already written by a previous case.
337        if !written.insert(entity_path.clone()) {
338            continue;
339        }
340
341        // Also skip if the entity already has an ID in the registry
342        // (loaded from file at startup).
343        if entry.entity.id.is_some() {
344            continue;
345        }
346
347        let entity_content = match std::fs::read_to_string(entity_path) {
348            Ok(c) => c,
349            Err(e) => {
350                eprintln!("{}: error reading file: {e}", entity_path.display());
351                return Some(2);
352            }
353        };
354
355        let fm_end = writeback::find_front_matter_end(&entity_content);
356        let mut ids = vec![writeback::PendingId {
357            line: fm_end.unwrap_or(2),
358            id: pending_id.id.clone(),
359            kind: writeback::WriteBackKind::EntityFrontMatter,
360        }];
361        if let Some(modified) = writeback::apply_writebacks(&entity_content, &mut ids) {
362            if let Err(e) = writeback::write_file(entity_path, &modified) {
363                eprintln!("{e}");
364                return Some(2);
365            }
366            eprintln!("{}: wrote generated ID back to file", entity_path.display());
367        }
368    }
369    None
370}
371
372/// Check whether a file's YAML front matter already contains an `id:` field.
373#[cfg(test)]
374fn front_matter_has_id(content: &str) -> bool {
375    let mut in_front_matter = false;
376    for line in content.lines() {
377        let trimmed = line.trim();
378        if trimmed == "---" && !in_front_matter {
379            in_front_matter = true;
380        } else if trimmed == "---" && in_front_matter {
381            return false; // end of front matter, no id found
382        } else if in_front_matter && trimmed.starts_with("id:") {
383            return true;
384        }
385    }
386    false
387}
388
389/// Resolve the content root directory.
390///
391/// Priority: explicit `--root` flag > parent of given path > current directory.
392pub fn resolve_content_root(path: Option<&str>, root: Option<&str>) -> std::path::PathBuf {
393    if let Some(r) = root {
394        return std::path::PathBuf::from(r);
395    }
396    if let Some(p) = path {
397        let p = std::path::Path::new(p);
398        if p.is_file() {
399            if let Some(parent) = p.parent() {
400                for ancestor in parent.ancestors() {
401                    if ancestor.join("cases").is_dir()
402                        || ancestor.join("people").is_dir()
403                        || ancestor.join("organizations").is_dir()
404                    {
405                        return ancestor.to_path_buf();
406                    }
407                }
408                return parent.to_path_buf();
409            }
410        } else if p.is_dir() {
411            return p.to_path_buf();
412        }
413    }
414    std::path::PathBuf::from(".")
415}
416
417/// Load entity registry from content root. Returns empty registry if no entity dirs exist.
418pub fn load_registry(content_root: &std::path::Path) -> Result<registry::EntityRegistry, i32> {
419    match registry::EntityRegistry::load(content_root) {
420        Ok(reg) => Ok(reg),
421        Err(errors) => {
422            for err in &errors {
423                eprintln!("registry: {err}");
424            }
425            Err(1)
426        }
427    }
428}
429
430/// Load tag registry from content root. Returns empty registry if no tags.yaml exists.
431pub fn load_tag_registry(content_root: &std::path::Path) -> Result<tags::TagRegistry, i32> {
432    match tags::TagRegistry::load(content_root) {
433        Ok(reg) => Ok(reg),
434        Err(errors) => {
435            for err in &errors {
436                eprintln!("tags: {err}");
437            }
438            Err(1)
439        }
440    }
441}
442
443/// Resolve case file paths from path argument.
444/// If path is a file, returns just that file.
445/// If path is a directory (or None), auto-discovers `cases/**/*.md`.
446pub fn resolve_case_files(
447    path: Option<&str>,
448    content_root: &std::path::Path,
449) -> Result<Vec<String>, i32> {
450    if let Some(p) = path {
451        let p_path = std::path::Path::new(p);
452        if p_path.is_file() {
453            return Ok(vec![p.to_string()]);
454        }
455        if !p_path.is_dir() {
456            eprintln!("{p}: not a file or directory");
457            return Err(2);
458        }
459    }
460
461    let cases_dir = content_root.join("cases");
462    if !cases_dir.is_dir() {
463        return Ok(Vec::new());
464    }
465
466    let mut files = Vec::new();
467    discover_md_files(&cases_dir, &mut files, 0);
468    files.sort();
469    Ok(files)
470}
471
472/// Recursively discover .md files in a directory (max 5 levels deep for cases/country/category/year/).
473fn discover_md_files(dir: &std::path::Path, files: &mut Vec<String>, depth: usize) {
474    const MAX_DEPTH: usize = 5;
475    if depth > MAX_DEPTH {
476        return;
477    }
478
479    let Ok(entries) = std::fs::read_dir(dir) else {
480        return;
481    };
482
483    let mut entries: Vec<_> = entries.filter_map(Result::ok).collect();
484    entries.sort_by_key(std::fs::DirEntry::file_name);
485
486    for entry in entries {
487        let path = entry.path();
488        if path.is_dir() {
489            discover_md_files(&path, files, depth + 1);
490        } else if path.extension().and_then(|e| e.to_str()) == Some("md")
491            && let Some(s) = path.to_str()
492        {
493            files.push(s.to_string());
494        }
495    }
496}
497
498/// Extract 2-letter country code from a case slug like `cases/id/corruption/2024/...`.
499/// Returns `Some("id")` for `cases/id/...`, `None` if the slug doesn't match.
500fn extract_country_code(slug: &str) -> Option<String> {
501    let parts: Vec<&str> = slug.split('/').collect();
502    // slug format: "cases/{country}/..." — country is at index 1
503    if parts.len() >= 2 {
504        let candidate = parts[1];
505        if candidate.len() == 2 && candidate.chars().all(|c| c.is_ascii_lowercase()) {
506            return Some(candidate.to_string());
507        }
508    }
509    None
510}
511
512/// Generate static HTML files, sitemap, tag pages, and NULID index from built case outputs.
513///
514/// Writes output to `{output_dir}/html/`. Returns `0` on success, non-zero on error.
515///
516/// This is the high-level orchestrator that calls individual `html::render_*` functions
517/// and writes the results to disk.
518pub fn generate_html_output(
519    output_dir: &str,
520    cases: &[CaseOutput],
521    base_url: &str,
522    thumbnail_base_url: Option<&str>,
523) -> i32 {
524    let html_dir = format!("{output_dir}/html");
525    let config = html::HtmlConfig {
526        thumbnail_base_url: thumbnail_base_url.map(String::from),
527    };
528
529    let mut nulid_index: BTreeMap<String, String> = BTreeMap::new();
530
531    let (all_people, all_orgs, person_cases, org_cases) =
532        match generate_case_pages(&html_dir, cases, &config, &mut nulid_index) {
533            Ok(collections) => collections,
534            Err(code) => return code,
535        };
536
537    if let Err(code) = generate_entity_pages(
538        &html_dir,
539        &all_people,
540        &person_cases,
541        &config,
542        &mut nulid_index,
543        "person",
544        |node, case_list, cfg| html::render_person(node, case_list, cfg),
545    ) {
546        return code;
547    }
548    eprintln!("html: {} person pages", all_people.len());
549
550    if let Err(code) = generate_entity_pages(
551        &html_dir,
552        &all_orgs,
553        &org_cases,
554        &config,
555        &mut nulid_index,
556        "organization",
557        |node, case_list, cfg| html::render_organization(node, case_list, cfg),
558    ) {
559        return code;
560    }
561    eprintln!("html: {} organization pages", all_orgs.len());
562
563    if let Err(code) = generate_sitemap(&html_dir, cases, &all_people, &all_orgs, base_url) {
564        return code;
565    }
566
567    if let Err(code) = generate_tag_pages(&html_dir, cases) {
568        return code;
569    }
570
571    if let Err(code) = write_nulid_index(&html_dir, &nulid_index) {
572        return code;
573    }
574
575    0
576}
577
578/// Write an HTML fragment to disk, creating parent directories as needed.
579fn write_html_file(path: &str, fragment: &str) -> Result<(), i32> {
580    if let Some(parent) = std::path::Path::new(path).parent()
581        && let Err(e) = std::fs::create_dir_all(parent)
582    {
583        eprintln!("error creating directory {}: {e}", parent.display());
584        return Err(2);
585    }
586    if let Err(e) = std::fs::write(path, fragment) {
587        eprintln!("error writing {path}: {e}");
588        return Err(2);
589    }
590    Ok(())
591}
592
593/// Render all case pages and collect entity references for person/org pages.
594#[allow(clippy::type_complexity)]
595fn generate_case_pages<'a>(
596    html_dir: &str,
597    cases: &'a [CaseOutput],
598    config: &html::HtmlConfig,
599    nulid_index: &mut BTreeMap<String, String>,
600) -> Result<
601    (
602        HashMap<String, &'a NodeOutput>,
603        HashMap<String, &'a NodeOutput>,
604        HashMap<String, Vec<(String, String)>>,
605        HashMap<String, Vec<(String, String)>>,
606    ),
607    i32,
608> {
609    let mut person_cases: HashMap<String, Vec<(String, String)>> = HashMap::new();
610    let mut org_cases: HashMap<String, Vec<(String, String)>> = HashMap::new();
611    let mut all_people: HashMap<String, &NodeOutput> = HashMap::new();
612    let mut all_orgs: HashMap<String, &NodeOutput> = HashMap::new();
613
614    for case in cases {
615        let rel_path = case.slug.as_deref().unwrap_or(&case.case_id);
616        let path = format!("{html_dir}/{rel_path}.html");
617
618        match html::render_case(case, config) {
619            Ok(fragment) => {
620                write_html_file(&path, &fragment)?;
621                eprintln!("html: {path}");
622            }
623            Err(e) => {
624                eprintln!("error rendering case {}: {e}", case.case_id);
625                return Err(2);
626            }
627        }
628
629        if let Some(slug) = &case.slug {
630            nulid_index.insert(case.id.clone(), slug.clone());
631        }
632
633        let case_link_slug = case.slug.as_deref().unwrap_or(&case.case_id).to_string();
634        for node in &case.nodes {
635            match node.label.as_str() {
636                "person" => {
637                    person_cases
638                        .entry(node.id.clone())
639                        .or_default()
640                        .push((case_link_slug.clone(), case.title.clone()));
641                    all_people.entry(node.id.clone()).or_insert(node);
642                }
643                "organization" => {
644                    org_cases
645                        .entry(node.id.clone())
646                        .or_default()
647                        .push((case_link_slug.clone(), case.title.clone()));
648                    all_orgs.entry(node.id.clone()).or_insert(node);
649                }
650                _ => {}
651            }
652        }
653    }
654
655    Ok((all_people, all_orgs, person_cases, org_cases))
656}
657
658/// Render entity pages (person or organization) and update the NULID index.
659fn generate_entity_pages<F>(
660    html_dir: &str,
661    entities: &HashMap<String, &NodeOutput>,
662    entity_cases: &HashMap<String, Vec<(String, String)>>,
663    config: &html::HtmlConfig,
664    nulid_index: &mut BTreeMap<String, String>,
665    label: &str,
666    render_fn: F,
667) -> Result<(), i32>
668where
669    F: Fn(&NodeOutput, &[(String, String)], &html::HtmlConfig) -> Result<String, String>,
670{
671    for (id, node) in entities {
672        let case_list = entity_cases.get(id).cloned().unwrap_or_default();
673        match render_fn(node, &case_list, config) {
674            Ok(fragment) => {
675                let rel_path = node.slug.as_deref().unwrap_or(id.as_str());
676                let path = format!("{html_dir}/{rel_path}.html");
677                write_html_file(&path, &fragment)?;
678            }
679            Err(e) => {
680                eprintln!("error rendering {label} {id}: {e}");
681                return Err(2);
682            }
683        }
684
685        if let Some(slug) = &node.slug {
686            nulid_index.insert(id.clone(), slug.clone());
687        }
688    }
689    Ok(())
690}
691
692/// Generate the sitemap.xml file.
693fn generate_sitemap(
694    html_dir: &str,
695    cases: &[CaseOutput],
696    all_people: &HashMap<String, &NodeOutput>,
697    all_orgs: &HashMap<String, &NodeOutput>,
698    base_url: &str,
699) -> Result<(), i32> {
700    let case_entries: Vec<(String, String)> = cases
701        .iter()
702        .map(|c| {
703            let slug = c.slug.as_deref().unwrap_or(&c.case_id).to_string();
704            (slug, c.title.clone())
705        })
706        .collect();
707    let people_entries: Vec<(String, String)> = all_people
708        .iter()
709        .map(|(id, n)| {
710            let slug = n.slug.as_deref().unwrap_or(id.as_str()).to_string();
711            (slug, n.name.clone())
712        })
713        .collect();
714    let org_entries: Vec<(String, String)> = all_orgs
715        .iter()
716        .map(|(id, n)| {
717            let slug = n.slug.as_deref().unwrap_or(id.as_str()).to_string();
718            (slug, n.name.clone())
719        })
720        .collect();
721
722    let sitemap = html::render_sitemap(&case_entries, &people_entries, &org_entries, base_url);
723    let sitemap_path = format!("{html_dir}/sitemap.xml");
724    if let Err(e) = std::fs::write(&sitemap_path, &sitemap) {
725        eprintln!("error writing {sitemap_path}: {e}");
726        return Err(2);
727    }
728    eprintln!("html: {sitemap_path}");
729    Ok(())
730}
731
732/// Generate tag pages (global and country-scoped).
733fn generate_tag_pages(html_dir: &str, cases: &[CaseOutput]) -> Result<(), i32> {
734    let mut tag_cases: BTreeMap<String, Vec<html::TagCaseEntry>> = BTreeMap::new();
735    let mut country_tag_cases: BTreeMap<String, BTreeMap<String, Vec<html::TagCaseEntry>>> =
736        BTreeMap::new();
737
738    for case in cases {
739        let case_slug = case.slug.as_deref().unwrap_or(&case.case_id).to_string();
740        let country = extract_country_code(&case_slug);
741        let entry = html::TagCaseEntry {
742            slug: case_slug.clone(),
743            title: case.title.clone(),
744            amounts: case.amounts.clone(),
745        };
746        for tag in &case.tags {
747            tag_cases.entry(tag.clone()).or_default().push(html::TagCaseEntry {
748                slug: case_slug.clone(),
749                title: case.title.clone(),
750                amounts: case.amounts.clone(),
751            });
752            if let Some(cc) = &country {
753                country_tag_cases
754                    .entry(cc.clone())
755                    .or_default()
756                    .entry(tag.clone())
757                    .or_default()
758                    .push(html::TagCaseEntry {
759                        slug: entry.slug.clone(),
760                        title: entry.title.clone(),
761                        amounts: entry.amounts.clone(),
762                    });
763            }
764        }
765    }
766
767    let mut tag_page_count = 0usize;
768    for (tag, entries) in &tag_cases {
769        let fragment = html::render_tag_page(tag, entries).map_err(|e| {
770            eprintln!("error rendering tag page {tag}: {e}");
771            2
772        })?;
773        let path = format!("{html_dir}/tags/{tag}.html");
774        write_html_file(&path, &fragment)?;
775        tag_page_count += 1;
776    }
777
778    let mut country_tag_page_count = 0usize;
779    for (country, tags) in &country_tag_cases {
780        for (tag, entries) in tags {
781            let fragment = html::render_tag_page_scoped(tag, country, entries).map_err(|e| {
782                eprintln!("error rendering tag page {country}/{tag}: {e}");
783                2
784            })?;
785            let path = format!("{html_dir}/tags/{country}/{tag}.html");
786            write_html_file(&path, &fragment)?;
787            country_tag_page_count += 1;
788        }
789    }
790
791    eprintln!(
792        "html: {} tag pages ({} global, {} country-scoped)",
793        tag_page_count + country_tag_page_count,
794        tag_page_count,
795        country_tag_page_count
796    );
797    Ok(())
798}
799
800/// Write the NULID-to-slug index JSON file.
801fn write_nulid_index(html_dir: &str, nulid_index: &BTreeMap<String, String>) -> Result<(), i32> {
802    let index_path = format!("{html_dir}/index.json");
803    let json = serde_json::to_string_pretty(nulid_index).map_err(|e| {
804        eprintln!("error serializing index.json: {e}");
805        2
806    })?;
807    if let Err(e) = std::fs::write(&index_path, &json) {
808        eprintln!("error writing {index_path}: {e}");
809        return Err(2);
810    }
811    eprintln!("html: {index_path} ({} entries)", nulid_index.len());
812    Ok(())
813}
814
815#[cfg(test)]
816mod tests {
817    use super::*;
818
819    #[test]
820    fn front_matter_has_id_present() {
821        let content = "---\nid: 01JABC000000000000000000AA\n---\n\n# Test\n";
822        assert!(front_matter_has_id(content));
823    }
824
825    #[test]
826    fn front_matter_has_id_absent() {
827        let content = "---\n---\n\n# Test\n";
828        assert!(!front_matter_has_id(content));
829    }
830
831    #[test]
832    fn front_matter_has_id_with_other_fields() {
833        let content = "---\nother: value\nid: 01JABC000000000000000000AA\n---\n\n# Test\n";
834        assert!(front_matter_has_id(content));
835    }
836
837    #[test]
838    fn front_matter_has_id_no_front_matter() {
839        let content = "# Test\n\nNo front matter here.\n";
840        assert!(!front_matter_has_id(content));
841    }
842
843    #[test]
844    fn front_matter_has_id_outside_front_matter() {
845        // `id:` appearing in the body should not count
846        let content = "---\n---\n\n# Test\n\n- id: some-value\n";
847        assert!(!front_matter_has_id(content));
848    }
849}