Skip to main content

weave_content/
html.rs

1//! Static HTML generator for case and entity pages.
2//!
3//! Produces semantic HTML fragments (no `<html>`/`<head>`/`<body>` wrapper)
4//! suitable for embedding in a Phoenix layout. Each fragment includes
5//! `data-og-*` attributes on the root element for meta tag extraction,
6//! Schema.org microdata, and a `<script type="application/ld+json">` block.
7
8#![allow(clippy::format_push_string)]
9
10use crate::domain::Jurisdiction;
11use crate::output::{CaseOutput, NodeOutput, RelOutput};
12use crate::parser::SourceEntry;
13use sha2::{Digest, Sha256};
14
15/// Configuration for HTML generation.
16#[derive(Debug, Default, Clone)]
17pub struct HtmlConfig {
18    /// Base URL for rewriting thumbnail image sources.
19    ///
20    /// When set, original thumbnail URLs are rewritten to
21    /// `{base_url}/thumbnails/{sha256_hex[0..32]}.webp` using the same
22    /// deterministic key as `weave-image::thumbnail_key`.
23    ///
24    /// Example: `http://files.web.garage.localhost:3902`
25    pub thumbnail_base_url: Option<String>,
26}
27
28/// Length of the hex-encoded SHA-256 prefix used for thumbnail keys.
29const THUMB_KEY_HEX_LEN: usize = 32;
30
31/// Maximum size for a single HTML fragment file (500 KB).
32const MAX_FRAGMENT_BYTES: usize = 512_000;
33
34/// Generate a complete case page HTML fragment.
35///
36/// # Errors
37///
38/// Returns an error if the rendered HTML exceeds [`MAX_FRAGMENT_BYTES`].
39pub fn render_case(case: &CaseOutput, config: &HtmlConfig) -> Result<String, String> {
40    let mut html = String::with_capacity(8192);
41
42    let og_title = truncate(&case.title, 120);
43    let og_description = build_case_og_description(case);
44
45    // Root element with OG data attributes
46    html.push_str(&format!(
47        "<article class=\"loom-case\" itemscope itemtype=\"https://schema.org/Article\" \
48         data-og-title=\"{}\" \
49         data-og-description=\"{}\" \
50         data-og-type=\"article\" \
51         data-og-url=\"/{}\"{}>\n",
52        escape_attr(&og_title),
53        escape_attr(&og_description),
54        escape_attr(case.slug.as_deref().unwrap_or(&case.case_id)),
55        og_image_attr(case_hero_image(case).as_deref(), config),
56    ));
57
58    // Header
59    let country = case
60        .slug
61        .as_deref()
62        .and_then(extract_country_from_case_slug);
63    render_case_header(&mut html, case, country.as_deref());
64
65    // Financial details — prominent position right after header
66    render_financial_details(&mut html, &case.relationships, &case.nodes);
67
68    // Sources
69    render_sources(&mut html, &case.sources);
70
71    // People section
72    let people: Vec<&NodeOutput> = case.nodes.iter().filter(|n| n.label == "person").collect();
73    if !people.is_empty() {
74        render_entity_section(&mut html, "People", &people, config);
75    }
76
77    // Organizations section
78    let orgs: Vec<&NodeOutput> = case
79        .nodes
80        .iter()
81        .filter(|n| n.label == "organization")
82        .collect();
83    if !orgs.is_empty() {
84        render_entity_section(&mut html, "Organizations", &orgs, config);
85    }
86
87    // Timeline section (events sorted by occurred_at)
88    let mut events: Vec<&NodeOutput> = case.nodes.iter().filter(|n| n.label == "event").collect();
89    events.sort_by(|a, b| a.occurred_at.cmp(&b.occurred_at));
90    if !events.is_empty() {
91        render_timeline(&mut html, &events);
92    }
93
94    // Related Cases section
95    render_related_cases(&mut html, &case.relationships, &case.nodes);
96
97    // JSON-LD
98    render_case_json_ld(&mut html, case);
99
100    html.push_str("</article>\n");
101
102    if html.len() > MAX_FRAGMENT_BYTES {
103        return Err(format!(
104            "HTML fragment exceeds {MAX_FRAGMENT_BYTES} bytes ({} bytes)",
105            html.len()
106        ));
107    }
108
109    Ok(html)
110}
111
112/// Generate a person page HTML fragment.
113///
114/// # Errors
115///
116/// Returns an error if the rendered HTML exceeds [`MAX_FRAGMENT_BYTES`].
117pub fn render_person(
118    node: &NodeOutput,
119    cases: &[(String, String)], // (case_id, case_title)
120    config: &HtmlConfig,
121) -> Result<String, String> {
122    let mut html = String::with_capacity(4096);
123
124    let og_title = truncate(&node.name, 120);
125    let og_description = build_person_og_description(node);
126
127    html.push_str(&format!(
128        "<article class=\"loom-person\" itemscope itemtype=\"https://schema.org/Person\" \
129         data-og-title=\"{}\" \
130         data-og-description=\"{}\" \
131         data-og-type=\"profile\" \
132         data-og-url=\"/{}\"{}>\n",
133        escape_attr(&og_title),
134        escape_attr(&og_description),
135        escape_attr(node.slug.as_deref().unwrap_or(&node.id)),
136        og_image_attr(node.thumbnail.as_deref(), config),
137    ));
138
139    render_entity_detail(&mut html, node, config);
140    render_cases_list(&mut html, cases);
141    render_person_json_ld(&mut html, node);
142
143    html.push_str("</article>\n");
144
145    check_size(&html)
146}
147
148/// Generate an organization page HTML fragment.
149///
150/// # Errors
151///
152/// Returns an error if the rendered HTML exceeds [`MAX_FRAGMENT_BYTES`].
153pub fn render_organization(
154    node: &NodeOutput,
155    cases: &[(String, String)],
156    config: &HtmlConfig,
157) -> Result<String, String> {
158    let mut html = String::with_capacity(4096);
159
160    let og_title = truncate(&node.name, 120);
161    let og_description = build_org_og_description(node);
162
163    html.push_str(&format!(
164        "<article class=\"loom-organization\" itemscope itemtype=\"https://schema.org/Organization\" \
165         data-og-title=\"{}\" \
166         data-og-description=\"{}\" \
167         data-og-type=\"profile\" \
168         data-og-url=\"/{}\"{}>\n",
169        escape_attr(&og_title),
170        escape_attr(&og_description),
171        escape_attr(node.slug.as_deref().unwrap_or(&node.id)),
172        og_image_attr(node.thumbnail.as_deref(), config),
173    ));
174
175    render_entity_detail(&mut html, node, config);
176    render_cases_list(&mut html, cases);
177    render_org_json_ld(&mut html, node);
178
179    html.push_str("</article>\n");
180
181    check_size(&html)
182}
183
184// --- Case sections ---
185
186fn render_case_header(html: &mut String, case: &CaseOutput, country: Option<&str>) {
187    html.push_str(&format!(
188        "  <header class=\"loom-case-header\">\n    <h1 itemprop=\"headline\">{}</h1>\n",
189        escape(&case.title)
190    ));
191
192    if !case.amounts.is_empty() {
193        html.push_str("    <div class=\"loom-case-amounts\">\n");
194        for entry in &case.amounts {
195            let approx_cls = if entry.approximate { " loom-amount-approx" } else { "" };
196            let label_cls = entry.label.as_deref().unwrap_or("unlabeled").replace('_', "-");
197            html.push_str(&format!(
198                "      <span class=\"loom-amount-badge loom-amount-{label_cls}{approx_cls}\">{}</span>\n",
199                escape(&entry.format_display())
200            ));
201        }
202        html.push_str("    </div>\n");
203    }
204
205    if !case.tags.is_empty() {
206        html.push_str("    <div class=\"loom-tags\">\n");
207        for tag in &case.tags {
208            let href = match country {
209                Some(cc) => format!("/tags/{}/{}", escape_attr(cc), escape_attr(tag)),
210                None => format!("/tags/{}", escape_attr(tag)),
211            };
212            html.push_str(&format!(
213                "      <a href=\"{}\" class=\"loom-tag\">{}</a>\n",
214                href,
215                escape(tag)
216            ));
217        }
218        html.push_str("    </div>\n");
219    }
220
221    if !case.summary.is_empty() {
222        html.push_str(&format!(
223            "    <p class=\"loom-summary\" itemprop=\"description\">{}</p>\n",
224            escape(&case.summary)
225        ));
226    }
227
228    // Canvas link for the case node
229    html.push_str(&format!(
230        "    <a href=\"/canvas/{}\" class=\"loom-canvas-link\">View on canvas</a>\n",
231        escape_attr(&case.id)
232    ));
233
234    html.push_str("  </header>\n");
235}
236
237fn render_sources(html: &mut String, sources: &[SourceEntry]) {
238    if sources.is_empty() {
239        return;
240    }
241    html.push_str("  <section class=\"loom-sources\">\n    <h2>Sources</h2>\n    <ol>\n");
242    for source in sources {
243        match source {
244            SourceEntry::Url(url) => {
245                html.push_str(&format!(
246                    "      <li><a href=\"{}\" rel=\"noopener noreferrer\" target=\"_blank\">{}</a></li>\n",
247                    escape_attr(url),
248                    escape(url)
249                ));
250            }
251            SourceEntry::Structured { url, title, .. } => {
252                let display = title.as_deref().unwrap_or(url.as_str());
253                html.push_str(&format!(
254                    "      <li><a href=\"{}\" rel=\"noopener noreferrer\" target=\"_blank\">{}</a></li>\n",
255                    escape_attr(url),
256                    escape(display)
257                ));
258            }
259        }
260    }
261    html.push_str("    </ol>\n  </section>\n");
262}
263
264fn render_entity_section(
265    html: &mut String,
266    title: &str,
267    nodes: &[&NodeOutput],
268    config: &HtmlConfig,
269) {
270    html.push_str(&format!(
271        "  <section class=\"loom-entities loom-entities-{}\">\n    <h2>{title}</h2>\n    <div class=\"loom-entity-cards\">\n",
272        title.to_lowercase()
273    ));
274    for node in nodes {
275        render_entity_card(html, node, config);
276    }
277    html.push_str("    </div>\n  </section>\n");
278}
279
280fn render_entity_card(html: &mut String, node: &NodeOutput, config: &HtmlConfig) {
281    let schema_type = match node.label.as_str() {
282        "person" => "Person",
283        "organization" => "Organization",
284        _ => "Thing",
285    };
286    html.push_str(&format!(
287        "      <div class=\"loom-entity-card\" itemscope itemtype=\"https://schema.org/{schema_type}\">\n"
288    ));
289
290    if let Some(thumb) = &node.thumbnail {
291        let thumb_url = rewrite_thumbnail_url(thumb, config);
292        html.push_str(&format!(
293            "        <img src=\"{}\" alt=\"{}\" class=\"loom-thumbnail\" itemprop=\"image\" loading=\"lazy\" width=\"64\" height=\"64\" />\n",
294            escape_attr(&thumb_url),
295            escape_attr(&node.name)
296        ));
297    }
298
299    // Link to static view when slug is available, otherwise fall back to canvas
300    let entity_href = if let Some(slug) = &node.slug {
301        format!("/{}", escape_attr(slug))
302    } else {
303        format!("/canvas/{}", escape_attr(&node.id))
304    };
305
306    html.push_str(&format!(
307        "        <div class=\"loom-entity-info\">\n          \
308         <a href=\"{}\" class=\"loom-entity-name\" itemprop=\"name\">{}</a>\n",
309        entity_href,
310        escape(&node.name)
311    ));
312
313    if let Some(q) = &node.qualifier {
314        html.push_str(&format!(
315            "          <span class=\"loom-qualifier\">{}</span>\n",
316            escape(q)
317        ));
318    }
319
320    // Label-specific fields
321    match node.label.as_str() {
322        "person" => {
323            let roles: Vec<_> = node.role.iter().map(|r| format_enum(r)).collect();
324            render_dl_field(html, "Role", &roles.join(", "));
325            render_dl_opt_country(html, "Nationality", node.nationality.as_ref());
326        }
327        "organization" => {
328            render_dl_opt_formatted(html, "Type", node.org_type.as_ref());
329            if let Some(j) = &node.jurisdiction {
330                render_dl_field(html, "Jurisdiction", &format_jurisdiction(j));
331            }
332        }
333        "asset" => {
334            render_dl_opt_formatted(html, "Type", node.asset_type.as_ref());
335            if let Some(m) = &node.value {
336                render_dl_field(html, "Value", &m.display);
337            }
338            render_dl_opt_formatted(html, "Status", node.status.as_ref());
339        }
340        "document" => {
341            render_dl_opt_formatted(html, "Type", node.doc_type.as_ref());
342            render_dl_opt(html, "Issued", node.issued_at.as_ref());
343        }
344        "event" => {
345            render_dl_opt_formatted(html, "Type", node.event_type.as_ref());
346            render_dl_opt(html, "Date", node.occurred_at.as_ref());
347        }
348        _ => {}
349    }
350
351    html.push_str("        </div>\n      </div>\n");
352}
353
354fn render_timeline(html: &mut String, events: &[&NodeOutput]) {
355    html.push_str(
356        "  <section class=\"loom-timeline\">\n    <h2>Timeline</h2>\n    <ol class=\"loom-events\">\n",
357    );
358    for event in events {
359        html.push_str("      <li class=\"loom-event\">\n");
360        if let Some(date) = &event.occurred_at {
361            html.push_str(&format!(
362                "        <time datetime=\"{}\" class=\"loom-event-date\">{}</time>\n",
363                escape_attr(date),
364                escape(date)
365            ));
366        }
367        html.push_str("        <div class=\"loom-event-body\">\n");
368        html.push_str(&format!(
369            "          <span class=\"loom-event-name\">{}</span>\n",
370            escape(&event.name)
371        ));
372        if let Some(et) = &event.event_type {
373            html.push_str(&format!(
374                "          <span class=\"loom-event-type\">{}</span>\n",
375                escape(&format_enum(et))
376            ));
377        }
378        if let Some(desc) = &event.description {
379            html.push_str(&format!(
380                "          <p class=\"loom-event-description\">{}</p>\n",
381                escape(desc)
382            ));
383        }
384        html.push_str("        </div>\n");
385        html.push_str("      </li>\n");
386    }
387    html.push_str("    </ol>\n  </section>\n");
388}
389
390fn render_related_cases(html: &mut String, relationships: &[RelOutput], nodes: &[NodeOutput]) {
391    let related: Vec<&RelOutput> = relationships
392        .iter()
393        .filter(|r| r.rel_type == "related_to")
394        .collect();
395    if related.is_empty() {
396        return;
397    }
398    html.push_str(
399        "  <section class=\"loom-related-cases\">\n    <h2>Related Cases</h2>\n    <div class=\"loom-related-list\">\n",
400    );
401    for rel in &related {
402        if let Some(node) = nodes
403            .iter()
404            .find(|n| n.id == rel.target_id && n.label == "case")
405        {
406            let href = node
407                .slug
408                .as_deref()
409                .map_or_else(|| format!("/cases/{}", node.id), |s| format!("/{s}"));
410            let desc = rel.description.as_deref().unwrap_or("");
411            html.push_str(&format!(
412                "      <a href=\"{}\" class=\"loom-related-card\">\n        <span class=\"loom-related-title\">{}</span>\n",
413                escape_attr(&href),
414                escape(&node.name)
415            ));
416            if !desc.is_empty() {
417                html.push_str(&format!(
418                    "        <span class=\"loom-related-desc\">{}</span>\n",
419                    escape(desc)
420                ));
421            }
422            html.push_str("      </a>\n");
423        }
424    }
425    html.push_str("    </div>\n  </section>\n");
426}
427
428// --- Financial details ---
429
430fn render_financial_details(html: &mut String, relationships: &[RelOutput], nodes: &[NodeOutput]) {
431    let financial: Vec<&RelOutput> = relationships
432        .iter()
433        .filter(|r| !r.amounts.is_empty())
434        .collect();
435    if financial.is_empty() {
436        return;
437    }
438
439    let node_name = |id: &str| -> String {
440        nodes
441            .iter()
442            .find(|n| n.id == id)
443            .map(|n| n.name.clone())
444            .unwrap_or_else(|| id.to_string())
445    };
446
447    html.push_str(
448        "  <section class=\"loom-financial\">\n    <h2>Financial Details</h2>\n    <dl class=\"loom-financial-list\">\n",
449    );
450    for rel in &financial {
451        let source = node_name(&rel.source_id);
452        let target = node_name(&rel.target_id);
453        let rel_label = format_enum(&rel.rel_type);
454        html.push_str(&format!(
455            "      <div class=\"loom-financial-entry\">\n        <dt>{} &rarr; {} <span class=\"loom-rel-label\">{}</span></dt>\n",
456            escape(&source), escape(&target), escape(&rel_label)
457        ));
458        for entry in &rel.amounts {
459            let approx_cls = if entry.approximate { " loom-amount-approx" } else { "" };
460            html.push_str(&format!(
461                "        <dd><span class=\"loom-amount-badge{}\">{}</span></dd>\n",
462                approx_cls,
463                escape(&entry.format_display())
464            ));
465        }
466        html.push_str("      </div>\n");
467    }
468    html.push_str("    </dl>\n  </section>\n");
469}
470
471// --- Entity detail page ---
472
473fn render_entity_detail(html: &mut String, node: &NodeOutput, config: &HtmlConfig) {
474    html.push_str("  <header class=\"loom-entity-header\">\n");
475
476    if let Some(thumb) = &node.thumbnail {
477        let thumb_url = rewrite_thumbnail_url(thumb, config);
478        html.push_str(&format!(
479            "    <img src=\"{}\" alt=\"{}\" class=\"loom-thumbnail-large\" itemprop=\"image\" loading=\"lazy\" width=\"128\" height=\"128\" />\n",
480            escape_attr(&thumb_url),
481            escape_attr(&node.name)
482        ));
483    }
484
485    html.push_str(&format!(
486        "    <h1 itemprop=\"name\">{}</h1>\n",
487        escape(&node.name)
488    ));
489
490    if let Some(q) = &node.qualifier {
491        html.push_str(&format!(
492            "    <p class=\"loom-qualifier\">{}</p>\n",
493            escape(q)
494        ));
495    }
496
497    html.push_str(&format!(
498        "    <a href=\"/canvas/{}\" class=\"loom-canvas-link\">View on canvas</a>\n",
499        escape_attr(&node.id)
500    ));
501    html.push_str("  </header>\n");
502
503    // Description
504    if let Some(desc) = &node.description {
505        html.push_str(&format!(
506            "  <p class=\"loom-description\" itemprop=\"description\">{}</p>\n",
507            escape(desc)
508        ));
509    }
510
511    // Fields as definition list
512    html.push_str("  <dl class=\"loom-fields\">\n");
513
514    match node.label.as_str() {
515        "person" => {
516            let roles: Vec<_> = node.role.iter().map(|r| format_enum(r)).collect();
517            render_dl_item(html, "Role", &roles.join(", "));
518            render_dl_opt_country_item(html, "Nationality", node.nationality.as_ref());
519            render_dl_opt_item(html, "Date of Birth", node.date_of_birth.as_ref());
520            render_dl_opt_item(html, "Place of Birth", node.place_of_birth.as_ref());
521            render_dl_opt_formatted_item(html, "Status", node.status.as_ref());
522        }
523        "organization" => {
524            render_dl_opt_formatted_item(html, "Type", node.org_type.as_ref());
525            if let Some(j) = &node.jurisdiction {
526                render_dl_item(html, "Jurisdiction", &format_jurisdiction(j));
527            }
528            render_dl_opt_item(html, "Headquarters", node.headquarters.as_ref());
529            render_dl_opt_item(html, "Founded", node.founded_date.as_ref());
530            render_dl_opt_item(html, "Registration", node.registration_number.as_ref());
531            render_dl_opt_formatted_item(html, "Status", node.status.as_ref());
532        }
533        "asset" => {
534            render_dl_opt_formatted_item(html, "Type", node.asset_type.as_ref());
535            if let Some(m) = &node.value {
536                render_dl_item(html, "Value", &m.display);
537            }
538            render_dl_opt_formatted_item(html, "Status", node.status.as_ref());
539        }
540        "document" => {
541            render_dl_opt_formatted_item(html, "Type", node.doc_type.as_ref());
542            render_dl_opt_item(html, "Issued", node.issued_at.as_ref());
543            render_dl_opt_item(html, "Issuing Authority", node.issuing_authority.as_ref());
544            render_dl_opt_item(html, "Case Number", node.case_number.as_ref());
545        }
546        "event" => {
547            render_dl_opt_formatted_item(html, "Type", node.event_type.as_ref());
548            render_dl_opt_item(html, "Date", node.occurred_at.as_ref());
549            render_dl_opt_formatted_item(html, "Severity", node.severity.as_ref());
550            if let Some(j) = &node.jurisdiction {
551                render_dl_item(html, "Jurisdiction", &format_jurisdiction(j));
552            }
553        }
554        _ => {}
555    }
556
557    html.push_str("  </dl>\n");
558
559    // Aliases
560    if !node.aliases.is_empty() {
561        html.push_str("  <div class=\"loom-aliases\">\n    <h3>Also known as</h3>\n    <ul>\n");
562        for alias in &node.aliases {
563            html.push_str(&format!("      <li>{}</li>\n", escape(alias)));
564        }
565        html.push_str("    </ul>\n  </div>\n");
566    }
567}
568
569fn render_cases_list(html: &mut String, cases: &[(String, String)]) {
570    if cases.is_empty() {
571        return;
572    }
573    html.push_str(
574        "  <section class=\"loom-cases\">\n    <h2>Cases</h2>\n    <ul class=\"loom-case-list\">\n",
575    );
576    for (case_slug, case_title) in cases {
577        html.push_str(&format!(
578            "      <li><a href=\"/{}\">{}</a></li>\n",
579            escape_attr(case_slug),
580            escape(case_title)
581        ));
582    }
583    html.push_str("    </ul>\n  </section>\n");
584}
585
586// --- JSON-LD ---
587
588fn render_case_json_ld(html: &mut String, case: &CaseOutput) {
589    let mut ld = serde_json::json!({
590        "@context": "https://schema.org",
591        "@type": "Article",
592        "headline": truncate(&case.title, 120),
593        "description": truncate(&case.summary, 200),
594        "url": format!("/{}", case.slug.as_deref().unwrap_or(&case.case_id)),
595    });
596
597    if !case.sources.is_empty() {
598        let urls: Vec<&str> = case
599            .sources
600            .iter()
601            .map(|s| match s {
602                SourceEntry::Url(u) => u.as_str(),
603                SourceEntry::Structured { url, .. } => url.as_str(),
604            })
605            .collect();
606        ld["citation"] = serde_json::json!(urls);
607    }
608
609    html.push_str(&format!(
610        "  <script type=\"application/ld+json\">{}</script>\n",
611        serde_json::to_string(&ld).unwrap_or_default()
612    ));
613}
614
615fn render_person_json_ld(html: &mut String, node: &NodeOutput) {
616    let mut ld = serde_json::json!({
617        "@context": "https://schema.org",
618        "@type": "Person",
619        "name": &node.name,
620        "url": format!("/{}", node.slug.as_deref().unwrap_or(&node.id)),
621    });
622
623    if let Some(nat) = &node.nationality {
624        ld["nationality"] = serde_json::json!(nat);
625    }
626    if let Some(desc) = &node.description {
627        ld["description"] = serde_json::json!(truncate(desc, 200));
628    }
629    if let Some(thumb) = &node.thumbnail {
630        ld["image"] = serde_json::json!(thumb);
631    }
632
633    html.push_str(&format!(
634        "  <script type=\"application/ld+json\">{}</script>\n",
635        serde_json::to_string(&ld).unwrap_or_default()
636    ));
637}
638
639fn render_org_json_ld(html: &mut String, node: &NodeOutput) {
640    let mut ld = serde_json::json!({
641        "@context": "https://schema.org",
642        "@type": "Organization",
643        "name": &node.name,
644        "url": format!("/{}", node.slug.as_deref().unwrap_or(&node.id)),
645    });
646
647    if let Some(desc) = &node.description {
648        ld["description"] = serde_json::json!(truncate(desc, 200));
649    }
650    if let Some(thumb) = &node.thumbnail {
651        ld["logo"] = serde_json::json!(thumb);
652    }
653
654    html.push_str(&format!(
655        "  <script type=\"application/ld+json\">{}</script>\n",
656        serde_json::to_string(&ld).unwrap_or_default()
657    ));
658}
659
660// --- Tag pages ---
661
662/// A case entry associated with a tag, used for tag page rendering.
663pub struct TagCaseEntry {
664    /// Display slug for the case link (e.g. `cases/id/corruption/2024/test-case`).
665    pub slug: String,
666    /// Case title.
667    pub title: String,
668    /// Structured amounts for display badge.
669    pub amounts: Vec<crate::domain::AmountEntry>,
670}
671
672/// Generate a tag page HTML fragment listing all cases with this tag.
673///
674/// # Errors
675///
676/// Returns an error if the rendered HTML exceeds [`MAX_FRAGMENT_BYTES`].
677pub fn render_tag_page(tag: &str, cases: &[TagCaseEntry]) -> Result<String, String> {
678    render_tag_page_with_path(tag, &format!("/tags/{}", escape_attr(tag)), cases)
679}
680
681pub fn render_tag_page_scoped(
682    tag: &str,
683    country: &str,
684    cases: &[TagCaseEntry],
685) -> Result<String, String> {
686    let display_tag = format!("{} ({})", tag.replace('-', " "), country.to_uppercase());
687    render_tag_page_with_path(
688        &display_tag,
689        &format!("/tags/{}/{}", escape_attr(country), escape_attr(tag)),
690        cases,
691    )
692}
693
694fn render_tag_page_with_path(
695    display: &str,
696    og_url: &str,
697    cases: &[TagCaseEntry],
698) -> Result<String, String> {
699    let mut html = String::with_capacity(2048);
700
701    let og_title = format!("Cases tagged \"{display}\"");
702
703    html.push_str(&format!(
704        "<article class=\"loom-tag-page\" \
705         data-og-title=\"{}\" \
706         data-og-description=\"{} cases tagged with {}\" \
707         data-og-type=\"website\" \
708         data-og-url=\"{}\">\n",
709        escape_attr(&og_title),
710        cases.len(),
711        escape_attr(display),
712        escape_attr(og_url),
713    ));
714
715    html.push_str(&format!(
716        "  <header class=\"loom-tag-header\">\n    \
717         <h1>{}</h1>\n    \
718         <p class=\"loom-tag-count\">{} cases</p>\n  \
719         </header>\n",
720        escape(display),
721        cases.len(),
722    ));
723
724    html.push_str("  <ul class=\"loom-case-list\">\n");
725    for entry in cases {
726        let amount_badges = if entry.amounts.is_empty() {
727            String::new()
728        } else {
729            let badges: Vec<String> = entry
730                .amounts
731                .iter()
732                .map(|a| {
733                    format!(
734                        " <span class=\"loom-amount-badge\">{}</span>",
735                        escape(&a.format_display())
736                    )
737                })
738                .collect();
739            badges.join("")
740        };
741        html.push_str(&format!(
742            "    <li><a href=\"/{}\">{}</a>{}</li>\n",
743            escape_attr(&entry.slug),
744            escape(&entry.title),
745            amount_badges,
746        ));
747    }
748    html.push_str("  </ul>\n");
749
750    html.push_str("</article>\n");
751
752    check_size(&html)
753}
754
755// --- Sitemap ---
756
757/// Generate a sitemap XML string.
758///
759/// All tuples are `(slug, display_name)` where slug is the full file-path slug
760/// (e.g. `cases/id/corruption/2024/hambalang-case`).
761pub fn render_sitemap(
762    cases: &[(String, String)],
763    people: &[(String, String)],
764    organizations: &[(String, String)],
765    base_url: &str,
766) -> String {
767    let mut xml = String::with_capacity(4096);
768    xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
769    xml.push_str("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
770
771    for (slug, _) in cases {
772        xml.push_str(&format!(
773            "  <url><loc>{base_url}/{}</loc></url>\n",
774            escape(slug)
775        ));
776    }
777    for (slug, _) in people {
778        xml.push_str(&format!(
779            "  <url><loc>{base_url}/{}</loc></url>\n",
780            escape(slug)
781        ));
782    }
783    for (slug, _) in organizations {
784        xml.push_str(&format!(
785            "  <url><loc>{base_url}/{}</loc></url>\n",
786            escape(slug)
787        ));
788    }
789
790    xml.push_str("</urlset>\n");
791    xml
792}
793
794// --- Helpers ---
795
796fn build_case_og_description(case: &CaseOutput) -> String {
797    if !case.summary.is_empty() {
798        return truncate(&case.summary, 200);
799    }
800    let people_count = case.nodes.iter().filter(|n| n.label == "person").count();
801    let org_count = case
802        .nodes
803        .iter()
804        .filter(|n| n.label == "organization")
805        .count();
806    truncate(
807        &format!(
808            "{} people, {} organizations, {} connections",
809            people_count,
810            org_count,
811            case.relationships.len()
812        ),
813        200,
814    )
815}
816
817fn build_person_og_description(node: &NodeOutput) -> String {
818    let mut parts = Vec::new();
819    if let Some(q) = &node.qualifier {
820        parts.push(q.clone());
821    }
822    if !node.role.is_empty() {
823        let roles: Vec<_> = node.role.iter().map(|r| format_enum(r)).collect();
824        parts.push(roles.join(", "));
825    }
826    if let Some(nat) = &node.nationality {
827        parts.push(country_name(nat));
828    }
829    if parts.is_empty() {
830        return truncate(&node.name, 200);
831    }
832    truncate(&format!("{} — {}", node.name, parts.join(" · ")), 200)
833}
834
835fn build_org_og_description(node: &NodeOutput) -> String {
836    let mut parts = Vec::new();
837    if let Some(q) = &node.qualifier {
838        parts.push(q.clone());
839    }
840    if let Some(ot) = &node.org_type {
841        parts.push(format_enum(ot));
842    }
843    if let Some(j) = &node.jurisdiction {
844        parts.push(format_jurisdiction(j));
845    }
846    if parts.is_empty() {
847        return truncate(&node.name, 200);
848    }
849    truncate(&format!("{} — {}", node.name, parts.join(" · ")), 200)
850}
851
852fn check_size(html: &str) -> Result<String, String> {
853    if html.len() > MAX_FRAGMENT_BYTES {
854        Err(format!(
855            "HTML fragment exceeds {MAX_FRAGMENT_BYTES} bytes ({} bytes)",
856            html.len()
857        ))
858    } else {
859        Ok(html.to_string())
860    }
861}
862
863fn truncate(s: &str, max: usize) -> String {
864    if s.len() <= max {
865        s.to_string()
866    } else {
867        let truncated: String = s.chars().take(max.saturating_sub(3)).collect();
868        format!("{truncated}...")
869    }
870}
871
872fn escape(s: &str) -> String {
873    s.replace('&', "&amp;")
874        .replace('<', "&lt;")
875        .replace('>', "&gt;")
876        .replace('"', "&quot;")
877}
878
879fn escape_attr(s: &str) -> String {
880    escape(s)
881}
882
883/// Rewrite a thumbnail source URL to a hosted URL.
884///
885/// When `config.thumbnail_base_url` is set, computes the deterministic
886/// key `thumbnails/{sha256_hex[0..32]}.webp` (matching `weave-image`)
887/// and returns `{base_url}/thumbnails/{hash}.webp`.
888///
889/// When not set, returns the original URL unchanged.
890fn rewrite_thumbnail_url(source_url: &str, config: &HtmlConfig) -> String {
891    match &config.thumbnail_base_url {
892        Some(base) => {
893            let key = thumbnail_key(source_url);
894            format!("{base}/{key}")
895        }
896        None => source_url.to_string(),
897    }
898}
899
900/// Compute the thumbnail object key from a source URL.
901///
902/// Returns `thumbnails/{sha256_hex[0..32]}.webp`, matching the algorithm
903/// in `weave-image::thumbnail_key`.
904fn thumbnail_key(source_url: &str) -> String {
905    let mut hasher = Sha256::new();
906    hasher.update(source_url.as_bytes());
907    let hash = hasher.finalize();
908    let hex = hex_encode(&hash);
909    format!("thumbnails/{}.webp", &hex[..THUMB_KEY_HEX_LEN])
910}
911
912/// Encode bytes as lowercase hex string.
913fn hex_encode(bytes: &[u8]) -> String {
914    bytes.iter().map(|b| format!("{b:02x}")).collect()
915}
916
917/// Build `data-og-image` attribute string if a URL is available.
918fn og_image_attr(url: Option<&str>, config: &HtmlConfig) -> String {
919    match url {
920        Some(u) if !u.is_empty() => {
921            let rewritten = rewrite_thumbnail_url(u, config);
922            format!(" data-og-image=\"{}\"", escape_attr(&rewritten))
923        }
924        _ => String::new(),
925    }
926}
927
928/// Find the first person thumbnail in a case to use as hero image.
929fn case_hero_image(case: &CaseOutput) -> Option<String> {
930    case.nodes
931        .iter()
932        .filter(|n| n.label == "person")
933        .find_map(|n| n.thumbnail.clone())
934}
935
936fn format_jurisdiction(j: &Jurisdiction) -> String {
937    let country = country_name(&j.country);
938    match &j.subdivision {
939        Some(sub) => format!("{country}, {sub}"),
940        None => country,
941    }
942}
943
944/// Map ISO 3166-1 alpha-2 codes to country names.
945/// Returns the code itself if not found (graceful fallback).
946fn country_name(code: &str) -> String {
947    match code.to_uppercase().as_str() {
948        "AF" => "Afghanistan",
949        "AL" => "Albania",
950        "DZ" => "Algeria",
951        "AR" => "Argentina",
952        "AU" => "Australia",
953        "AT" => "Austria",
954        "BD" => "Bangladesh",
955        "BE" => "Belgium",
956        "BR" => "Brazil",
957        "BN" => "Brunei",
958        "KH" => "Cambodia",
959        "CA" => "Canada",
960        "CN" => "China",
961        "CO" => "Colombia",
962        "HR" => "Croatia",
963        "CZ" => "Czech Republic",
964        "DK" => "Denmark",
965        "EG" => "Egypt",
966        "FI" => "Finland",
967        "FR" => "France",
968        "DE" => "Germany",
969        "GH" => "Ghana",
970        "GR" => "Greece",
971        "HK" => "Hong Kong",
972        "HU" => "Hungary",
973        "IN" => "India",
974        "ID" => "Indonesia",
975        "IR" => "Iran",
976        "IQ" => "Iraq",
977        "IE" => "Ireland",
978        "IL" => "Israel",
979        "IT" => "Italy",
980        "JP" => "Japan",
981        "KE" => "Kenya",
982        "KR" => "South Korea",
983        "KW" => "Kuwait",
984        "LA" => "Laos",
985        "LB" => "Lebanon",
986        "MY" => "Malaysia",
987        "MX" => "Mexico",
988        "MM" => "Myanmar",
989        "NL" => "Netherlands",
990        "NZ" => "New Zealand",
991        "NG" => "Nigeria",
992        "NO" => "Norway",
993        "PK" => "Pakistan",
994        "PH" => "Philippines",
995        "PL" => "Poland",
996        "PT" => "Portugal",
997        "QA" => "Qatar",
998        "RO" => "Romania",
999        "RU" => "Russia",
1000        "SA" => "Saudi Arabia",
1001        "SG" => "Singapore",
1002        "ZA" => "South Africa",
1003        "ES" => "Spain",
1004        "LK" => "Sri Lanka",
1005        "SE" => "Sweden",
1006        "CH" => "Switzerland",
1007        "TW" => "Taiwan",
1008        "TH" => "Thailand",
1009        "TL" => "Timor-Leste",
1010        "TR" => "Turkey",
1011        "AE" => "United Arab Emirates",
1012        "GB" => "United Kingdom",
1013        "US" => "United States",
1014        "VN" => "Vietnam",
1015        _ => return code.to_uppercase(),
1016    }
1017    .to_string()
1018}
1019
1020/// Extract a 2-letter country code from a case slug like `cases/id/corruption/2024/...`.
1021fn extract_country_from_case_slug(slug: &str) -> Option<String> {
1022    let parts: Vec<&str> = slug.split('/').collect();
1023    if parts.len() >= 2 {
1024        let candidate = parts[1];
1025        if candidate.len() == 2 && candidate.chars().all(|c| c.is_ascii_lowercase()) {
1026            return Some(candidate.to_string());
1027        }
1028    }
1029    None
1030}
1031
1032fn format_enum(s: &str) -> String {
1033    if let Some(custom) = s.strip_prefix("custom:") {
1034        return custom.to_string();
1035    }
1036    s.split('_')
1037        .map(|word| {
1038            let mut chars = word.chars();
1039            match chars.next() {
1040                None => String::new(),
1041                Some(c) => {
1042                    let upper: String = c.to_uppercase().collect();
1043                    upper + chars.as_str()
1044                }
1045            }
1046        })
1047        .collect::<Vec<_>>()
1048        .join(" ")
1049}
1050
1051fn render_dl_field(html: &mut String, label: &str, value: &str) {
1052    if !value.is_empty() {
1053        html.push_str(&format!(
1054            "          <span class=\"loom-field\"><strong>{label}:</strong> {}</span>\n",
1055            escape(value)
1056        ));
1057    }
1058}
1059
1060fn render_dl_opt(html: &mut String, label: &str, value: Option<&String>) {
1061    if let Some(v) = value {
1062        render_dl_field(html, label, v);
1063    }
1064}
1065
1066fn render_dl_opt_formatted(html: &mut String, label: &str, value: Option<&String>) {
1067    if let Some(v) = value {
1068        render_dl_field(html, label, &format_enum(v));
1069    }
1070}
1071
1072fn render_dl_item(html: &mut String, label: &str, value: &str) {
1073    if !value.is_empty() {
1074        html.push_str(&format!(
1075            "    <dt>{label}</dt>\n    <dd>{}</dd>\n",
1076            escape(value)
1077        ));
1078    }
1079}
1080
1081fn render_dl_opt_item(html: &mut String, label: &str, value: Option<&String>) {
1082    if let Some(v) = value {
1083        render_dl_item(html, label, v);
1084    }
1085}
1086
1087fn render_dl_opt_country(html: &mut String, label: &str, value: Option<&String>) {
1088    if let Some(v) = value {
1089        render_dl_field(html, label, &country_name(v));
1090    }
1091}
1092
1093fn render_dl_opt_country_item(html: &mut String, label: &str, value: Option<&String>) {
1094    if let Some(v) = value {
1095        render_dl_item(html, label, &country_name(v));
1096    }
1097}
1098
1099fn render_dl_opt_formatted_item(html: &mut String, label: &str, value: Option<&String>) {
1100    if let Some(v) = value {
1101        render_dl_item(html, label, &format_enum(v));
1102    }
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107    use super::*;
1108    use crate::output::{CaseOutput, NodeOutput, RelOutput};
1109    use crate::parser::SourceEntry;
1110
1111    fn make_case() -> CaseOutput {
1112        CaseOutput {
1113            id: "01TESTCASE0000000000000000".into(),
1114            case_id: "test-case".into(),
1115            title: "Test Corruption Case".into(),
1116            summary: "A politician was caught accepting bribes.".into(),
1117            tags: vec!["bribery".into(), "government".into()],
1118            slug: None,
1119            case_type: None,
1120            amounts: vec![],
1121            status: None,
1122            nodes: vec![
1123                NodeOutput {
1124                    id: "01AAA".into(),
1125                    label: "person".into(),
1126                    name: "John Doe".into(),
1127                    slug: Some("people/id/john-doe--governor-of-test-province".into()),
1128                    qualifier: Some("Governor of Test Province".into()),
1129                    description: None,
1130                    thumbnail: Some("https://files.example.com/thumb.webp".into()),
1131                    aliases: vec![],
1132                    urls: vec![],
1133                    role: vec!["politician".into()],
1134                    nationality: Some("ID".into()),
1135                    date_of_birth: None,
1136                    place_of_birth: None,
1137                    status: Some("convicted".into()),
1138                    org_type: None,
1139                    jurisdiction: None,
1140                    headquarters: None,
1141                    founded_date: None,
1142                    registration_number: None,
1143                    event_type: None,
1144                    occurred_at: None,
1145                    severity: None,
1146                    doc_type: None,
1147                    issued_at: None,
1148                    issuing_authority: None,
1149                    case_number: None,
1150                    case_type: None,
1151                    amounts: vec![],
1152                    asset_type: None,
1153                    value: None,
1154                    tags: vec![],
1155                },
1156                NodeOutput {
1157                    id: "01BBB".into(),
1158                    label: "organization".into(),
1159                    name: "KPK".into(),
1160                    slug: Some("organizations/id/kpk--anti-corruption-commission".into()),
1161                    qualifier: Some("Anti-Corruption Commission".into()),
1162                    description: None,
1163                    thumbnail: None,
1164                    aliases: vec![],
1165                    urls: vec![],
1166                    role: vec![],
1167                    nationality: None,
1168                    date_of_birth: None,
1169                    place_of_birth: None,
1170                    status: None,
1171                    org_type: Some("government_agency".into()),
1172                    jurisdiction: Some(Jurisdiction {
1173                        country: "ID".into(),
1174                        subdivision: None,
1175                    }),
1176                    headquarters: None,
1177                    founded_date: None,
1178                    registration_number: None,
1179                    event_type: None,
1180                    occurred_at: None,
1181                    severity: None,
1182                    doc_type: None,
1183                    issued_at: None,
1184                    issuing_authority: None,
1185                    case_number: None,
1186                    case_type: None,
1187                    amounts: vec![],
1188                    asset_type: None,
1189                    value: None,
1190                    tags: vec![],
1191                },
1192                NodeOutput {
1193                    id: "01CCC".into(),
1194                    label: "event".into(),
1195                    name: "Arrest".into(),
1196                    slug: None,
1197                    qualifier: None,
1198                    description: Some("John Doe arrested by KPK.".into()),
1199                    thumbnail: None,
1200                    aliases: vec![],
1201                    urls: vec![],
1202                    role: vec![],
1203                    nationality: None,
1204                    date_of_birth: None,
1205                    place_of_birth: None,
1206                    status: None,
1207                    org_type: None,
1208                    jurisdiction: None,
1209                    headquarters: None,
1210                    founded_date: None,
1211                    registration_number: None,
1212                    event_type: Some("arrest".into()),
1213                    occurred_at: Some("2024-03-15".into()),
1214                    severity: None,
1215                    doc_type: None,
1216                    issued_at: None,
1217                    issuing_authority: None,
1218                    case_number: None,
1219                    case_type: None,
1220                    amounts: vec![],
1221                    asset_type: None,
1222                    value: None,
1223                    tags: vec![],
1224                },
1225            ],
1226            relationships: vec![RelOutput {
1227                id: "01DDD".into(),
1228                rel_type: "investigated_by".into(),
1229                source_id: "01BBB".into(),
1230                target_id: "01CCC".into(),
1231                source_urls: vec![],
1232                description: None,
1233                amounts: vec![],
1234                valid_from: None,
1235                valid_until: None,
1236            }],
1237            sources: vec![SourceEntry::Url("https://example.com/article".into())],
1238        }
1239    }
1240
1241    #[test]
1242    fn render_case_produces_valid_html() {
1243        let case = make_case();
1244        let config = HtmlConfig::default();
1245        let html = render_case(&case, &config).unwrap();
1246
1247        assert!(html.starts_with("<article"));
1248        assert!(html.ends_with("</article>\n"));
1249        assert!(html.contains("data-og-title=\"Test Corruption Case\""));
1250        assert!(html.contains("data-og-description="));
1251        assert!(html.contains("<h1 itemprop=\"headline\">Test Corruption Case</h1>"));
1252        assert!(html.contains("loom-tag"));
1253        assert!(html.contains("bribery"));
1254        assert!(html.contains("John Doe"));
1255        assert!(html.contains("KPK"));
1256        assert!(html.contains("Arrest"));
1257        assert!(html.contains("2024-03-15"));
1258        assert!(html.contains("application/ld+json"));
1259        // Case header has canvas link
1260        assert!(html.contains("View on canvas"));
1261        assert!(html.contains("/canvas/01TESTCASE0000000000000000"));
1262    }
1263
1264    #[test]
1265    fn render_case_has_sources() {
1266        let case = make_case();
1267        let config = HtmlConfig::default();
1268        let html = render_case(&case, &config).unwrap();
1269        assert!(html.contains("Sources"));
1270        assert!(html.contains("https://example.com/article"));
1271    }
1272
1273    #[test]
1274    fn render_case_entity_cards_link_to_static_views() {
1275        let case = make_case();
1276        let config = HtmlConfig::default();
1277        let html = render_case(&case, &config).unwrap();
1278
1279        // Entity cards should link to static views, not canvas
1280        assert!(html.contains("href=\"/people/id/john-doe--governor-of-test-province\""));
1281        assert!(html.contains("href=\"/organizations/id/kpk--anti-corruption-commission\""));
1282        // Should NOT link to /canvas/ for entities with slugs
1283        assert!(!html.contains("href=\"/canvas/01AAA\""));
1284        assert!(!html.contains("href=\"/canvas/01BBB\""));
1285    }
1286
1287    #[test]
1288    fn render_case_entity_cards_fallback_to_canvas() {
1289        let mut case = make_case();
1290        let config = HtmlConfig::default();
1291        // Remove slugs from entities
1292        for node in &mut case.nodes {
1293            node.slug = None;
1294        }
1295        let html = render_case(&case, &config).unwrap();
1296
1297        // Without slugs, entity cards fall back to canvas links
1298        assert!(html.contains("href=\"/canvas/01AAA\""));
1299        assert!(html.contains("href=\"/canvas/01BBB\""));
1300    }
1301
1302    #[test]
1303    fn render_case_omits_connections_table() {
1304        let case = make_case();
1305        let config = HtmlConfig::default();
1306        let html = render_case(&case, &config).unwrap();
1307        // Connections table is intentionally omitted — relationships are
1308        // already expressed in People/Organizations cards and Timeline
1309        assert!(!html.contains("Connections"));
1310        assert!(!html.contains("loom-rel-table"));
1311    }
1312
1313    #[test]
1314    fn render_person_page() {
1315        let case = make_case();
1316        let config = HtmlConfig::default();
1317        let person = &case.nodes[0];
1318        let cases_list = vec![("test-case".into(), "Test Corruption Case".into())];
1319        let html = render_person(person, &cases_list, &config).unwrap();
1320
1321        assert!(html.contains("itemtype=\"https://schema.org/Person\""));
1322        assert!(html.contains("John Doe"));
1323        assert!(html.contains("Governor of Test Province"));
1324        assert!(html.contains("/canvas/01AAA"));
1325        assert!(html.contains("Test Corruption Case"));
1326        assert!(html.contains("application/ld+json"));
1327    }
1328
1329    #[test]
1330    fn render_organization_page() {
1331        let case = make_case();
1332        let config = HtmlConfig::default();
1333        let org = &case.nodes[1];
1334        let cases_list = vec![("test-case".into(), "Test Corruption Case".into())];
1335        let html = render_organization(org, &cases_list, &config).unwrap();
1336
1337        assert!(html.contains("itemtype=\"https://schema.org/Organization\""));
1338        assert!(html.contains("KPK"));
1339        assert!(html.contains("Indonesia")); // jurisdiction (resolved from ID)
1340    }
1341
1342    #[test]
1343    fn render_sitemap_includes_all_urls() {
1344        let cases = vec![("cases/id/corruption/2024/test-case".into(), "Case 1".into())];
1345        let people = vec![("people/id/john-doe".into(), "John".into())];
1346        let orgs = vec![("organizations/id/test-corp".into(), "Corp".into())];
1347        let xml = render_sitemap(&cases, &people, &orgs, "https://redberrythread.org");
1348
1349        assert!(xml.contains("<?xml"));
1350        assert!(xml.contains("/cases/id/corruption/2024/test-case"));
1351        assert!(xml.contains("/people/id/john-doe"));
1352        assert!(xml.contains("/organizations/id/test-corp"));
1353    }
1354
1355    #[test]
1356    fn escape_html_special_chars() {
1357        assert_eq!(escape("<script>"), "&lt;script&gt;");
1358        assert_eq!(escape("AT&T"), "AT&amp;T");
1359        assert_eq!(escape("\"quoted\""), "&quot;quoted&quot;");
1360    }
1361
1362    #[test]
1363    fn truncate_short_string() {
1364        assert_eq!(truncate("hello", 10), "hello");
1365    }
1366
1367    #[test]
1368    fn truncate_long_string() {
1369        let long = "a".repeat(200);
1370        let result = truncate(&long, 120);
1371        assert!(result.len() <= 120);
1372        assert!(result.ends_with("..."));
1373    }
1374
1375    #[test]
1376    fn format_enum_underscore() {
1377        assert_eq!(format_enum("investigated_by"), "Investigated By");
1378        assert_eq!(format_enum("custom:Special Type"), "Special Type");
1379    }
1380
1381    #[test]
1382    fn thumbnail_key_deterministic() {
1383        let k1 = thumbnail_key("https://example.com/photo.jpg");
1384        let k2 = thumbnail_key("https://example.com/photo.jpg");
1385        assert_eq!(k1, k2);
1386        assert!(k1.starts_with("thumbnails/"));
1387        assert!(k1.ends_with(".webp"));
1388        // Key hex part is 32 chars
1389        let hex_part = k1
1390            .strip_prefix("thumbnails/")
1391            .and_then(|s| s.strip_suffix(".webp"))
1392            .unwrap_or("");
1393        assert_eq!(hex_part.len(), THUMB_KEY_HEX_LEN);
1394    }
1395
1396    #[test]
1397    fn thumbnail_key_different_urls_differ() {
1398        let k1 = thumbnail_key("https://example.com/a.jpg");
1399        let k2 = thumbnail_key("https://example.com/b.jpg");
1400        assert_ne!(k1, k2);
1401    }
1402
1403    #[test]
1404    fn rewrite_thumbnail_url_no_config() {
1405        let config = HtmlConfig::default();
1406        let result = rewrite_thumbnail_url("https://example.com/photo.jpg", &config);
1407        assert_eq!(result, "https://example.com/photo.jpg");
1408    }
1409
1410    #[test]
1411    fn rewrite_thumbnail_url_with_base() {
1412        let config = HtmlConfig {
1413            thumbnail_base_url: Some("http://files.garage.local:3902/files".into()),
1414        };
1415        let result = rewrite_thumbnail_url("https://example.com/photo.jpg", &config);
1416        assert!(result.starts_with("http://files.garage.local:3902/files/thumbnails/"));
1417        assert!(result.ends_with(".webp"));
1418        assert!(!result.contains("example.com"));
1419    }
1420
1421    #[test]
1422    fn render_case_rewrites_thumbnails() {
1423        let case = make_case();
1424        let config = HtmlConfig {
1425            thumbnail_base_url: Some("http://garage.local/files".into()),
1426        };
1427        let html = render_case(&case, &config).unwrap();
1428
1429        // Original URL should not appear in img src
1430        assert!(!html.contains("src=\"https://files.example.com/thumb.webp\""));
1431        // Rewritten URL should appear
1432        assert!(html.contains("src=\"http://garage.local/files/thumbnails/"));
1433        // OG image should also be rewritten
1434        assert!(html.contains("data-og-image=\"http://garage.local/files/thumbnails/"));
1435    }
1436
1437    #[test]
1438    fn render_person_rewrites_thumbnails() {
1439        let case = make_case();
1440        let person = &case.nodes[0];
1441        let config = HtmlConfig {
1442            thumbnail_base_url: Some("http://garage.local/files".into()),
1443        };
1444        let html = render_person(person, &[], &config).unwrap();
1445
1446        assert!(!html.contains("src=\"https://files.example.com/thumb.webp\""));
1447        assert!(html.contains("src=\"http://garage.local/files/thumbnails/"));
1448    }
1449
1450    #[test]
1451    fn render_case_with_related_cases() {
1452        let mut case = make_case();
1453        // Add a related_to relationship and target case node
1454        case.relationships.push(RelOutput {
1455            id: "01RELID".into(),
1456            rel_type: "related_to".into(),
1457            source_id: "01TESTCASE0000000000000000".into(),
1458            target_id: "01TARGETCASE000000000000000".into(),
1459            source_urls: vec![],
1460            description: Some("Connected bribery scandal".into()),
1461            amounts: vec![],
1462            valid_from: None,
1463            valid_until: None,
1464        });
1465        case.nodes.push(NodeOutput {
1466            id: "01TARGETCASE000000000000000".into(),
1467            label: "case".into(),
1468            name: "Target Scandal Case".into(),
1469            slug: Some("cases/id/corruption/2002/target-scandal".into()),
1470            qualifier: None,
1471            description: None,
1472            thumbnail: None,
1473            aliases: vec![],
1474            urls: vec![],
1475            role: vec![],
1476            nationality: None,
1477            date_of_birth: None,
1478            place_of_birth: None,
1479            status: None,
1480            org_type: None,
1481            jurisdiction: None,
1482            headquarters: None,
1483            founded_date: None,
1484            registration_number: None,
1485            event_type: None,
1486            occurred_at: None,
1487            severity: None,
1488            doc_type: None,
1489            issued_at: None,
1490            issuing_authority: None,
1491            case_number: None,
1492            case_type: None,
1493            amounts: vec![],
1494            asset_type: None,
1495            value: None,
1496            tags: vec![],
1497        });
1498
1499        let config = HtmlConfig::default();
1500        let html = render_case(&case, &config).unwrap();
1501
1502        assert!(html.contains("loom-related-cases"));
1503        assert!(html.contains("Related Cases"));
1504        assert!(html.contains("Target Scandal Case"));
1505        assert!(html.contains("loom-related-card"));
1506        assert!(html.contains("Connected bribery scandal"));
1507    }
1508
1509    #[test]
1510    fn render_case_without_related_cases() {
1511        let case = make_case();
1512        let config = HtmlConfig::default();
1513        let html = render_case(&case, &config).unwrap();
1514
1515        assert!(!html.contains("loom-related-cases"));
1516    }
1517}