isis-report-lib 0.2.0

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! Report pipeline: prepare -> HTML -> (PDF). CSV/XLSX reuse the prepared shape.

use std::path::{Path, PathBuf};

use indexmap::IndexMap;

use crate::charts::build_chart;
use crate::crosstab::{build_crosstab, Crosstab};
use crate::error::{Error, Result};
use crate::formatting::normalize_footnote;
use crate::layout::{assign_report_footnotes, build_report, collect_footnotes, infer_layout, is_template_format, template_header_layout};
use crate::media::normalize_image_src;
use crate::payload::{normalize_payload, Limits, Meta, Payload};
use crate::pyops;
use crate::rendering::render_report_html;
use crate::value::Value;

#[cfg(feature = "pdf")]
use crate::pdf_backend::{Margins, PageFormat, PdfBackend, PdfOptions};

/// Prepared report: dataset, layout and normalized metadata.
#[derive(Debug, Clone)]
pub struct PreparedReport {
    /// Template-ready dataset.
    pub dataset: Value,
    /// Template-ready layout.
    pub layout: Value,
    /// Normalized metadata.
    pub meta: Meta,
}

fn footnotes_value(footnotes: &[(String, String)]) -> Value {
    Value::Array(
        footnotes
            .iter()
            .map(|(mark, text)| Value::Array(vec![Value::String(mark.clone()), Value::String(text.clone())]))
            .collect(),
    )
}

fn section_source(section: &IndexMap<String, Value>) -> Result<String> {
    match section.get("source") {
        None | Some(Value::Null) => Ok(String::new()),
        Some(Value::String(source)) if source.is_empty() => Ok(String::new()),
        Some(Value::String(source)) => Ok(source.clone()),
        Some(_) => Err(Error::option("Invalid section source (must be a string)")),
    }
}

fn crosstab_footnotes(crosstab: &Value) -> Vec<(String, String)> {
    let mut found = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let Some(crosstab) = crosstab.as_object() else {
        return found;
    };
    for key in ["row_field", "col_field", "measure_field"] {
        let Some(note) = crosstab.get(key).and_then(|field| field.get("footnote")).and_then(Value::as_object) else {
            continue;
        };
        let Some(mark) = note.get("mark").and_then(Value::as_str) else {
            continue;
        };
        if mark.is_empty() || !seen.insert(mark.to_string()) {
            continue;
        }
        found.push((
            mark.to_string(),
            note.get("text").and_then(Value::as_str).unwrap_or_default().to_string(),
        ));
    }
    found
}

fn item_footnotes(items: &[Value]) -> Vec<(String, String)> {
    let mut found = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for item in items {
        let Some(note) = item.get("footnote").and_then(Value::as_object) else {
            continue;
        };
        let Some(mark) = note.get("mark").and_then(Value::as_str) else {
            continue;
        };
        if mark.is_empty() || !seen.insert(mark.to_string()) {
            continue;
        }
        found.push((
            mark.to_string(),
            note.get("text").and_then(Value::as_str).unwrap_or_default().to_string(),
        ));
    }
    found
}

#[cfg(feature = "pdf")]
fn margin_value(value: Option<&Value>, default: &str) -> Result<String> {
    match value {
        None | Some(Value::Null) => Ok(default.to_string()),
        Some(Value::String(value)) if !value.trim().is_empty() => Ok(value.clone()),
        Some(Value::Int(value)) if *value >= 0 => Ok(format!("{value}in")),
        Some(Value::UInt(value)) => Ok(format!("{value}in")),
        Some(Value::Float(value)) if *value >= 0.0 => Ok(format!("{value}in")),
        Some(_) => Err(Error::option("Invalid page margin (expected a positive CSS length)")),
    }
}

fn prepare_sections(sections: &[IndexMap<String, Value>], _meta: &Meta) -> Result<(Value, Value)> {
    let mut built: Vec<Value> = Vec::new();
    for section in sections {
        let section_type = section.get("type").and_then(Value::as_str).unwrap_or("table");
        if matches!(section_type, "table" | "crosstab") {
            match section.get("data") {
                None | Some(Value::Null) => {}
                Some(Value::Array(_)) => {}
                Some(_) => {
                    return Err(Error::option(format!(
                        "Invalid {section_type} section data (must be a list of records)"
                    )))
                }
            }
        }
        match section_type {
            "table" => {
                let data = section.get("data").and_then(Value::as_array).cloned().unwrap_or_default();
                let layout_raw = match section.get("layout") {
                    None | Some(Value::Null) => IndexMap::new(),
                    Some(Value::Object(object)) => object.clone(),
                    Some(_) => return Err(Error::option("Invalid table section layout (must be an object)")),
                };
                let (dataset, layout) = build_report(&data, &layout_raw)?;
                let mut entry = IndexMap::new();
                entry.insert("type".to_string(), Value::String("table".to_string()));
                entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
                entry.insert("dataset".to_string(), dataset);
                entry.insert("layout".to_string(), layout);
                if let Some(empty_text) = section.get("empty_text").and_then(Value::as_str) {
                    if !empty_text.is_empty() {
                        entry.insert("empty_text".to_string(), Value::String(empty_text.to_string()));
                    }
                }
                built.push(Value::Object(entry));
            }
            "text" => {
                let paragraphs = match section.get("paragraphs") {
                    Some(value) => value.clone(),
                    None => match section.get("body") {
                        Some(body) if !body.is_null() => Value::Array(vec![body.clone()]),
                        _ => Value::Array(Vec::new()),
                    },
                };
                let Some(paragraphs) = paragraphs.as_array() else {
                    return Err(Error::option("Invalid text section (need paragraphs: [...])"));
                };
                if !paragraphs.iter().all(Value::is_string) {
                    return Err(Error::option("Invalid text section (need paragraphs: [...])"));
                }
                let mut entry = IndexMap::new();
                entry.insert("type".to_string(), Value::String("text".to_string()));
                entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
                entry.insert("paragraphs".to_string(), Value::Array(paragraphs.clone()));
                built.push(Value::Object(entry));
            }
            "kpi" => {
                let Some(raw_items) = section.get("items").and_then(Value::as_array) else {
                    return Err(Error::option("Invalid kpi section (need items: [...])"));
                };
                let mut items = Vec::new();
                for (index, raw) in raw_items.iter().enumerate() {
                    let Some(raw) = raw.as_object() else {
                        return Err(Error::option("Invalid kpi item (need at least a label)"));
                    };
                    if !raw.contains_key("label") {
                        return Err(Error::option("Invalid kpi item (need at least a label)"));
                    }
                    let mut item = raw.clone();
                    if let Some(note) = item.get("footnote").cloned() {
                        let note = normalize_footnote(&note, &format!("kpi item {}", index + 1))?;
                        item.insert("footnote".to_string(), note.to_value());
                    }
                    items.push(Value::Object(item));
                }
                let mut entry = IndexMap::new();
                entry.insert("type".to_string(), Value::String("kpi".to_string()));
                entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
                entry.insert("items".to_string(), Value::Array(items));
                built.push(Value::Object(entry));
            }
            "chart" => {
                let chart_spec = match section.get("chart") {
                    Some(Value::Object(object)) => object.clone(),
                    _ => IndexMap::new(),
                };
                let svg = build_chart(&chart_spec)?;
                let mut entry = IndexMap::new();
                entry.insert("type".to_string(), Value::String("chart".to_string()));
                let title = section
                    .get("title")
                    .filter(|value| value.truthy())
                    .or_else(|| chart_spec.get("title"))
                    .cloned()
                    .unwrap_or(Value::Null);
                entry.insert("title".to_string(), title);
                entry.insert("svg".to_string(), Value::String(svg));
                entry.insert("chart".to_string(), Value::Object(chart_spec));
                built.push(Value::Object(entry));
            }
            "crosstab" => {
                let spec = Value::Object(section.clone());
                let crosstab = build_crosstab(
                    section.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]),
                    &spec,
                )?;
                let mut entry = IndexMap::new();
                entry.insert("type".to_string(), Value::String("crosstab".to_string()));
                entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
                entry.insert("crosstab".to_string(), crosstab.to_value());
                built.push(Value::Object(entry));
            }
            "image" => {
                let src = normalize_image_src(section.get("src").unwrap_or(&Value::Null), "image section src")?;
                let alt = match section.get("alt") {
                    None | Some(Value::Null) => String::new(),
                    Some(Value::String(alt)) => alt.clone(),
                    Some(_) => return Err(Error::option("Invalid image section alt (must be a string)")),
                };
                let caption = match section.get("caption") {
                    None | Some(Value::Null) => String::new(),
                    Some(Value::String(caption)) => caption.clone(),
                    Some(_) => return Err(Error::option("Invalid image section caption (must be a string)")),
                };
                let width = match section.get("width") {
                    None | Some(Value::Null) => None,
                    Some(Value::Int(width)) if (16..=1600).contains(width) => Some(*width),
                    Some(Value::UInt(width)) if (16..=1600).contains(width) => Some(*width as i64),
                    Some(_) => return Err(Error::option("Invalid image section width (must be an integer 16..1600)")),
                };
                let align = section.get("align").and_then(Value::as_str).unwrap_or("center");
                if !matches!(align, "left" | "center" | "right") {
                    return Err(Error::option("Invalid image section align (expected left|center|right)"));
                }
                let mut entry = IndexMap::new();
                entry.insert("type".to_string(), Value::String("image".to_string()));
                entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
                entry.insert("src".to_string(), Value::String(src));
                entry.insert("alt".to_string(), Value::String(alt));
                entry.insert("caption".to_string(), Value::String(caption));
                entry.insert("width".to_string(), width.map(Value::Int).unwrap_or(Value::Null));
                entry.insert("align".to_string(), Value::String(align.to_string()));
                built.push(Value::Object(entry));
            }
            "toc" => {
                let mut entry = IndexMap::new();
                entry.insert("type".to_string(), Value::String("toc".to_string()));
                entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
                entry.insert("items".to_string(), Value::Array(Vec::new()));
                built.push(Value::Object(entry));
            }
            other => {
                let _ = other;
                return Err(Error::option(
                    "Unknown section type (expected table|text|kpi|chart|crosstab|image|toc)",
                ));
            }
        }
    }

    let mut anchors: Vec<Value> = Vec::new();
    let mut anchor_index = 0usize;
    for entry in &mut built {
        let Some(entry) = entry.as_object_mut() else {
            continue;
        };
        let has_title = entry.get("title").is_some_and(Value::truthy);
        let is_toc = entry.get("type").and_then(Value::as_str) == Some("toc");
        if has_title && !is_toc {
            anchor_index += 1;
            let anchor = format!("section-{anchor_index}");
            entry.insert("anchor".to_string(), Value::String(anchor.clone()));
            let mut item = IndexMap::new();
            item.insert("title".to_string(), entry.get("title").cloned().unwrap_or(Value::Null));
            item.insert("anchor".to_string(), Value::String(anchor));
            anchors.push(Value::Object(item));
        }
    }
    for entry in &mut built {
        let Some(entry) = entry.as_object_mut() else {
            continue;
        };
        if entry.get("type").and_then(Value::as_str) == Some("toc") {
            entry.insert("items".to_string(), Value::Array(anchors.clone()));
        }
    }
    for (entry, section) in built.iter_mut().zip(sections) {
        let source = section_source(section)?;
        if !source.is_empty() {
            if let Some(object) = entry.as_object_mut() {
                object.insert("source".to_string(), Value::String(source));
            }
        }
    }

    let mut layout_object = IndexMap::new();
    let mut header = IndexMap::new();
    header.insert("header".to_string(), Value::Array(Vec::new()));
    layout_object.insert("groups".to_string(), Value::Object(header));
    let mut layout = Value::Object(layout_object);
    assign_report_footnotes(&mut layout, Some(&mut built))?;

    for section in &mut built {
        let Some(object) = section.as_object_mut() else {
            continue;
        };
        let section_type = object.get("type").and_then(Value::as_str).unwrap_or("table").to_string();
        let footnotes = match section_type.as_str() {
            "table" => object.get("layout").map(collect_footnotes).unwrap_or_default(),
            "crosstab" => object.get("crosstab").map(crosstab_footnotes).unwrap_or_default(),
            "kpi" => object
                .get("items")
                .and_then(Value::as_array)
                .map(|items| item_footnotes(items))
                .unwrap_or_default(),
            _ => Vec::new(),
        };
        object.insert("footnotes".to_string(), footnotes_value(&footnotes));
    }

    let mut dataset = IndexMap::new();
    dataset.insert("sections".to_string(), Value::Array(built));
    Ok((Value::Object(dataset), layout))
}

/// Build (dataset, layout, meta) from a normalized payload (shared by all outputs).
///
/// ```
/// use isis_report_lib::{prepare_report, ReportService, Value};
/// use serde_json::json;
///
/// let payload = Value::from_json(json!({
///     "meta": {"title": "Sales"},
///     "data": [{"name": "Pen", "total": 12.5}]
/// }));
/// let prepared = prepare_report(&payload, None)?;
/// assert_eq!(prepared.meta.title(), Some("Sales"));
///
/// let service = ReportService::new();
/// let html = service.render_html(&payload)?;
/// assert!(html.contains("Sales"));
/// # Ok::<(), isis_report_lib::Error>(())
/// ```
pub fn prepare_report(payload: &Value, operator_limits: Option<Limits>) -> Result<PreparedReport> {
    let payload: Payload = normalize_payload(payload, operator_limits)?;
    if let Some(sections) = &payload.sections {
        let (dataset, layout) = prepare_sections(sections, &payload.meta)?;
        return Ok(PreparedReport {
            dataset,
            layout,
            meta: payload.meta,
        });
    }

    let data = &payload.data;
    let layout_raw = payload.layout.as_ref().filter(|layout| !layout.is_empty());
    let (mut dataset, mut layout) = if let Some(layout_raw) = layout_raw {
        build_report(data, layout_raw)?
    } else if is_template_format(data) {
        let layout = template_header_layout(data)?;
        let mut dataset = IndexMap::new();
        dataset.insert("groups".to_string(), Value::Array(data.clone()));
        dataset.insert("summary".to_string(), Value::Null);
        (Value::Object(dataset), layout)
    } else {
        let layout = infer_layout(data);
        let groups: Vec<Value> = data
            .iter()
            .map(|row| {
                let mut fields = IndexMap::new();
                if let Some(object) = row.as_object() {
                    for (key, value) in object {
                        fields.insert(key.clone(), value.clone());
                    }
                } else {
                    fields.insert("value".to_string(), row.clone());
                }
                let mut item = IndexMap::new();
                item.insert("fields".to_string(), Value::Object(fields));
                Value::Object(item)
            })
            .collect();
        let mut dataset = IndexMap::new();
        dataset.insert("groups".to_string(), Value::Array(groups));
        dataset.insert("summary".to_string(), Value::Null);
        (Value::Object(dataset), layout)
    };
    assign_report_footnotes(&mut layout, None)?;
    let footnotes = collect_footnotes(&layout);
    if let Some(object) = layout.as_object_mut() {
        object.insert("footnotes".to_string(), footnotes_value(&footnotes));
    }
    if let Some(object) = dataset.as_object_mut() {
        object.entry("summary".to_string()).or_insert(Value::Null);
    }
    Ok(PreparedReport {
        dataset,
        layout,
        meta: payload.meta,
    })
}

/// Default pipeline service.
#[derive(Debug, Clone)]
pub struct ReportService {
    /// Custom template directory.
    pub template_dir: Option<PathBuf>,
    /// Template name.
    pub template_name: String,
    /// Inline CSS (requires the `email` feature).
    pub inline_css: bool,
    /// Operator quotas.
    pub limits: Option<Limits>,
    /// Explicit PDF options. When `None`, `meta.page` drives the page format,
    /// orientation and margins (matching the Python service).
    #[cfg(feature = "pdf")]
    pub pdf_options: Option<PdfOptions>,
}

impl Default for ReportService {
    fn default() -> Self {
        Self {
            template_dir: None,
            template_name: "tabular.jinja".to_string(),
            inline_css: false,
            limits: None,
            #[cfg(feature = "pdf")]
            pdf_options: None,
        }
    }
}

impl ReportService {
    /// Create a service with defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Use a custom template directory.
    pub fn with_template_dir(mut self, directory: impl Into<PathBuf>) -> Self {
        self.template_dir = Some(directory.into());
        self
    }

    /// Select the template name.
    pub fn with_template_name(mut self, name: impl Into<String>) -> Self {
        self.template_name = name.into();
        self
    }

    /// Enable inline CSS. Requires the `email` feature.
    pub fn with_inline_css(mut self, inline_css: bool) -> Self {
        self.inline_css = inline_css;
        self
    }

    /// Apply operator quotas.
    pub fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = Some(limits);
        self
    }

    /// Override the PDF options resolved from `meta.page`.
    #[cfg(feature = "pdf")]
    pub fn with_pdf_options(mut self, options: PdfOptions) -> Self {
        self.pdf_options = Some(options);
        self
    }

    /// Resolve the effective PDF options: `meta.page` first, then explicit
    /// `pdf_options`, then the localized default footer.
    #[cfg(feature = "pdf")]
    pub fn resolve_pdf_options(&self, meta: &Meta) -> Result<PdfOptions> {
        // Python `_page_pdf_options` turns bookmarks on by default.
        let mut options = PdfOptions {
            outline: true,
            ..PdfOptions::default()
        };

        if let Some(page) = meta.page() {
            if let Some(size) = page.get("size") {
                let size = size
                    .as_str()
                    .ok_or_else(|| Error::option("Invalid page size (must be a string such as A4)"))?;
                options.format = size.parse::<PageFormat>().map_err(|error| Error::option(error.to_string()))?;
            }
            match page.get("orientation").and_then(Value::as_str) {
                None | Some("portrait") => {}
                Some("landscape") => options.landscape = true,
                Some(_) => return Err(Error::option("Invalid page orientation (expected portrait|landscape)")),
            }
            if let Some(margins) = page.get("margins") {
                let margins = margins
                    .as_object()
                    .ok_or_else(|| Error::option("Invalid page margins (must be an object)"))?;
                options.margin = Margins {
                    top: margin_value(margins.get("top"), ".15in")?,
                    bottom: margin_value(margins.get("bottom"), ".4in")?,
                    left: margin_value(margins.get("left"), ".15in")?,
                    right: margin_value(margins.get("right"), ".15in")?,
                };
            }
        }

        if let Some(explicit) = &self.pdf_options {
            options = explicit.clone();
        }

        if options.backend != PdfBackend::ExternalWeasyPrint && options.display_header_footer && options.footer_template.is_none() {
            options.footer_template = Some(crate::pdf_backend::default_footer(
                meta.printed_at_text().as_deref(),
                &meta.locale(),
            ));
        }
        if options.backend == PdfBackend::ExternalWeasyPrint && options.header_template.is_none() && options.footer_template.is_none() {
            // WeasyPrint has no Playwright header/footer templates.
            options.display_header_footer = false;
        }
        Ok(options)
    }

    /// Render HTML from an already prepared report, applying this service's
    /// template, inline-CSS and section-template settings.
    pub fn render_prepared_html(&self, prepared: &PreparedReport) -> Result<String> {
        let mut template_name = self.template_name.clone();
        if prepared.dataset.get("sections").is_some() && template_name == "tabular.jinja" {
            template_name = "sections.jinja".to_string();
        }
        render_report_html(
            &prepared.dataset,
            &prepared.layout,
            &prepared.meta.to_value(),
            &template_name,
            self.template_dir.as_deref(),
            self.inline_css,
        )
    }

    /// Generate a PDF synchronously with the resolved options.
    #[cfg(feature = "pdf")]
    pub fn generate_pdf(&self, payload: &Value) -> Result<Vec<u8>> {
        let prepared = self.prepare(payload)?;
        let options = self.resolve_pdf_options(&prepared.meta)?;
        self.generate_pdf_prepared(&prepared, &options)
    }

    /// Generate a PDF from an already prepared report.
    #[cfg(feature = "pdf")]
    pub fn generate_pdf_prepared(&self, prepared: &PreparedReport, options: &PdfOptions) -> Result<Vec<u8>> {
        let html = self.render_prepared_html(prepared)?;
        let options = options.clone();
        let outcome = std::thread::spawn(move || -> std::result::Result<Vec<u8>, String> {
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|error| format!("Cannot start the PDF runtime: {error}"))?;
            runtime
                .block_on(crate::pdf_backend::render_html_to_pdf(&html, &options))
                .map_err(|error| error.to_string())
        })
        .join()
        .map_err(|_| Error::pdf("PDF worker thread panicked"))?;
        outcome.map_err(Error::pdf)
    }

    /// Generate a PDF asynchronously with the resolved options.
    #[cfg(feature = "pdf")]
    pub async fn generate_pdf_async(&self, payload: &Value) -> Result<Vec<u8>> {
        let prepared = self.prepare(payload)?;
        let options = self.resolve_pdf_options(&prepared.meta)?;
        self.generate_pdf_prepared_async(&prepared, &options).await
    }

    /// Generate a PDF from an already prepared report without blocking.
    #[cfg(feature = "pdf")]
    pub async fn generate_pdf_prepared_async(&self, prepared: &PreparedReport, options: &PdfOptions) -> Result<Vec<u8>> {
        let html = self.render_prepared_html(prepared)?;
        crate::pdf_backend::render_html_to_pdf(&html, options)
            .await
            .map_err(|error| Error::pdf(error.to_string()))
    }

    /// Validate and shape a payload with this service's quotas.
    pub fn prepare(&self, payload: &Value) -> Result<PreparedReport> {
        prepare_report(payload, self.limits)
    }

    /// Render HTML with this service's template settings.
    pub fn render_html(&self, payload: &Value) -> Result<String> {
        let prepared = self.prepare(payload)?;
        self.render_prepared_html(&prepared)
    }
}

/// Python-compatible alias.
pub type TabularReportService = ReportService;

/// Convenience helper used by tests and embedders.
pub fn meta_value(meta: &Meta) -> Value {
    meta.to_value()
}

/// Convenience helper for callers that already have a `Crosstab`.
pub fn crosstab_value(crosstab: &Crosstab) -> Value {
    crosstab.to_value()
}

/// Validate a section source without building the section.
pub fn validate_section_source(section: &IndexMap<String, Value>) -> Result<String> {
    section_source(section)
}

/// Python-like text for diagnostics.
pub fn value_text(value: &Value) -> String {
    pyops::py_str(value)
}

/// Template directory validation used by the API layer.
pub fn validate_template_dir(directory: Option<&Path>) -> Result<Option<PathBuf>> {
    match directory {
        None => Ok(None),
        Some(directory) if directory.is_dir() => Ok(Some(directory.to_path_buf())),
        Some(directory) => Err(Error::TemplateDirNotFound(directory.to_path_buf())),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn value(value: serde_json::Value) -> Value {
        Value::from_json(value)
    }

    #[test]
    fn prepares_tabular_report() {
        let payload = value(json!({
            "meta": {"title": "Order", "mode": "exact"},
            "layout": {
                "company": {"label": "Company", "format_mask": "str", "alignment": "left"},
                "orders": {
                    "order": {"label": "Code", "format_mask": "int", "alignment": "right"},
                    "total": {"label": "Total", "format_mask": "float", "alignment": "right", "aggregate": "sum"}
                }
            },
            "data": [{"company": "ACME", "orders": [{"order": 750, "total": 4000}]}]
        }));
        let prepared = prepare_report(&payload, None).unwrap();
        assert!(prepared.dataset.get("groups").is_some());
        assert!(prepared.layout.get("footnotes").is_some());
        assert_eq!(prepared.meta.title(), Some("Order"));
    }

    #[test]
    fn prepares_sections_and_toc() {
        let payload = value(json!({
            "meta": {"title": "Board Pack"},
            "sections": [
                {"type": "toc", "title": "Contents"},
                {"type": "text", "title": "Intro", "paragraphs": ["Hello."]},
                {"type": "kpi", "title": "Totals", "items": [{"label": "Orders", "value": 42}]}
            ]
        }));
        let prepared = prepare_report(&payload, None).unwrap();
        let sections = prepared.dataset.get("sections").and_then(Value::as_array).unwrap();
        assert_eq!(sections.len(), 3);
        assert_eq!(sections[1].get("anchor").and_then(Value::as_str), Some("section-1"));
        let toc_items = sections[0].get("items").and_then(Value::as_array).unwrap();
        assert_eq!(toc_items.len(), 2);
    }

    #[test]
    fn renders_html_through_service() {
        let payload = value(json!({"meta": {"title": "T"}, "data": [{"a": 1}]}));
        let html = ReportService::new().render_html(&payload).unwrap();
        assert!(html.contains("T"));
        assert!(html.contains("1"));
    }

    #[test]
    fn quotas_apply_in_prepare() {
        let payload = value(json!({"meta": {"title": "T", "limits": {"max_rows": 1}}, "data": [{"a": 1}, {"a": 2}]}));
        assert!(prepare_report(&payload, None).is_err());
    }

    #[cfg(feature = "pdf")]
    #[test]
    fn resolves_pdf_page_options_from_meta() {
        let payload = value(json!({
            "meta": {
                "title": "T",
                "locale": "en-US",
                "printed_at": "2026-12-02 10:00",
                "page": {
                    "size": "Letter",
                    "orientation": "landscape",
                    "margins": {"top": "1cm", "bottom": ".5in", "left": "10mm", "right": "20px"}
                }
            },
            "data": [{"a": 1}]
        }));
        let prepared = prepare_report(&payload, None).unwrap();
        let options = ReportService::default().resolve_pdf_options(&prepared.meta).unwrap();
        assert_eq!(options.format, crate::pdf_backend::PageFormat::Letter);
        assert!(options.landscape);
        assert!(options.outline);
        assert_eq!(options.margin.top, "1cm");
        assert_eq!(options.margin.bottom, ".5in");
        assert_eq!(options.margin.left, "10mm");
        assert_eq!(options.margin.right, "20px");
        let footer = options.footer_template.unwrap();
        assert!(footer.contains("Printed on 2026-12-02 10:00"));
        assert!(footer.contains("Page"));
    }

    #[test]
    fn helpers_builders_and_section_errors() {
        let empty = IndexMap::new();
        assert_eq!(validate_section_source(&empty).unwrap(), "");
        let null = IndexMap::from([("source".to_string(), Value::Null)]);
        assert_eq!(validate_section_source(&null).unwrap(), "");
        let text = IndexMap::from([("source".to_string(), Value::String("x".into()))]);
        assert_eq!(validate_section_source(&text).unwrap(), "x");
        let bad = IndexMap::from([("source".to_string(), Value::Int(1))]);
        assert!(validate_section_source(&bad).is_err());

        let directory = tempfile::tempdir().unwrap();
        assert!(validate_template_dir(None).unwrap().is_none());
        assert_eq!(
            validate_template_dir(Some(directory.path())).unwrap().as_deref(),
            Some(directory.path())
        );
        assert!(validate_template_dir(Some(&directory.path().join("missing"))).is_err());

        let limits = Limits {
            max_rows: Some(2),
            max_bytes: Some(3),
        };
        let service = ReportService::new()
            .with_template_dir(directory.path())
            .with_template_name("custom.jinja")
            .with_inline_css(true)
            .with_limits(limits);
        assert_eq!(service.template_name, "custom.jinja");
        assert_eq!(service.template_dir.as_deref(), Some(directory.path()));
        assert!(service.inline_css);
        assert_eq!(service.limits, Some(limits));
        #[cfg(feature = "pdf")]
        {
            let service = service.with_pdf_options(PdfOptions::default());
            assert!(service.pdf_options.is_some());
        }

        assert_eq!(value_text(&Value::Null), "None");
        let meta = normalize_payload(&value(json!({"meta": {"title": "T"}, "data": []})), None)
            .unwrap()
            .meta;
        assert_eq!(meta_value(&meta).get("title").and_then(Value::as_str), Some("T"));
        let crosstab = build_crosstab(
            &[value(json!({"r": "a", "c": "b", "v": 1}))],
            &value(json!({"rows": "r", "columns": "c", "measure": "v"})),
        )
        .unwrap();
        assert!(crosstab_value(&crosstab).get("row_headers").is_some());

        for payload in [
            json!({"meta": {"title": "T"}, "sections": [{"type": "text", "paragraphs": "x"}]}),
            json!({"meta": {"title": "T"}, "sections": [{"type": "text", "paragraphs": [1]}]}),
            json!({"meta": {"title": "T"}, "sections": [{"type": "text", "body": 1}]}),
            json!({"meta": {"title": "T"}, "sections": [{"type": "kpi", "items": [{"value": 1}]}]}),
            json!({"meta": {"title": "T"}, "sections": [{"type": "kpi", "items": "x"}]}),
            json!({"meta": {"title": "T"}, "sections": [{"type": "table", "layout": 1, "data": []}]}),
            json!({"meta": {"title": "T"}, "sections": [{"type": "unknown"}]}),
            json!({"meta": {"title": "T"}, "sections": [{"type": "table", "source": 1, "data": []}]}),
        ] {
            assert!(
                prepare_report(&value(payload), Some(Limits::none())).is_err(),
                "accepted invalid section"
            );
        }

        let text_body = value(json!({
            "meta": {"title": "T"},
            "sections": [{"type": "text", "title": "Body", "body": "Plain body"}]
        }));
        let prepared = prepare_report(&text_body, Some(Limits::none())).unwrap();
        let sections = prepared.dataset.get("sections").and_then(Value::as_array).unwrap();
        let paragraphs = sections[0].get("paragraphs").and_then(Value::as_array).unwrap();
        assert_eq!(paragraphs[0].as_str(), Some("Plain body"));

        let empty_text = value(json!({
            "meta": {"title": "T"},
            "sections": [{"type": "table", "title": "Empty", "data": [], "empty_text": "No rows"}]
        }));
        let prepared = prepare_report(&empty_text, Some(Limits::none())).unwrap();
        let sections = prepared.dataset.get("sections").and_then(Value::as_array).unwrap();
        assert_eq!(sections[0].get("empty_text").and_then(Value::as_str), Some("No rows"));
    }

    #[cfg(feature = "pdf")]
    #[test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    fn service_pdf_paths_generate_real_pdfs() {
        let payload = value(json!({"meta": {"title": "Service PDF"}, "data": [{"a": 1}]}));
        let service = ReportService::new();
        let pdf = service.generate_pdf(&payload).unwrap();
        assert!(pdf.starts_with(b"%PDF-"));

        let prepared = service.prepare(&payload).unwrap();
        let options = service.resolve_pdf_options(&prepared.meta).unwrap();
        let pdf = service.generate_pdf_prepared(&prepared, &options).unwrap();
        assert!(pdf.starts_with(b"%PDF-"));

        let pdf = futures::executor::block_on(service.generate_pdf_async(&payload)).unwrap();
        assert!(pdf.starts_with(b"%PDF-"));
        let pdf = futures::executor::block_on(service.generate_pdf_prepared_async(&prepared, &options)).unwrap();
        assert!(pdf.starts_with(b"%PDF-"));
        crate::pdf_backend::shutdown_pdf_pool();
    }
}