weave-content 0.2.3

Content DSL parser, validator, and builder for OSINT case files
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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
mod cache;
mod entity;
mod nulid_gen;
mod output;
mod parser;
mod registry;
mod relationship;
mod thumbnail;
mod timeline;
mod verifier;
mod writeback;

use clap::{Parser, Subcommand};

use crate::entity::Entity;
use crate::parser::{ParseError, ParsedCase, SectionKind};
use crate::relationship::Rel;

/// Content DSL parser, validator, and builder for OSINT case files.
#[derive(Parser)]
#[command(name = "weave-content", version, about)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Validate case files (parse and check schema).
    Validate {
        /// Path to case file, or content root directory.
        /// When a directory is given, auto-discovers cases/**/*.md.
        path: Option<String>,

        /// Content root directory (for loading entity registry).
        /// Defaults to the parent of the given path, or current directory.
        #[arg(long)]
        root: Option<String>,
    },
    /// Verify URLs in case files (HEAD/GET checks).
    Verify {
        /// Path to case file, or content root directory.
        path: Option<String>,

        /// Content root directory.
        #[arg(long)]
        root: Option<String>,

        /// Maximum concurrent requests.
        #[arg(long, default_value_t = 16)]
        concurrency: usize,

        /// Per-URL timeout in seconds.
        #[arg(long, default_value_t = 15)]
        timeout: u64,

        /// Path to URL verification cache file.
        #[arg(long)]
        cache: Option<String>,

        /// Report all as warnings, never fail.
        #[arg(long)]
        warn_only: bool,
    },
    /// Build JSON output from case files.
    Build {
        /// Path to case file, or content root directory.
        path: Option<String>,

        /// Content root directory.
        #[arg(long)]
        root: Option<String>,

        /// Output directory (one JSON per case). Stdout if omitted.
        #[arg(short, long)]
        output: Option<String>,

        /// S3 endpoint for thumbnail uploads.
        #[arg(long)]
        s3_endpoint: Option<String>,

        /// S3 bucket for thumbnail uploads.
        #[arg(long)]
        s3_bucket: Option<String>,

        /// S3 region.
        #[arg(long)]
        s3_region: Option<String>,

        /// Public URL prefix for uploaded files.
        #[arg(long)]
        files_public_url: Option<String>,
    },
}

fn main() {
    let cli = Cli::parse();

    let exit_code = match cli.command {
        Command::Validate { ref path, ref root } => cmd_validate(path.as_deref(), root.as_deref()),
        Command::Verify {
            ref path,
            ref root,
            concurrency,
            timeout,
            ref cache,
            warn_only,
        } => cmd_verify(
            path.as_deref(),
            root.as_deref(),
            concurrency,
            timeout,
            cache.as_deref(),
            warn_only,
        ),
        Command::Build {
            ref path,
            ref root,
            ref output,
            ref s3_endpoint,
            ref s3_bucket,
            ref s3_region,
            ref files_public_url,
        } => cmd_build(
            path.as_deref(),
            root.as_deref(),
            output.as_deref(),
            s3_endpoint.as_deref(),
            s3_bucket.as_deref(),
            s3_region.as_deref(),
            files_public_url.as_deref(),
        ),
    };

    std::process::exit(exit_code);
}

fn cmd_validate(path: Option<&str>, root: Option<&str>) -> i32 {
    let content_root = resolve_content_root(path, root);
    let reg = match load_registry(&content_root) {
        Ok(r) => r,
        Err(code) => return code,
    };

    let case_files = match resolve_case_files(path, &content_root) {
        Ok(f) => f,
        Err(code) => return code,
    };

    if case_files.is_empty() {
        eprintln!("no case files found");
        return 1;
    }

    if !reg.is_empty() {
        eprintln!("registry: {} entities loaded", reg.len(),);
    }

    let mut exit_code = 0;
    for case_path in &case_files {
        let result = validate_single_case(case_path, &reg);
        if result != 0 {
            exit_code = result;
        }
    }
    exit_code
}

fn validate_single_case(path: &str, reg: &registry::EntityRegistry) -> i32 {
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{path}: error reading file: {e}");
            return 2;
        }
    };

    match parse_full(&content, Some(reg)) {
        Ok((case, entities, rels)) => {
            eprintln!(
                "{path}: ok -- {id}: {title} ({ent} entities, {rel} relationships, {src} sources)",
                id = case.id,
                title = case.title,
                ent = entities.len(),
                rel = rels.len(),
                src = case.sources.len(),
            );
            if !case.summary.is_empty() {
                eprintln!(
                    "  summary: {}...",
                    &case.summary[..case.summary.len().min(80)]
                );
            }
            for e in &entities {
                let id_display = e.id.as_deref().unwrap_or("(no id)");
                eprintln!(
                    "  line {}: {id_display} {} ({}, {} fields)",
                    e.line,
                    e.name,
                    e.label,
                    e.fields.len()
                );
            }
            for r in &rels {
                let id_display = r.id.as_deref().unwrap_or("(no id)");
                eprintln!(
                    "  line {}: {id_display} {} -> {}: {}",
                    r.line, r.source_name, r.target_name, r.rel_type,
                );
            }
            0
        }
        Err(errors) => {
            for err in &errors {
                eprintln!("{path}:{err}");
            }
            1
        }
    }
}

#[allow(clippy::too_many_lines)]
fn cmd_verify(
    path: Option<&str>,
    root: Option<&str>,
    concurrency: usize,
    timeout: u64,
    cache_path: Option<&str>,
    warn_only: bool,
) -> i32 {
    let content_root = resolve_content_root(path, root);
    let reg = match load_registry(&content_root) {
        Ok(r) => r,
        Err(code) => return code,
    };

    let case_files = match resolve_case_files(path, &content_root) {
        Ok(f) => f,
        Err(code) => return code,
    };

    if case_files.is_empty() {
        eprintln!("no case files found");
        return 1;
    }

    let mut exit_code = 0;
    for case_path in &case_files {
        let result =
            verify_single_case(case_path, &reg, concurrency, timeout, cache_path, warn_only);
        if result != 0 {
            exit_code = result;
        }
    }
    exit_code
}

#[allow(clippy::too_many_lines)]
fn verify_single_case(
    path: &str,
    reg: &registry::EntityRegistry,
    concurrency: usize,
    timeout: u64,
    cache_path: Option<&str>,
    warn_only: bool,
) -> i32 {
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{path}: error reading file: {e}");
            return 2;
        }
    };

    let (case, entities, rels) = match parse_full(&content, Some(reg)) {
        Ok(result) => result,
        Err(errors) => {
            for err in &errors {
                eprintln!("{path}:{err}");
            }
            return 1;
        }
    };

    let mut collect_errors = Vec::new();
    let urls = verifier::collect_urls(&case.sources, &entities, &rels, &mut collect_errors);

    if !collect_errors.is_empty() {
        for err in &collect_errors {
            eprintln!("{path}:{err}");
        }
        return 1;
    }

    if urls.is_empty() {
        eprintln!("{path}: no URLs to verify");
        return 0;
    }

    // Load cache if path provided
    let mut verify_cache = cache_path.map(|p| match cache::VerifyCache::load(p) {
        Ok(c) => {
            eprintln!("{path}: using cache {p}");
            c
        }
        Err(e) => {
            eprintln!("{path}: cache load warning: {e}");
            cache::VerifyCache::load("/dev/null").unwrap_or_else(|_| {
                // Fallback: in-memory only, won't save
                cache::VerifyCache::empty()
            })
        }
    });

    // Partition URLs into cached and uncached
    let (cached_results, urls_to_check) = partition_cached(&urls, verify_cache.as_ref());

    let check_count = urls_to_check.len();
    let cached_count = cached_results.len();

    if cached_count > 0 {
        eprintln!(
            "{path}: {cached_count} cached, {check_count} to check (concurrency={concurrency}, timeout={timeout}s)"
        );
    } else {
        eprintln!(
            "{path}: verifying {check_count} URLs (concurrency={concurrency}, timeout={timeout}s)"
        );
    }

    let fresh_results = if urls_to_check.is_empty() {
        Vec::new()
    } else {
        let rt = match tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
        {
            Ok(rt) => rt,
            Err(e) => {
                eprintln!("{path}: failed to create async runtime: {e}");
                return 2;
            }
        };
        rt.block_on(verifier::verify_urls(urls_to_check, concurrency, timeout))
    };

    // Update cache with fresh results
    if let Some(ref mut vc) = verify_cache {
        for check in &fresh_results {
            vc.put(&check.url, check.status, check.detail.as_deref());
        }
    }

    // Combine cached + fresh results
    let mut all_results = cached_results;
    all_results.extend(fresh_results);

    let mut has_error = false;

    for check in &all_results {
        let detail = check.detail.as_deref().unwrap_or("");
        match check.status {
            verifier::CheckStatus::Ok => {
                eprintln!(
                    "  ok  {}{}",
                    check.url,
                    if check.is_thumbnail {
                        " [thumbnail]"
                    } else {
                        ""
                    }
                );
            }
            verifier::CheckStatus::Warn => {
                eprintln!("  warn  {} -- {detail}", check.url);
            }
            verifier::CheckStatus::Error => {
                has_error = true;
                eprintln!("  ERROR {} -- {detail}", check.url);
            }
        }
    }

    let ok_count = all_results
        .iter()
        .filter(|c| c.status == verifier::CheckStatus::Ok)
        .count();
    let warn_count = all_results
        .iter()
        .filter(|c| c.status == verifier::CheckStatus::Warn)
        .count();
    let err_count = all_results
        .iter()
        .filter(|c| c.status == verifier::CheckStatus::Error)
        .count();

    eprintln!("{path}: {ok_count} ok, {warn_count} warn, {err_count} error");

    // Save cache
    if let Some(ref vc) = verify_cache
        && let Err(e) = vc.save()
    {
        eprintln!("{path}: cache save warning: {e}");
    }

    i32::from(has_error && !warn_only)
}

/// Partition URLs into cached (already verified) and uncached (need checking).
fn partition_cached(
    urls: &[verifier::UrlEntry],
    verify_cache: Option<&cache::VerifyCache>,
) -> (Vec<verifier::UrlCheck>, Vec<verifier::UrlEntry>) {
    let Some(vc) = verify_cache else {
        // No cache -- all URLs need checking
        return (
            Vec::new(),
            urls.iter().map(verifier::UrlEntry::clone_entry).collect(),
        );
    };

    let mut cached = Vec::new();
    let mut uncached = Vec::new();

    for entry in urls {
        if let Some(cache_entry) = vc.get(entry.url()) {
            let status = match cache_entry.status.as_str() {
                "ok" => verifier::CheckStatus::Ok,
                "warn" => verifier::CheckStatus::Warn,
                _ => verifier::CheckStatus::Error,
            };
            cached.push(verifier::UrlCheck {
                url: entry.url().to_string(),
                status,
                detail: cache_entry.detail.clone(),
                is_thumbnail: entry.is_thumbnail(),
            });
        } else {
            uncached.push(entry.clone_entry());
        }
    }

    (cached, uncached)
}

fn cmd_build(
    path: Option<&str>,
    root: Option<&str>,
    output_dir: Option<&str>,
    s3_endpoint: Option<&str>,
    s3_bucket: Option<&str>,
    s3_region: Option<&str>,
    files_public_url: Option<&str>,
) -> i32 {
    let content_root = resolve_content_root(path, root);
    let reg = match load_registry(&content_root) {
        Ok(r) => r,
        Err(code) => return code,
    };

    let case_files = match resolve_case_files(path, &content_root) {
        Ok(f) => f,
        Err(code) => return code,
    };

    if case_files.is_empty() {
        eprintln!("no case files found");
        return 1;
    }

    let mut exit_code = 0;
    for case_path in &case_files {
        let result = build_single_case(
            case_path,
            &reg,
            output_dir,
            s3_endpoint,
            s3_bucket,
            s3_region,
            files_public_url,
        );
        if result != 0 {
            exit_code = result;
        }
    }
    exit_code
}

#[allow(clippy::too_many_arguments)]
fn build_single_case(
    path: &str,
    reg: &registry::EntityRegistry,
    output_dir: Option<&str>,
    s3_endpoint: Option<&str>,
    s3_bucket: Option<&str>,
    s3_region: Option<&str>,
    files_public_url: Option<&str>,
) -> i32 {
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{path}: error reading file: {e}");
            return 2;
        }
    };

    let (case, entities, rels) = match parse_full(&content, Some(reg)) {
        Ok(result) => result,
        Err(errors) => {
            for err in &errors {
                eprintln!("{path}:{err}");
            }
            return 1;
        }
    };

    // Collect referenced registry entities (those named in relationships)
    let referenced_entities = collect_referenced_registry_entities(&rels, &entities, reg);

    let build_result = match output::build_output(
        &case.id,
        &case.title,
        &case.summary,
        &case.sources,
        &entities,
        &rels,
        &referenced_entities,
    ) {
        Ok(out) => out,
        Err(errors) => {
            for err in &errors {
                eprintln!("{path}:{err}");
            }
            return 1;
        }
    };

    let mut case_output = build_result.output;

    // Write back generated IDs to source case file
    if !build_result.case_pending.is_empty() {
        let mut pending = build_result.case_pending;
        if let Some(modified) = writeback::apply_writebacks(&content, &mut pending) {
            if let Err(e) = writeback::write_file(std::path::Path::new(path), &modified) {
                eprintln!("{e}");
                return 2;
            }
            let count = pending.len();
            eprintln!("{path}: wrote {count} generated ID(s) back to file");
        }
    }

    // Write back generated IDs to entity files
    if let Some(code) = writeback_registry_entities(&build_result.registry_pending, reg) {
        return code;
    }

    // Process thumbnails if S3 config is available
    if let Some(config) =
        thumbnail::S3Config::from_args_or_env(s3_endpoint, s3_bucket, s3_region, files_public_url)
    {
        let rt = match tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
        {
            Ok(rt) => rt,
            Err(e) => {
                eprintln!("{path}: failed to create async runtime: {e}");
                return 2;
            }
        };
        thumbnail::process_thumbnails(&mut case_output, &config, &rt);
    }

    write_case_output(path, &case.id, &case_output, output_dir)
}

/// Write back generated IDs to registry entity files.
/// Returns `Some(exit_code)` on error, `None` on success.
fn writeback_registry_entities(
    pending: &[(String, writeback::PendingId)],
    reg: &registry::EntityRegistry,
) -> Option<i32> {
    for (entity_name, pending_id) in pending {
        let Some(entry) = reg.get_by_name(entity_name) else {
            continue;
        };
        let entity_path = &entry.path;
        let entity_content = match std::fs::read_to_string(entity_path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("{}: error reading file: {e}", entity_path.display());
                return Some(2);
            }
        };
        let fm_end = writeback::find_front_matter_end(&entity_content);
        let mut ids = vec![writeback::PendingId {
            line: fm_end.unwrap_or(2),
            id: pending_id.id.clone(),
            kind: writeback::WriteBackKind::EntityFrontMatter,
        }];
        if let Some(modified) = writeback::apply_writebacks(&entity_content, &mut ids) {
            if let Err(e) = writeback::write_file(entity_path, &modified) {
                eprintln!("{e}");
                return Some(2);
            }
            eprintln!("{}: wrote generated ID back to file", entity_path.display());
        }
    }
    None
}

/// Write case output JSON to file or stdout.
fn write_case_output(
    path: &str,
    case_id: &str,
    case_output: &output::CaseOutput,
    output_dir: Option<&str>,
) -> i32 {
    match output_dir {
        Some(dir) => {
            let out_path = format!("{dir}/{case_id}.json");
            match serde_json::to_string_pretty(case_output) {
                Ok(json) => {
                    if let Err(e) = std::fs::write(&out_path, json) {
                        eprintln!("{out_path}: error writing file: {e}");
                        return 2;
                    }
                    eprintln!("{path} -> {out_path}");
                }
                Err(e) => {
                    eprintln!("{path}: JSON serialization error: {e}");
                    return 2;
                }
            }
        }
        None => match serde_json::to_string_pretty(case_output) {
            Ok(json) => println!("{json}"),
            Err(e) => {
                eprintln!("{path}: JSON serialization error: {e}");
                return 2;
            }
        },
    }

    0
}

/// Resolve the content root directory.
///
/// Priority: explicit `--root` flag > parent of given path > current directory.
fn resolve_content_root(path: Option<&str>, root: Option<&str>) -> std::path::PathBuf {
    if let Some(r) = root {
        return std::path::PathBuf::from(r);
    }
    if let Some(p) = path {
        let p = std::path::Path::new(p);
        if p.is_file() {
            // Try to find content root: walk up looking for `cases/` or `actors/` directory
            if let Some(parent) = p.parent() {
                // If path is like cases/2025/football/case.md, go up 3 levels
                for ancestor in parent.ancestors() {
                    if ancestor.join("cases").is_dir()
                        || ancestor.join("actors").is_dir()
                        || ancestor.join("institutions").is_dir()
                    {
                        return ancestor.to_path_buf();
                    }
                }
                return parent.to_path_buf();
            }
        } else if p.is_dir() {
            return p.to_path_buf();
        }
    }
    std::path::PathBuf::from(".")
}

/// Load entity registry from content root. Returns empty registry if no entity dirs exist.
fn load_registry(content_root: &std::path::Path) -> Result<registry::EntityRegistry, i32> {
    match registry::EntityRegistry::load(content_root) {
        Ok(reg) => Ok(reg),
        Err(errors) => {
            for err in &errors {
                eprintln!("registry: {err}");
            }
            Err(1)
        }
    }
}

/// Resolve case file paths from path argument.
/// If path is a file, returns just that file.
/// If path is a directory (or None), auto-discovers `cases/**/*.md`.
fn resolve_case_files(
    path: Option<&str>,
    content_root: &std::path::Path,
) -> Result<Vec<String>, i32> {
    if let Some(p) = path {
        let p_path = std::path::Path::new(p);
        if p_path.is_file() {
            return Ok(vec![p.to_string()]);
        }
        if !p_path.is_dir() {
            eprintln!("{p}: not a file or directory");
            return Err(2);
        }
    }

    // Auto-discover: cases/**/*.md
    let cases_dir = content_root.join("cases");
    if !cases_dir.is_dir() {
        return Ok(Vec::new());
    }

    let mut files = Vec::new();
    discover_md_files(&cases_dir, &mut files, 0);
    files.sort();
    Ok(files)
}

/// Recursively discover .md files in a directory (max 3 levels deep for cases/year/topic/).
fn discover_md_files(dir: &std::path::Path, files: &mut Vec<String>, depth: usize) {
    const MAX_DEPTH: usize = 3;
    if depth > MAX_DEPTH {
        return;
    }

    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };

    let mut entries: Vec<_> = entries.filter_map(Result::ok).collect();
    entries.sort_by_key(std::fs::DirEntry::file_name);

    for entry in entries {
        let path = entry.path();
        if path.is_dir() {
            discover_md_files(&path, files, depth + 1);
        } else if path.extension().and_then(|e| e.to_str()) == Some("md") {
            if let Some(s) = path.to_str() {
                files.push(s.to_string());
            }
        }
    }
}

/// Collect registry entities referenced by relationships in this case.
fn collect_referenced_registry_entities(
    rels: &[Rel],
    inline_entities: &[Entity],
    reg: &registry::EntityRegistry,
) -> Vec<Entity> {
    let inline_names: Vec<&str> = inline_entities.iter().map(|e| e.name.as_str()).collect();
    let mut referenced = Vec::new();
    let mut seen_names: Vec<String> = Vec::new();

    for rel in rels {
        for name in [&rel.source_name, &rel.target_name] {
            if !inline_names.contains(&name.as_str()) && !seen_names.contains(name) {
                if let Some(entry) = reg.get_by_name(name) {
                    referenced.push(entry.entity.clone());
                    seen_names.push(name.clone());
                }
            }
        }
    }

    referenced
}

/// Parse a case file fully: front matter, entities, relationships, timeline.
/// Returns the parsed case, inline entities, and relationships (including NEXT from timeline).
///
/// When a registry is provided, relationship and timeline names are resolved
/// against both inline events AND the global entity registry.
fn parse_full(
    content: &str,
    reg: Option<&registry::EntityRegistry>,
) -> Result<(ParsedCase, Vec<Entity>, Vec<Rel>), Vec<ParseError>> {
    let case = parser::parse(content)?;
    let mut errors = Vec::new();

    let mut all_entities = Vec::new();
    for section in &case.sections {
        if section.kind == SectionKind::Events {
            let entities =
                entity::parse_entities(&section.body, section.kind, section.line, &mut errors);
            all_entities.extend(entities);
        }
    }

    // Build combined name list: inline events + registry entities
    let mut entity_names: Vec<&str> = all_entities.iter().map(|e| e.name.as_str()).collect();
    if let Some(registry) = reg {
        for name in registry.names() {
            if !entity_names.contains(&name) {
                entity_names.push(name);
            }
        }
    }

    let event_names: Vec<&str> = all_entities
        .iter()
        .filter(|e| e.label == entity::Label::PublicRecord)
        .map(|e| e.name.as_str())
        .collect();

    let mut all_rels = Vec::new();
    for section in &case.sections {
        if section.kind == SectionKind::Relationships {
            let rels = relationship::parse_relationships(
                &section.body,
                section.line,
                &entity_names,
                &case.sources,
                &mut errors,
            );
            all_rels.extend(rels);
        }
    }

    for section in &case.sections {
        if section.kind == SectionKind::Timeline {
            let rels =
                timeline::parse_timeline(&section.body, section.line, &event_names, &mut errors);
            all_rels.extend(rels);
        }
    }

    if errors.is_empty() {
        Ok((case, all_entities, all_rels))
    } else {
        Err(errors)
    }
}

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

    const FULL_CASE: &str = r"---
id: bonnick-v-arsenal
sources:
  - https://www.theguardian.com/football/2025/feb/03/bonnick
  - https://novaramedia.com/2025/02/04/bonnick
---

# Bonnick v Arsenal FC

Kit manager dismissed over social media posts about Israel-Gaza.

## Events

### Bonnick dismissal
- occurred_at: 2024-12-24
- document_type: termination
- description: Arsenal dismisses Bonnick over social media posts
  regarding Israel-Gaza conflict.

### FA investigation finding
- occurred_at: 2024
- document_type: investigation
- description: FA investigates and finds the posts did not breach
  FA rules. Matter closed by FA.

### Employment tribunal filing
- occurred_at: 2025-02-03
- document_type: filing
- description: Bonnick files employment tribunal claim against Arsenal.

## Relationships

- Bonnick dismissal -> FA investigation finding: related_to
- FA investigation finding -> Employment tribunal filing: related_to
- Bonnick dismissal -> Employment tribunal filing: related_to
  - source: https://novaramedia.com/2025/02/04/bonnick

## Timeline

Bonnick dismissal -> FA investigation finding -> Employment tribunal filing
";

    #[test]
    fn parse_full_case_file() {
        let (case, entities, rels) = parse_full(FULL_CASE, None).unwrap();

        assert_eq!(case.id, "bonnick-v-arsenal");
        assert_eq!(case.title, "Bonnick v Arsenal FC");
        assert!(case.summary.contains("Kit manager dismissed"));
        assert_eq!(case.sources.len(), 2);

        // 3 events (PublicRecord entities)
        assert_eq!(entities.len(), 3);
        assert!(
            entities
                .iter()
                .all(|e| e.label == entity::Label::PublicRecord)
        );

        let dismissal = entities
            .iter()
            .find(|e| e.name == "Bonnick dismissal")
            .unwrap();
        assert_eq!(dismissal.label, entity::Label::PublicRecord);

        // 3 explicit rels + 2 NEXT from timeline = 5
        assert_eq!(rels.len(), 5);

        // Check NEXT relationships from timeline
        let next_rels: Vec<_> = rels.iter().filter(|r| r.rel_type == "next").collect();
        assert_eq!(next_rels.len(), 2);
        assert_eq!(next_rels[0].source_name, "Bonnick dismissal");
        assert_eq!(next_rels[0].target_name, "FA investigation finding");
        assert_eq!(next_rels[1].source_name, "FA investigation finding");
        assert_eq!(next_rels[1].target_name, "Employment tribunal filing");
    }

    #[test]
    fn parse_full_minimal_case() {
        let input = r"---
id: minimal-test
sources:
  - https://example.com/source
---

# Minimal Test Case

A simple test.

## Events

### Something happened
- occurred_at: 2025-01-01
- document_type: court_ruling
";
        let (case, entities, rels) = parse_full(input, None).unwrap();
        assert_eq!(case.id, "minimal-test");
        assert_eq!(case.title, "Minimal Test Case");
        assert_eq!(entities.len(), 1);
        assert_eq!(entities[0].name, "Something happened");
        assert!(rels.is_empty());
    }

    #[test]
    fn json_snapshot_full_case() {
        let (case, entities, rels) = parse_full(FULL_CASE, None).unwrap();
        let build_result = output::build_output(
            &case.id,
            &case.title,
            &case.summary,
            &case.sources,
            &entities,
            &rels,
            &[],
        )
        .unwrap();

        let json = serde_json::to_string_pretty(&build_result.output).unwrap();

        // Verify structure
        assert!(json.contains("\"case_id\": \"bonnick-v-arsenal\""));
        assert!(json.contains("\"title\": \"Bonnick v Arsenal FC\""));
        assert!(json.contains("\"label\": \"public_record\""));
        assert!(json.contains("\"name\": \"Bonnick dismissal\""));
        assert!(json.contains("\"name\": \"FA investigation finding\""));
        assert!(json.contains("\"document_type\": \"termination\""));
        assert!(json.contains("\"document_type\": \"investigation\""));
        assert!(json.contains("\"type\": \"related_to\""));
        assert!(json.contains("\"type\": \"next\""));

        // Verify NULIDs
        let output: serde_json::Value = serde_json::from_str(&json).unwrap();
        let nodes = output["nodes"].as_array().unwrap();
        let rels_arr = output["relationships"].as_array().unwrap();

        for node in nodes {
            let id = node["id"].as_str().unwrap();
            assert!(!id.is_empty());
            assert!(id.len() >= 20);
        }
        for rel in rels_arr {
            let id = rel["id"].as_str().unwrap();
            assert!(!id.is_empty());
        }

        // source_id/target_id should reference existing node IDs
        let node_ids: Vec<&str> = nodes.iter().map(|n| n["id"].as_str().unwrap()).collect();
        for rel in rels_arr {
            let source_id = rel["source_id"].as_str().unwrap();
            let target_id = rel["target_id"].as_str().unwrap();
            assert!(
                node_ids.contains(&source_id),
                "source_id {source_id} not found in nodes"
            );
            assert!(
                node_ids.contains(&target_id),
                "target_id {target_id} not found in nodes"
            );
        }
    }

    #[test]
    fn json_snapshot_omits_empty_fields() {
        let input = r"---
id: sparse
sources:
  - https://example.com/src
---

# Sparse Case

Summary.

## Events

### Something
- occurred_at: 2025-01-01
";
        let (case, entities, rels) = parse_full(input, None).unwrap();
        let build_result = output::build_output(
            &case.id,
            &case.title,
            &case.summary,
            &case.sources,
            &entities,
            &rels,
            &[],
        )
        .unwrap();

        let json = serde_json::to_string_pretty(&build_result.output).unwrap();

        // These should be omitted (not present at all)
        assert!(!json.contains("\"qualifier\""));
        assert!(!json.contains("\"description\""));
        assert!(!json.contains("\"thumbnail\""));
        assert!(!json.contains("\"aliases\""));
        assert!(!json.contains("\"urls\""));

        // These should be present
        assert!(json.contains("\"occurred_at\": \"2025-01-01\""));
    }

    #[test]
    fn cross_file_resolution_with_registry() {
        use std::path::PathBuf;

        // Create a registry with an actor
        let entries = vec![registry::RegistryEntry {
            entity: Entity {
                name: "Mark Bonnick".to_string(),
                label: entity::Label::Actor,
                fields: vec![(
                    "nationality".to_string(),
                    entity::FieldValue::Single("British".to_string()),
                )],
                id: Some("01JXYZ123456789ABCDEFGHIJK".to_string()),
                line: 1,
            },
            path: PathBuf::from("actors/mark-bonnick.md"),
        }];
        let reg = registry::EntityRegistry::from_entries(entries).unwrap();

        // Case file references "Mark Bonnick" in relationships
        let input = r"---
id: test-cross-ref
sources:
  - https://example.com/src
---

# Cross Reference Test

Summary.

## Events

### Dismissal
- occurred_at: 2024-12-24
- document_type: termination

## Relationships

- Mark Bonnick -> Dismissal: related_to
";
        // Without registry: should fail (Mark Bonnick not found)
        let err = parse_full(input, None).unwrap_err();
        assert!(err.iter().any(|e| e.message.contains("Mark Bonnick")));

        // With registry: should succeed
        let (case, entities, rels) = parse_full(input, Some(&reg)).unwrap();
        assert_eq!(case.id, "test-cross-ref");
        assert_eq!(entities.len(), 1); // only inline event
        assert_eq!(rels.len(), 1);
        assert_eq!(rels[0].source_name, "Mark Bonnick");
        assert_eq!(rels[0].target_name, "Dismissal");
    }
}