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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! Payload envelope validation, metadata defaults and operator quotas.
//!
//! The envelope is validated against the same contract as the Python library:
//! unknown top-level/meta keys and mistyped values fail closed, before any
//! shaping or rendering. Error messages name fields and shapes, never payload
//! values.

use std::fmt;

use chrono::Local;
use indexmap::IndexMap;

use crate::error::{Error, Result};
use crate::media::{normalize_image_src, normalize_watermark};
use crate::pyops;
use crate::value::Value;

/// Default operator quota: 1,000,000 records.
pub const DEFAULT_MAX_ROWS: usize = 1_000_000;
/// Default operator quota: 64 MiB.
pub const DEFAULT_MAX_BYTES: usize = 64 * 1024 * 1024;

const LIMIT_KEYS: [&str; 2] = ["max_rows", "max_bytes"];
const META_KEYS: [&str; 16] = [
    "title",
    "sub_title",
    "company",
    "mode",
    "page",
    "locale",
    "direction",
    "currency",
    "accent_color",
    "logo",
    "watermark",
    "printed_at",
    "summary_side",
    "source_note",
    "empty_text",
    "limits",
];

/// Operator/payload quota caps.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Limits {
    /// Maximum number of data rows, when set.
    pub max_rows: Option<usize>,
    /// Maximum serialized payload size in bytes, when set.
    pub max_bytes: Option<usize>,
}

impl Limits {
    /// Built-in safe defaults.
    pub fn defaults() -> Self {
        Self {
            max_rows: Some(DEFAULT_MAX_ROWS),
            max_bytes: Some(DEFAULT_MAX_BYTES),
        }
    }

    /// Disable both caps.
    pub fn none() -> Self {
        Self::default()
    }

    /// Return `true` when both caps are disabled.
    pub fn is_empty(&self) -> bool {
        self.max_rows.is_none() && self.max_bytes.is_none()
    }

    /// Payload caps may only tighten the operator caps (or add one when the
    /// operator disabled that dimension).
    pub fn tightened_with(self, other: Limits) -> Self {
        Self {
            max_rows: merge_limit(self.max_rows, other.max_rows),
            max_bytes: merge_limit(self.max_bytes, other.max_bytes),
        }
    }

    /// Encode as the payload `limits` object.
    pub fn to_value(self) -> Value {
        let mut object = IndexMap::new();
        if let Some(value) = self.max_rows {
            object.insert("max_rows".to_string(), Value::UInt(value as u64));
        }
        if let Some(value) = self.max_bytes {
            object.insert("max_bytes".to_string(), Value::UInt(value as u64));
        }
        Value::Object(object)
    }
}

fn merge_limit(left: Option<usize>, right: Option<usize>) -> Option<usize> {
    match (left, right) {
        (Some(left), Some(right)) => Some(left.min(right)),
        (Some(value), None) | (None, Some(value)) => Some(value),
        (None, None) => None,
    }
}

/// Report metadata (normalized, insertion order preserved).
#[derive(Debug, Clone, Default)]
pub struct Meta {
    object: IndexMap<String, Value>,
}

impl Meta {
    /// Create empty metadata.
    pub fn new() -> Self {
        Self::default()
    }

    /// Wrap an existing metadata map.
    pub fn from_object(object: IndexMap<String, Value>) -> Self {
        Self { object }
    }

    /// Borrow the underlying map.
    pub fn as_object(&self) -> &IndexMap<String, Value> {
        &self.object
    }

    /// Clone into a [`Value::Object`].
    pub fn to_value(&self) -> Value {
        Value::Object(self.object.clone())
    }

    /// Look up a metadata key.
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.object.get(key)
    }

    /// Insert or replace a metadata key.
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<Value>) {
        self.object.insert(key.into(), value.into());
    }

    /// Chainable [`set`](Self::set) for any metadata key.
    pub fn with_meta(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.set(key, value);
        self
    }

    /// Chainable title setter.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.set("title", title.into());
        self
    }

    /// Chainable subtitle setter (payload key `sub_title`).
    pub fn with_subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.set("sub_title", subtitle.into());
        self
    }

    /// Chainable company setter.
    pub fn with_company(mut self, company: impl Into<String>) -> Self {
        self.set("company", company.into());
        self
    }

    /// Chainable locale setter.
    pub fn with_locale(mut self, locale: impl Into<String>) -> Self {
        self.set("locale", locale.into());
        self
    }

    /// Chainable currency setter.
    pub fn with_currency(mut self, currency: impl Into<String>) -> Self {
        self.set("currency", currency.into());
        self
    }

    /// Chainable text direction setter (`ltr` or `rtl`).
    pub fn with_direction(mut self, direction: impl Into<String>) -> Self {
        self.set("direction", direction.into());
        self
    }

    /// Chainable accent color setter.
    pub fn with_accent_color(mut self, accent_color: impl Into<String>) -> Self {
        self.set("accent_color", accent_color.into());
        self
    }

    /// Chainable source note setter.
    pub fn with_source_note(mut self, source_note: impl Into<String>) -> Self {
        self.set("source_note", source_note.into());
        self
    }

    /// Report title.
    pub fn title(&self) -> Option<&str> {
        self.get("title").and_then(Value::as_str)
    }

    /// Report subtitle (`sub_title`).
    pub fn sub_title(&self) -> Option<&str> {
        self.get("sub_title").and_then(Value::as_str)
    }

    /// Company shown in the header.
    pub fn company(&self) -> Option<&str> {
        self.get("company").and_then(Value::as_str)
    }

    /// Rendering mode.
    pub fn mode(&self) -> Option<&str> {
        self.get("mode").and_then(Value::as_str)
    }

    /// BCP-47 locale (`pt-BR` when absent).
    pub fn locale(&self) -> String {
        self.get("locale").and_then(Value::as_str).unwrap_or("pt-BR").to_string()
    }

    /// Text direction (`ltr` when absent).
    pub fn direction(&self) -> &str {
        self.get("direction").and_then(Value::as_str).unwrap_or("ltr")
    }

    /// Default currency code.
    pub fn currency(&self) -> Option<&str> {
        self.get("currency").and_then(Value::as_str)
    }

    /// Header accent color.
    pub fn accent_color(&self) -> Option<&str> {
        self.get("accent_color").and_then(Value::as_str)
    }

    /// Logo path or data URI.
    pub fn logo(&self) -> Option<&str> {
        self.get("logo").and_then(Value::as_str)
    }

    /// Watermark value when present and non-null.
    pub fn watermark(&self) -> Option<&Value> {
        self.get("watermark").filter(|value| !value.is_null())
    }

    /// Page settings object.
    pub fn page(&self) -> Option<&IndexMap<String, Value>> {
        self.get("page").and_then(Value::as_object)
    }

    /// Printable `printed_at` text.
    pub fn printed_at_text(&self) -> Option<String> {
        self.get("printed_at").filter(|value| !value.is_null()).map(pyops::py_str)
    }

    /// Summary block side (`left`/`right`).
    pub fn summary_side(&self) -> Option<&str> {
        self.get("summary_side").and_then(Value::as_str)
    }

    /// Source note shown in the footer.
    pub fn source_note(&self) -> Option<&str> {
        self.get("source_note").and_then(Value::as_str)
    }

    /// Text shown for empty tables.
    pub fn empty_text(&self) -> Option<&Value> {
        self.get("empty_text")
    }

    /// Payload quotas, when valid.
    pub fn limits(&self) -> Option<Limits> {
        self.get("limits")
            .filter(|value| !value.is_null())
            .and_then(|value| normalize_limits(value).ok())
    }
}

/// A validated payload ready for shaping.
#[derive(Debug, Clone)]
pub struct Payload {
    /// Original payload value.
    pub raw: Value,
    /// Normalized metadata.
    pub meta: Meta,
    /// Layout object, when provided.
    pub layout: Option<IndexMap<String, Value>>,
    /// Validated data rows.
    pub data: Vec<Value>,
    /// `None` means the key was absent; `Some` means it was present (possibly
    /// null or empty), which switches the pipeline to composed sections.
    pub sections: Option<Vec<IndexMap<String, Value>>>,
    /// Quotas declared inside the payload.
    pub payload_limits: Option<Limits>,
}

#[derive(Default)]
struct Problems {
    messages: Vec<String>,
    total: usize,
}

impl Problems {
    fn push(&mut self, path: &str, message: &str) {
        self.total += 1;
        if self.messages.len() < 3 {
            self.messages.push(format!("{path}: {message}"));
        }
    }

    fn finish(self) -> Result<()> {
        if self.total == 0 {
            return Ok(());
        }
        let more = if self.total > 3 {
            format!(" (+{} more)", self.total - 3)
        } else {
            String::new()
        };
        let problems = if self.total == 1 { "problem" } else { "problems" };
        Err(Error::payload(format!(
            "Invalid payload ({} {problems}): {}{more}",
            self.total,
            self.messages.join("; ")
        )))
    }
}

/// Human-readable value type used in validation messages.
pub fn type_name(value: &Value) -> &'static str {
    match value {
        Value::Null => "NoneType",
        Value::Bool(_) => "bool",
        Value::Int(_) | Value::UInt(_) => "int",
        Value::Float(_) => "float",
        Value::Decimal(_) => "Decimal",
        Value::String(_) => "str",
        Value::Date(_) => "date",
        Value::DateTime(_) => "datetime",
        Value::Array(_) => "list",
        Value::Object(_) => "dict",
    }
}

fn is_string_or_null(value: &Value) -> bool {
    matches!(value, Value::String(_) | Value::Null)
}

fn validate_meta(meta: &Value, problems: &mut Problems) {
    if meta.is_null() {
        return;
    }
    let Some(object) = meta.as_object() else {
        problems.push("meta", "Input should be a valid dictionary or instance of MetaInfo");
        return;
    };
    for (key, value) in object {
        if !META_KEYS.contains(&key.as_str()) {
            problems.push(&format!("meta.{key}"), "Extra inputs are not permitted");
            continue;
        }
        let string_field = matches!(
            key.as_str(),
            "title" | "sub_title" | "company" | "mode" | "locale" | "currency" | "accent_color" | "logo"
        );
        if key == "mode" && value.is_null() {
            problems.push("meta.mode", "Input should be a valid string");
        } else if string_field && !is_string_or_null(value) {
            problems.push(&format!("meta.{key}"), "Input should be a valid string");
        }
        match key.as_str() {
            "page" if !value.is_null() && !value.is_object() => {
                problems.push("meta.page", "Input should be a valid dictionary");
            }
            "direction" if !value.is_null() => match value.as_str() {
                Some("ltr" | "rtl") => {}
                _ => problems.push("meta.direction", "Input should be 'ltr' or 'rtl'"),
            },
            _ => {}
        }
    }
}

/// Validate the top-level envelope against the ReportPayload model.
pub fn validate_payload_shape(payload: &Value) -> Result<()> {
    let Some(object) = payload.as_object() else {
        return Err(Error::payload(format!(
            "Invalid payload (must be an object): {}",
            type_name(payload)
        )));
    };
    let mut problems = Problems::default();
    for key in object.keys() {
        if !matches!(key.as_str(), "meta" | "layout" | "data" | "sections") {
            problems.push(key, "Extra inputs are not permitted");
        }
    }
    if let Some(meta) = object.get("meta") {
        validate_meta(meta, &mut problems);
    }
    if let Some(layout) = object.get("layout") {
        if !layout.is_null() && !layout.is_object() {
            problems.push("layout", "Input should be a valid dictionary");
        }
    }
    if let Some(data) = object.get("data") {
        if !data.is_array() {
            problems.push("data", "Input should be a valid list");
        }
    }
    if let Some(sections) = object.get("sections") {
        if !sections.is_null() {
            match sections {
                Value::Array(items) => {
                    for (index, item) in items.iter().enumerate() {
                        if !item.is_object() {
                            problems.push(&format!("sections.{index}"), "Input should be a valid dictionary");
                        }
                    }
                }
                _ => problems.push("sections", "Input should be a valid list"),
            }
        }
    }
    problems.finish()
}

/// Fill display metadata the payload did not provide (print timestamp,
/// direction) and normalize logo/watermark/limits.
pub fn with_meta_defaults(meta: Option<&Value>) -> Result<Meta> {
    let mut object = match meta {
        Some(Value::Object(object)) => object.clone(),
        Some(Value::Null) | None => IndexMap::new(),
        Some(_) => {
            return Err(Error::payload(
                "Invalid payload (1 problem): meta: Input should be a valid dictionary or instance of MetaInfo",
            ))
        }
    };

    let printed_at_missing = object.get("printed_at").map(|value| !value.truthy()).unwrap_or(true);
    if printed_at_missing {
        object.insert(
            "printed_at".to_string(),
            Value::String(Local::now().format("%Y-%m-%d %H:%M").to_string()),
        );
    }

    let direction_missing = object.get("direction").map(|value| !value.truthy()).unwrap_or(true);
    if direction_missing {
        object.insert("direction".to_string(), Value::String("ltr".to_string()));
    }

    if let Some(source_note) = object.get("source_note") {
        if !source_note.is_null() {
            match source_note.as_str() {
                Some(text) if !text.is_empty() => {}
                _ => return Err(Error::option("Invalid meta.source_note (must be a non-empty string)")),
            }
        }
    }

    if let Some(summary_side) = object.get("summary_side") {
        if !summary_side.is_null() && !matches!(summary_side.as_str(), Some("top" | "bottom")) {
            return Err(Error::option("Invalid meta.summary_side (expected top|bottom)"));
        }
    }

    if let Some(logo) = object.get("logo").cloned() {
        if !logo.is_null() {
            let normalized = normalize_image_src(&logo, "meta.logo")?;
            object.insert("logo".to_string(), Value::String(normalized));
        }
    }

    if let Some(watermark) = object.get("watermark").cloned() {
        if !watermark.is_null() {
            let normalized = normalize_watermark(&watermark)?;
            if let Some(watermark) = normalized {
                object.insert("watermark".to_string(), watermark.to_value());
            }
        }
    }

    if let Some(limits) = object.get("limits").cloned() {
        if !limits.is_null() {
            let normalized = normalize_limits(&limits)?;
            object.insert("limits".to_string(), normalized.to_value());
        }
    }

    Ok(Meta::from_object(object))
}

/// Validate and normalize a limits object.
pub fn normalize_limits(value: &Value) -> Result<Limits> {
    let Some(object) = value.as_object() else {
        return Err(Error::option("Invalid meta.limits (must be an object)"));
    };
    for key in object.keys() {
        if !LIMIT_KEYS.contains(&key.as_str()) {
            return Err(Error::option("Unknown meta.limits key (expected max_rows|max_bytes)"));
        }
    }
    let mut limits = Limits::none();
    for key in LIMIT_KEYS {
        let Some(value) = object.get(key) else {
            continue;
        };
        if value.is_null() {
            continue;
        }
        let number = match value {
            Value::Int(value) if *value >= 1 => *value as usize,
            Value::UInt(value) if *value >= 1 => {
                usize::try_from(*value).map_err(|_| Error::option(format!("Invalid meta.limits.{key} (must be a positive integer)")))?
            }
            _ => return Err(Error::option(format!("Invalid meta.limits.{key} (must be a positive integer)"))),
        };
        match key {
            "max_rows" => limits.max_rows = Some(number),
            "max_bytes" => limits.max_bytes = Some(number),
            _ => {}
        }
    }
    Ok(limits)
}

fn count_data_records(value: &Value) -> usize {
    let mut count = 0usize;
    let mut stack: Vec<&Value> = vec![value];
    while let Some(node) = stack.pop() {
        match node {
            Value::Array(values) => stack.extend(values.iter()),
            Value::Object(values) => {
                count += 1;
                stack.extend(values.values());
            }
            _ => {}
        }
    }
    count
}

fn count_payload_records(payload: &Value) -> usize {
    let Some(object) = payload.as_object() else {
        return 0;
    };
    if object.contains_key("sections") {
        let Some(sections) = object.get("sections").and_then(Value::as_array) else {
            return 0;
        };
        let mut total = 0usize;
        for section in sections {
            let Some(section) = section.as_object() else {
                continue;
            };
            let section_type = section.get("type").and_then(Value::as_str).unwrap_or("table");
            match section_type {
                "table" | "crosstab" => {
                    total += section.get("data").map(count_data_records).unwrap_or_default();
                }
                "kpi" => {
                    total += section.get("items").map(count_data_records).unwrap_or_default();
                }
                _ => {}
            }
        }
        return total;
    }
    object.get("data").map(count_data_records).unwrap_or_default()
}

/// Enforce the effective quotas before any expensive shaping.
pub fn check_quotas(payload: &Value, limits: Limits) -> Result<()> {
    if limits.is_empty() {
        return Ok(());
    }
    if let Some(max_bytes) = limits.max_bytes {
        let bytes = serde_json::to_vec(&payload.to_json())
            .map_err(|error| Error::payload(format!("Payload is nested too deeply to measure its size: {error}")))?;
        if bytes.len() > max_bytes {
            return Err(Error::option(format!(
                "Payload is {} bytes, exceeding the max_bytes limit ({max_bytes})",
                bytes.len()
            )));
        }
    }
    if let Some(max_rows) = limits.max_rows {
        let total = count_payload_records(payload);
        if total > max_rows {
            return Err(Error::option(format!(
                "Payload has {total} data records, exceeding the max_rows limit ({max_rows})"
            )));
        }
    }
    Ok(())
}

/// Validate and normalize a payload. `operator_limits = None` applies the
/// default operator caps; `Some(Limits::none())` disables them.
pub fn normalize_payload(payload: &Value, operator_limits: Option<Limits>) -> Result<Payload> {
    validate_payload_shape(payload)?;
    let object = payload.as_object().expect("validated object");
    let meta = with_meta_defaults(object.get("meta"))?;
    let payload_limits = meta.limits();
    let operator = operator_limits.unwrap_or_else(Limits::defaults);
    let effective = operator.tightened_with(payload_limits.unwrap_or_default());
    check_quotas(payload, effective)?;

    let layout = object.get("layout").and_then(Value::as_object).cloned();
    let data = object.get("data").and_then(Value::as_array).cloned().unwrap_or_default();
    let sections = if object.contains_key("sections") {
        Some(
            object
                .get("sections")
                .and_then(Value::as_array)
                .cloned()
                .unwrap_or_default()
                .into_iter()
                .filter_map(|section| section.as_object().cloned())
                .collect(),
        )
    } else {
        None
    };
    Ok(Payload {
        raw: payload.clone(),
        meta,
        layout,
        data,
        sections,
        payload_limits,
    })
}

impl fmt::Display for Limits {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "Limits {{ max_rows: {:?}, max_bytes: {:?} }}",
            self.max_rows, self.max_bytes
        )
    }
}

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

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

    #[test]
    fn rejects_unknown_top_level_keys() {
        let error = normalize_payload(&value(json!({"meta": {"title": "T"}, "data": [], "bogus": 1})), None).unwrap_err();
        assert!(error.to_string().contains("Invalid payload"));
        assert!(error.to_string().contains("bogus"));
    }

    #[test]
    fn rejects_unknown_meta_keys_and_mistyped_values() {
        let error = normalize_payload(&value(json!({"meta": {"title": "T", "bogus": 1}, "data": []})), None).unwrap_err();
        assert!(error.to_string().contains("meta.bogus"));
        let error = normalize_payload(&value(json!({"meta": {"title": 123}, "data": []})), None).unwrap_err();
        assert!(error.to_string().contains("meta.title"));
    }

    #[test]
    fn fills_printed_at_and_direction() {
        let payload = normalize_payload(&value(json!({"meta": {"title": "T"}, "data": []})), None).unwrap();
        assert!(payload.meta.get("printed_at").is_some());
        assert_eq!(payload.meta.direction(), "ltr");
    }

    #[test]
    fn quotas_only_tighten() {
        let payload = value(json!({
            "meta": {"title": "T", "limits": {"max_rows": 100}},
            "data": [{"a": 1}, {"a": 2}]
        }));
        let error = normalize_payload(
            &payload,
            Some(Limits {
                max_rows: Some(1),
                max_bytes: None,
            }),
        )
        .unwrap_err();
        assert!(error.to_string().contains("max_rows limit (1)"));
    }

    #[test]
    fn counts_nested_records() {
        let payload = value(json!({"meta": {"title": "T"}, "data": [{"g": "x", "items": [{"a": 1}, {"a": 2}]}]}));
        let error = normalize_payload(
            &payload,
            Some(Limits {
                max_rows: Some(2),
                max_bytes: None,
            }),
        )
        .unwrap_err();
        assert!(error.to_string().contains("3 data records"));
    }

    #[test]
    fn sections_switch_the_pipeline() {
        let payload = normalize_payload(&value(json!({"meta": {"title": "T"}, "sections": []})), None).unwrap();
        assert!(payload.sections.is_some());
        assert!(payload.data.is_empty());
    }

    #[test]
    fn invalid_limits_fail_closed() {
        for limits in [
            json!("10"),
            json!([10]),
            json!({"max_rows": 0}),
            json!({"max_rows": -1}),
            json!({"max_rows": 1.5}),
            json!({"max_rows": true}),
            json!({"max_row": 5}),
        ] {
            let payload = value(json!({"meta": {"title": "T", "limits": limits}, "data": []}));
            assert!(normalize_payload(&payload, None).is_err());
        }
    }

    #[test]
    fn meta_accessors_limits_and_type_names() {
        use chrono::{FixedOffset, NaiveDate};
        use rust_decimal::Decimal;

        let png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lK3Q6wAAAABJRU5ErkJggg==";
        let payload = value(json!({
            "meta": {
                "title": "T",
                "sub_title": "S",
                "company": "C",
                "mode": "exact",
                "page": {"orientation": "landscape"},
                "locale": "en-US",
                "direction": "rtl",
                "currency": "USD",
                "accent_color": "#112233",
                "logo": png,
                "watermark": {"text": "Draft"},
                "printed_at": "2024-01-01 10:00",
                "summary_side": "top",
                "source_note": "Source",
                "empty_text": "Empty",
                "limits": {"max_rows": 3, "max_bytes": 100000}
            },
            "data": []
        }));
        let normalized = normalize_payload(&payload, Some(Limits::none())).unwrap();
        let meta = &normalized.meta;
        assert_eq!(meta.title(), Some("T"));
        assert_eq!(meta.sub_title(), Some("S"));
        assert_eq!(meta.company(), Some("C"));
        assert_eq!(meta.mode(), Some("exact"));
        assert_eq!(meta.locale(), "en-US");
        assert_eq!(meta.direction(), "rtl");
        assert_eq!(meta.currency(), Some("USD"));
        assert_eq!(meta.accent_color(), Some("#112233"));
        assert_eq!(meta.logo(), Some(png));
        assert!(meta.watermark().is_some());
        assert!(meta.page().is_some());
        assert_eq!(meta.printed_at_text().as_deref(), Some("2024-01-01 10:00"));
        assert_eq!(meta.summary_side(), Some("top"));
        assert_eq!(meta.source_note(), Some("Source"));
        assert_eq!(meta.empty_text().and_then(Value::as_str), Some("Empty"));
        assert_eq!(meta.limits().and_then(|limits| limits.max_rows), Some(3));
        assert!(!meta.as_object().is_empty());

        let mut meta = meta.clone();
        meta.set("note", "x");
        assert_eq!(meta.get("note").and_then(Value::as_str), Some("x"));

        let limits = Limits {
            max_rows: Some(1),
            max_bytes: Some(2),
        };
        assert_eq!(limits.to_value().to_json(), json!({"max_rows": 1, "max_bytes": 2}));
        assert!(limits.to_string().contains("max_rows: Some(1)"));

        let cases = [
            (Value::Null, "NoneType"),
            (Value::Bool(true), "bool"),
            (Value::Int(1), "int"),
            (Value::UInt(1), "int"),
            (Value::Float(1.0), "float"),
            (Value::Decimal(Decimal::new(1, 0)), "Decimal"),
            (Value::String("x".into()), "str"),
            (Value::Date(NaiveDate::from_ymd_opt(2024, 1, 1).unwrap()), "date"),
            (
                Value::DateTime(chrono::DateTime::<FixedOffset>::parse_from_rfc3339("2024-01-01T00:00:00+00:00").unwrap()),
                "datetime",
            ),
            (Value::Array(vec![]), "list"),
            (Value::Object(IndexMap::new()), "dict"),
        ];
        for (value, expected) in cases {
            assert_eq!(type_name(&value), expected);
        }
    }

    #[test]
    fn validates_shapes_limits_and_quota_errors() {
        assert!(validate_payload_shape(&value(json!([])))
            .unwrap_err()
            .to_string()
            .contains("must be an object"));
        assert!(with_meta_defaults(Some(&value(json!(1)))).is_err());

        for bad in [
            json!({"meta": "x", "data": []}),
            json!({"meta": {"mode": null}, "data": []}),
            json!({"meta": {"page": 1}, "data": []}),
            json!({"meta": {"direction": "up"}, "data": []}),
            json!({"layout": 1, "data": []}),
            json!({"meta": {}, "data": 1}),
            json!({"meta": {}, "sections": "x"}),
            json!({"meta": {}, "sections": [1]}),
            json!({"meta": {}, "extra": 1}),
        ] {
            assert!(
                normalize_payload(&value(bad), Some(Limits::none())).is_err(),
                "accepted invalid payload"
            );
        }

        let many = value(json!({"meta": {}, "a": 1, "b": 2, "c": 3, "d": 4}));
        assert!(validate_payload_shape(&many).unwrap_err().to_string().contains("(+1 more)"));

        assert_eq!(
            normalize_limits(&value(json!({"max_rows": 3, "max_bytes": 4}))).unwrap(),
            Limits {
                max_rows: Some(3),
                max_bytes: Some(4)
            }
        );
        assert!(normalize_limits(&value(json!({"max_rows": null}))).unwrap().is_empty());
        assert!(normalize_limits(&value(json!({"bogus": 1}))).is_err());
        assert!(normalize_limits(&value(json!({"max_rows": 1.5}))).is_err());

        let payload = value(json!({"meta": {"title": "T"}, "data": []}));
        let error = check_quotas(
            &payload,
            Limits {
                max_rows: None,
                max_bytes: Some(1),
            },
        )
        .unwrap_err();
        assert!(error.to_string().contains("max_bytes limit"));
    }
}