weave-content 0.2.6

Content DSL parser, validator, and builder for OSINT case files
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
use std::fmt;

use crate::parser::{ParseError, SectionKind};

/// Maximum entities per file.
const MAX_ENTITIES_PER_FILE: usize = 50;

/// Maximum length of an entity name.
const MAX_NAME_LEN: usize = 300;

/// Label derived from the section an entity appears in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Label {
    Actor,
    Institution,
    PublicRecord,
}

impl fmt::Display for Label {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Actor => write!(f, "actor"),
            Self::Institution => write!(f, "institution"),
            Self::PublicRecord => write!(f, "public_record"),
        }
    }
}

impl Label {
    pub fn from_section(kind: SectionKind) -> Option<Self> {
        match kind {
            SectionKind::Actors => Some(Self::Actor),
            SectionKind::Institutions => Some(Self::Institution),
            SectionKind::Events => Some(Self::PublicRecord),
            _ => None,
        }
    }
}

/// A parsed entity with its name, label, and field map.
#[derive(Debug, Clone)]
pub struct Entity {
    pub name: String,
    pub label: Label,
    pub fields: Vec<(String, FieldValue)>,
    /// Stored NULID from `- id:` field (None if not yet generated).
    pub id: Option<String>,
    /// Line number (1-indexed) of the H3 heading.
    pub line: usize,
}

/// A field value: either a single string or a list of strings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldValue {
    Single(String),
    List(Vec<String>),
}

/// Parse a single entity from a standalone entity file body.
/// The body is the text after the H1 heading (bullet fields, no H3 headings).
/// `label` is determined by the file's directory (actors/ or institutions/).
/// `id` comes from the front matter (may be None).
pub fn parse_entity_file_body(
    name: &str,
    body: &str,
    label: Label,
    id: Option<String>,
    title_line: usize,
    errors: &mut Vec<ParseError>,
) -> Entity {
    let section_kind = match label {
        Label::Actor => SectionKind::Actors,
        Label::Institution => SectionKind::Institutions,
        Label::PublicRecord => SectionKind::Events,
    };

    // Wrap the body with a fake H3 heading so we can reuse parse_entities
    let wrapped = format!("### {name}\n{body}");
    let mut entities = parse_entities(&wrapped, section_kind, title_line.saturating_sub(1), errors);

    if let Some(mut entity) = entities.pop() {
        entity.id = id;
        entity.line = title_line;
        entity
    } else {
        Entity {
            name: name.to_string(),
            label,
            fields: Vec::new(),
            id,
            line: title_line,
        }
    }
}

/// Parse entities from an entity section (Actors, Institutions, Events).
/// The `body` is the text between the H2 heading and the next H2 heading.
/// `section_start_line` is the line number of the H2 heading in the original file.
#[allow(clippy::too_many_lines)]
pub fn parse_entities(
    body: &str,
    section_kind: SectionKind,
    section_start_line: usize,
    errors: &mut Vec<ParseError>,
) -> Vec<Entity> {
    let Some(label) = Label::from_section(section_kind) else {
        return Vec::new();
    };

    let lines: Vec<&str> = body.lines().collect();
    let mut entities: Vec<Entity> = Vec::new();
    let mut current_name: Option<String> = None;
    let mut current_line: usize = 0;
    let mut current_fields: Vec<(String, FieldValue)> = Vec::new();
    // Track multi-line value continuation and nested list building
    let mut pending_list_key: Option<String> = None;
    let mut pending_list_items: Vec<String> = Vec::new();

    for (i, line) in lines.iter().enumerate() {
        let file_line = section_start_line + 1 + i; // +1 because body starts after the H2 heading line

        // Check for H3 heading
        if let Some(name) = strip_h3(line) {
            // Flush pending list
            flush_pending_list(
                &mut pending_list_key,
                &mut pending_list_items,
                &mut current_fields,
            );

            // Flush previous entity
            if let Some(entity_name) = current_name.take() {
                let entity = build_entity(
                    entity_name,
                    label,
                    current_line,
                    &mut current_fields,
                    errors,
                );
                entities.push(entity);
            }

            current_name = Some(name.to_string());
            current_line = file_line;
            current_fields.clear();
            continue;
        }

        // Only parse bullet fields if we're inside an entity (after an H3)
        if current_name.is_none() {
            if !line.trim().is_empty() {
                errors.push(ParseError {
                    line: file_line,
                    message: "content before first entity heading (### Name)".into(),
                });
            }
            continue;
        }

        let trimmed = line.trim();

        // Nested list item: `  - value` (2-space indent + dash)
        if let Some(item) = trimmed.strip_prefix("- ") {
            if line.starts_with("  - ") && pending_list_key.is_some() {
                // Nested list item for pending list key
                pending_list_items.push(item.trim().to_string());
                continue;
            }

            // Flush pending list before processing new top-level bullet
            flush_pending_list(
                &mut pending_list_key,
                &mut pending_list_items,
                &mut current_fields,
            );

            // Top-level bullet: `- key: value` or `- key:`
            if let Some((key, value)) = parse_bullet(item) {
                if value.is_empty() {
                    // Start a nested list: `- urls:`
                    pending_list_key = Some(key);
                    pending_list_items.clear();
                } else if is_list_field(&key) && value.contains(',') {
                    // Comma-separated list: `- aliases: A, B, C`
                    let items: Vec<String> = value
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect();
                    current_fields.push((key, FieldValue::List(items)));
                } else {
                    current_fields.push((key, FieldValue::Single(value)));
                }
            } else {
                errors.push(ParseError {
                    line: file_line,
                    message: format!(
                        "invalid field syntax: expected `- key: value`, got {trimmed:?}"
                    ),
                });
            }
            continue;
        }

        // Multi-line value continuation (2-space indent, not a bullet)
        if line.starts_with("  ") && !trimmed.is_empty() && !trimmed.starts_with('-') {
            if pending_list_key.is_some() {
                // Could be continuation inside a list context -- treat as error
                errors.push(ParseError {
                    line: file_line,
                    message: "unexpected indented text in list context".into(),
                });
            } else if let Some(last) = current_fields.last_mut() {
                // Append to last single-value field
                if let FieldValue::Single(ref mut val) = last.1 {
                    val.push('\n');
                    val.push_str(trimmed);
                }
            }
            continue;
        }

        // Blank line or other content -- ignore
        if !trimmed.is_empty() {
            // Flush pending list on non-indented non-bullet content
            flush_pending_list(
                &mut pending_list_key,
                &mut pending_list_items,
                &mut current_fields,
            );
        }
    }

    // Flush final pending list and entity
    flush_pending_list(
        &mut pending_list_key,
        &mut pending_list_items,
        &mut current_fields,
    );

    if let Some(entity_name) = current_name.take() {
        let entity = build_entity(
            entity_name,
            label,
            current_line,
            &mut current_fields,
            errors,
        );
        entities.push(entity);
    }

    // Boundary check
    if entities.len() > MAX_ENTITIES_PER_FILE {
        errors.push(ParseError {
            line: section_start_line,
            message: format!(
                "too many entities in section (max {MAX_ENTITIES_PER_FILE}, got {})",
                entities.len()
            ),
        });
    }

    entities
}

fn flush_pending_list(
    pending_key: &mut Option<String>,
    pending_items: &mut Vec<String>,
    fields: &mut Vec<(String, FieldValue)>,
) {
    if let Some(key) = pending_key.take() {
        fields.push((key, FieldValue::List(std::mem::take(pending_items))));
    }
}

fn build_entity(
    name: String,
    label: Label,
    line: usize,
    fields: &mut Vec<(String, FieldValue)>,
    errors: &mut Vec<ParseError>,
) -> Entity {
    // Validate name
    if name.trim().is_empty() {
        errors.push(ParseError {
            line,
            message: "entity name must not be empty".into(),
        });
    } else if name.len() > MAX_NAME_LEN {
        errors.push(ParseError {
            line,
            message: format!(
                "entity name exceeds {MAX_NAME_LEN} chars (got {})",
                name.len()
            ),
        });
    }

    // Extract id field before validation (not a schema field)
    let id = extract_id_field(fields);

    // Apply type: shorthand
    apply_type_shorthand(fields, label);

    // Validate fields against schema
    validate_fields(fields, label, line, errors);

    Entity {
        name,
        label,
        fields: std::mem::take(fields),
        id,
        line,
    }
}

/// Extract and remove the `id` field from the field list.
fn extract_id_field(fields: &mut Vec<(String, FieldValue)>) -> Option<String> {
    let pos = fields.iter().position(|(k, _)| k == "id")?;
    let (_, value) = fields.remove(pos);
    match value {
        FieldValue::Single(s) if !s.is_empty() => Some(s),
        _ => None,
    }
}

/// Replace `type:` shorthand with the label-specific field name.
fn apply_type_shorthand(fields: &mut [(String, FieldValue)], label: Label) {
    for field in fields.iter_mut() {
        if field.0 == "type" {
            field.0 = match label {
                Label::Institution => "institution_type".to_string(),
                Label::PublicRecord => "document_type".to_string(),
                Label::Actor => "type".to_string(), // will be caught as unknown
            };
        }
    }
}

/// Parse `key: value` from a bullet item (after stripping `- `).
fn parse_bullet(item: &str) -> Option<(String, String)> {
    let colon_pos = item.find(':')?;
    let key = item[..colon_pos].trim();
    if key.is_empty() {
        return None;
    }
    let value = item[colon_pos + 1..].trim();
    Some((key.to_string(), value.to_string()))
}

/// Check if a field name is a list-type field.
fn is_list_field(key: &str) -> bool {
    matches!(key, "aliases" | "urls")
}

/// Strip an H3 heading prefix. Returns the heading text.
fn strip_h3(line: &str) -> Option<&str> {
    let trimmed = line.trim_start();
    if let Some(rest) = trimmed.strip_prefix("### ") {
        // Must not be H4+
        if !rest.starts_with('#') {
            return Some(rest.trim());
        }
    }
    None
}

// --- Field validation ---

/// Known fields per label (common + label-specific).
const COMMON_FIELDS: &[&str] = &[
    "qualifier",
    "aliases",
    "thumbnail",
    "thumbnail_source",
    "occurred_at",
    "urls",
    "description",
];

const ACTOR_FIELDS: &[&str] = &[
    "date_of_birth",
    "place_of_birth",
    "nationality",
    "occupation",
];

const INSTITUTION_FIELDS: &[&str] = &[
    "institution_type",
    "jurisdiction",
    "headquarters",
    "founded_date",
    "registration_number",
];

const PUBLIC_RECORD_FIELDS: &[&str] = &[
    "document_type",
    "case_number",
    "filing_date",
    "issuing_authority",
];

/// Known enum values.
const OCCUPATION_VALUES: &[&str] = &[
    "politician",
    "executive",
    "journalist",
    "lawyer",
    "footballer",
    "activist",
    "civil_servant",
    "military",
    "academic",
    "lobbyist",
];

const INSTITUTION_TYPE_VALUES: &[&str] = &[
    "football_club",
    "political_party",
    "corporation",
    "government_agency",
    "court",
    "law_enforcement",
    "ngo",
    "media",
    "regulatory_body",
    "military",
    "university",
    "trade_union",
    "lobby_group",
    "sports_body",
];

const DOCUMENT_TYPE_VALUES: &[&str] = &[
    "court_ruling",
    "criminal_charge",
    "contract",
    "legislation",
    "filing",
    "investigation",
    "termination",
    "transfer",
    "election_result",
    "financial_disclosure",
    "sanctions",
    "permit",
    "audit_report",
];

/// Field max lengths.
struct FieldConstraint {
    max_len: usize,
    /// If Some, the field is an enum with these known values.
    enum_values: Option<&'static [&'static str]>,
}

fn field_constraint(key: &str) -> Option<FieldConstraint> {
    match key {
        "description" => Some(FieldConstraint {
            max_len: 2000,
            enum_values: None,
        }),
        "thumbnail" | "thumbnail_source" => Some(FieldConstraint {
            max_len: 2048,
            enum_values: None,
        }),
        "occurred_at" | "date_of_birth" | "founded_date" | "filing_date" => Some(FieldConstraint {
            max_len: 10,
            enum_values: None,
        }),
        "place_of_birth" | "jurisdiction" | "headquarters" | "issuing_authority" => {
            Some(FieldConstraint {
                max_len: 200,
                enum_values: None,
            })
        }
        "occupation" => Some(FieldConstraint {
            max_len: 100,
            enum_values: Some(OCCUPATION_VALUES),
        }),
        "institution_type" => Some(FieldConstraint {
            max_len: 100,
            enum_values: Some(INSTITUTION_TYPE_VALUES),
        }),
        "document_type" => Some(FieldConstraint {
            max_len: 100,
            enum_values: Some(DOCUMENT_TYPE_VALUES),
        }),
        "qualifier" | "nationality" | "case_number" | "registration_number" => {
            Some(FieldConstraint {
                max_len: 100,
                enum_values: None,
            })
        }
        // List fields validated separately
        _ => None,
    }
}

/// Maximum items in list fields.
const MAX_ALIASES: usize = 10;
const MAX_ALIAS_LEN: usize = 200;
const MAX_URLS: usize = 10;
const MAX_URL_LEN: usize = 2048;

fn validate_fields(
    fields: &[(String, FieldValue)],
    label: Label,
    line: usize,
    errors: &mut Vec<ParseError>,
) {
    let label_fields: &[&str] = match label {
        Label::Actor => ACTOR_FIELDS,
        Label::Institution => INSTITUTION_FIELDS,
        Label::PublicRecord => PUBLIC_RECORD_FIELDS,
    };

    for (key, value) in fields {
        // Check if field is known
        if !COMMON_FIELDS.contains(&key.as_str()) && !label_fields.contains(&key.as_str()) {
            errors.push(ParseError {
                line,
                message: format!("unknown field {key:?} for {label}"),
            });
            continue;
        }

        match value {
            FieldValue::Single(val) => {
                if let Some(constraint) = field_constraint(key) {
                    if val.len() > constraint.max_len {
                        errors.push(ParseError {
                            line,
                            message: format!(
                                "field {key:?} exceeds {} chars (got {})",
                                constraint.max_len,
                                val.len()
                            ),
                        });
                    }

                    // Validate enum values
                    if let Some(allowed) = constraint.enum_values {
                        validate_enum_value(key, val, allowed, line, errors);
                    }

                    // Validate date format
                    if matches!(
                        key.as_str(),
                        "occurred_at" | "date_of_birth" | "founded_date" | "filing_date"
                    ) && !val.is_empty()
                    {
                        validate_date_format(key, val, line, errors);
                    }

                    // Validate URL fields
                    if matches!(key.as_str(), "thumbnail" | "thumbnail_source")
                        && !val.is_empty()
                        && !val.starts_with("https://")
                    {
                        errors.push(ParseError {
                            line,
                            message: format!("field {key:?} must be HTTPS URL"),
                        });
                    }
                }
            }
            FieldValue::List(items) => match key.as_str() {
                "aliases" => {
                    if items.len() > MAX_ALIASES {
                        errors.push(ParseError {
                            line,
                            message: format!(
                                "aliases exceeds {MAX_ALIASES} items (got {})",
                                items.len()
                            ),
                        });
                    }
                    for item in items {
                        if item.len() > MAX_ALIAS_LEN {
                            errors.push(ParseError {
                                line,
                                message: format!("alias exceeds {MAX_ALIAS_LEN} chars: {item:?}"),
                            });
                        }
                    }
                }
                "urls" => {
                    if items.len() > MAX_URLS {
                        errors.push(ParseError {
                            line,
                            message: format!("urls exceeds {MAX_URLS} items (got {})", items.len()),
                        });
                    }
                    for item in items {
                        if item.len() > MAX_URL_LEN {
                            errors.push(ParseError {
                                line,
                                message: format!("url exceeds {MAX_URL_LEN} chars: {item:?}"),
                            });
                        }
                        if !item.starts_with("https://") {
                            errors.push(ParseError {
                                line,
                                message: format!("url must be HTTPS: {item:?}"),
                            });
                        }
                    }
                }
                _ => {}
            },
        }
    }
}

fn validate_enum_value(
    key: &str,
    value: &str,
    allowed: &[&str],
    line: usize,
    errors: &mut Vec<ParseError>,
) {
    // custom: prefix is always valid (if non-empty after prefix, max 100 chars)
    if let Some(custom) = value.strip_prefix("custom:") {
        if custom.is_empty() || custom.len() > 100 {
            errors.push(ParseError {
                line,
                message: format!(
                    "field {key:?} custom value must be 1-100 chars, got {}",
                    custom.len()
                ),
            });
        }
        return;
    }

    let normalized = value.to_lowercase().replace(' ', "_");
    if !allowed.contains(&normalized.as_str()) {
        errors.push(ParseError {
            line,
            message: format!(
                "invalid {key} value {value:?} (known: {}; use \"custom:Value\" for custom)",
                allowed.join(", ")
            ),
        });
    }
}

fn validate_date_format(key: &str, value: &str, line: usize, errors: &mut Vec<ParseError>) {
    // Valid formats: YYYY, YYYY-MM, YYYY-MM-DD
    let valid = matches!(value.len(), 4 | 7 | 10)
        && value.chars().enumerate().all(|(i, c)| match i {
            4 | 7 => c == '-',
            _ => c.is_ascii_digit(),
        });

    if !valid {
        errors.push(ParseError {
            line,
            message: format!("field {key:?} must be YYYY, YYYY-MM, or YYYY-MM-DD, got {value:?}"),
        });
    }
}

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

    #[test]
    fn parse_actor_entity() {
        let body = [
            "",
            "### Mark Bonnick",
            "- qualifier: Arsenal Kit Manager",
            "- nationality: British",
            "- occupation: custom:Kit Manager",
            "- date_of_birth: 1962",
            "- description: Academy kit manager at Arsenal FC for 22 years",
            "  (2001-2024). Age 62 at time of dismissal.",
            "",
        ]
        .join("\n");

        let mut errors = Vec::new();
        let entities = parse_entities(&body, SectionKind::Actors, 10, &mut errors);
        assert!(errors.is_empty(), "errors: {errors:?}");
        assert_eq!(entities.len(), 1);

        let e = &entities[0];
        assert_eq!(e.name, "Mark Bonnick");
        assert_eq!(e.label, Label::Actor);
        assert_eq!(e.fields.len(), 5);

        // Check multi-line description
        let desc = e
            .fields
            .iter()
            .find(|(k, _)| k == "description")
            .map(|(_, v)| v);
        assert_eq!(
            desc,
            Some(&FieldValue::Single(
                "Academy kit manager at Arsenal FC for 22 years\n(2001-2024). Age 62 at time of dismissal.".into()
            ))
        );
    }

    #[test]
    fn parse_institution_with_type_shorthand() {
        let body = [
            "",
            "### Arsenal FC",
            "- type: football_club",
            "- jurisdiction: England",
            "- aliases: Arsenal, The Gunners, Arsenal Football Club",
            "- urls:",
            "  - https://www.arsenal.com",
            "  - https://en.wikipedia.org/wiki/Arsenal_F.C.",
            "",
        ]
        .join("\n");

        let mut errors = Vec::new();
        let entities = parse_entities(&body, SectionKind::Institutions, 20, &mut errors);
        assert!(errors.is_empty(), "errors: {errors:?}");
        assert_eq!(entities.len(), 1);

        let e = &entities[0];
        assert_eq!(e.name, "Arsenal FC");
        assert_eq!(e.label, Label::Institution);

        // type: should have been expanded to institution_type:
        let it = e.fields.iter().find(|(k, _)| k == "institution_type");
        assert_eq!(
            it.map(|(_, v)| v),
            Some(&FieldValue::Single("football_club".into()))
        );

        // aliases as comma-separated
        let aliases = e.fields.iter().find(|(k, _)| k == "aliases");
        assert_eq!(
            aliases.map(|(_, v)| v),
            Some(&FieldValue::List(vec![
                "Arsenal".into(),
                "The Gunners".into(),
                "Arsenal Football Club".into(),
            ]))
        );

        // urls as nested list
        let urls = e.fields.iter().find(|(k, _)| k == "urls");
        assert_eq!(
            urls.map(|(_, v)| v),
            Some(&FieldValue::List(vec![
                "https://www.arsenal.com".into(),
                "https://en.wikipedia.org/wiki/Arsenal_F.C.".into(),
            ]))
        );
    }

    #[test]
    fn parse_event_with_type_shorthand() {
        let body = [
            "",
            "### Bonnick dismissal",
            "- occurred_at: 2024-12-24",
            "- type: termination",
            "- description: Arsenal dismisses Bonnick.",
            "",
        ]
        .join("\n");

        let mut errors = Vec::new();
        let entities = parse_entities(&body, SectionKind::Events, 50, &mut errors);
        assert!(errors.is_empty(), "errors: {errors:?}");

        let e = &entities[0];
        assert_eq!(e.label, Label::PublicRecord);
        let dt = e.fields.iter().find(|(k, _)| k == "document_type");
        assert_eq!(
            dt.map(|(_, v)| v),
            Some(&FieldValue::Single("termination".into()))
        );
    }

    #[test]
    fn reject_unknown_field() {
        let body = "### Test\n- foobar: value\n";
        let mut errors = Vec::new();
        parse_entities(body, SectionKind::Actors, 1, &mut errors);
        assert!(errors.iter().any(|e| e.message.contains("unknown field")));
    }

    #[test]
    fn reject_wrong_label_field() {
        // institution_type on an actor
        let body = "### Test\n- institution_type: court\n";
        let mut errors = Vec::new();
        parse_entities(body, SectionKind::Actors, 1, &mut errors);
        assert!(errors.iter().any(|e| e.message.contains("unknown field")));
    }

    #[test]
    fn reject_invalid_enum_value() {
        let body = "### Test\n- occupation: wizard\n";
        let mut errors = Vec::new();
        parse_entities(body, SectionKind::Actors, 1, &mut errors);
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("invalid occupation"))
        );
    }

    #[test]
    fn accept_custom_enum_value() {
        let body = "### Test\n- occupation: custom:Kit Manager\n";
        let mut errors = Vec::new();
        let entities = parse_entities(body, SectionKind::Actors, 1, &mut errors);
        assert!(errors.is_empty(), "errors: {errors:?}");
        assert_eq!(entities.len(), 1);
    }

    #[test]
    fn reject_invalid_date_format() {
        let body = "### Test\n- date_of_birth: January 1990\n";
        let mut errors = Vec::new();
        parse_entities(body, SectionKind::Actors, 1, &mut errors);
        assert!(errors.iter().any(|e| e.message.contains("YYYY")));
    }

    #[test]
    fn accept_valid_date_formats() {
        for date in &["2024", "2024-01", "2024-01-15"] {
            let body = format!("### Test\n- date_of_birth: {date}\n");
            let mut errors = Vec::new();
            parse_entities(&body, SectionKind::Actors, 1, &mut errors);
            assert!(
                errors.is_empty(),
                "date {date:?} should be valid: {errors:?}"
            );
        }
    }

    #[test]
    fn reject_non_https_url() {
        let body = "### Test\n- urls:\n  - http://example.com\n";
        let mut errors = Vec::new();
        parse_entities(body, SectionKind::Actors, 1, &mut errors);
        assert!(errors.iter().any(|e| e.message.contains("HTTPS")));
    }

    #[test]
    fn reject_non_https_thumbnail() {
        let body = "### Test\n- thumbnail: http://example.com/img.jpg\n";
        let mut errors = Vec::new();
        parse_entities(body, SectionKind::Actors, 1, &mut errors);
        assert!(errors.iter().any(|e| e.message.contains("HTTPS")));
    }

    #[test]
    fn multiple_entities() {
        let body = [
            "",
            "### Alice",
            "- nationality: Dutch",
            "",
            "### Bob",
            "- nationality: British",
            "",
        ]
        .join("\n");

        let mut errors = Vec::new();
        let entities = parse_entities(&body, SectionKind::Actors, 1, &mut errors);
        assert!(errors.is_empty(), "errors: {errors:?}");
        assert_eq!(entities.len(), 2);
        assert_eq!(entities[0].name, "Alice");
        assert_eq!(entities[1].name, "Bob");
    }

    #[test]
    fn field_max_length_violation() {
        let long_val = "a".repeat(201);
        let body = format!("### Test\n- nationality: {long_val}\n");
        let mut errors = Vec::new();
        parse_entities(&body, SectionKind::Actors, 1, &mut errors);
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("exceeds 100 chars"))
        );
    }

    #[test]
    fn too_many_aliases() {
        let aliases: Vec<String> = (0..11).map(|i| format!("Alias{i}")).collect();
        let body = format!("### Test\n- aliases: {}\n", aliases.join(", "));
        let mut errors = Vec::new();
        parse_entities(&body, SectionKind::Actors, 1, &mut errors);
        assert!(errors.iter().any(|e| e.message.contains("exceeds 10")));
    }
}