oximedia-archive 0.1.7

Media archive verification and long-term preservation system
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
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
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
//! Archive catalog management.
//!
//! Provides catalog entries, access control, full-text search, date-range
//! search, CSV import/export, and OAI-PMH XML export.

#![allow(dead_code)]

/// Access control level for catalog entries.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccessLevel {
    /// Freely available to all.
    Public,
    /// Available to authenticated users.
    Restricted,
    /// Sensitive; accessible only to named individuals.
    Confidential,
    /// Internal staff use only.
    Internal,
}

impl AccessLevel {
    /// Returns `true` if a user with the given `user_role` may access this level.
    ///
    /// Role hierarchy (most privileged first): `"admin"`, `"staff"`, `"user"`, anything else.
    #[must_use]
    pub fn can_access(&self, user_role: &str) -> bool {
        match self {
            Self::Public => true,
            Self::Restricted => matches!(user_role, "admin" | "staff" | "user"),
            Self::Internal => matches!(user_role, "admin" | "staff"),
            Self::Confidential => user_role == "admin",
        }
    }

    /// Short string label.
    #[must_use]
    pub const fn label(&self) -> &str {
        match self {
            Self::Public => "public",
            Self::Restricted => "restricted",
            Self::Confidential => "confidential",
            Self::Internal => "internal",
        }
    }
}

/// A single catalog record describing a media asset.
#[derive(Clone, Debug)]
pub struct CatalogEntry {
    /// Unique identifier.
    pub id: String,
    /// Human-readable title.
    pub title: String,
    /// Extended description.
    pub description: String,
    /// Creation timestamp (Unix milliseconds).
    pub date_created_ms: u64,
    /// File format identifier (e.g., `"dpx"`, `"mp4"`).
    pub format: String,
    /// Duration in seconds, if applicable.
    pub duration_secs: Option<f64>,
    /// Physical shelf location, if applicable.
    pub physical_location: Option<String>,
    /// Path or URI to the digital file.
    pub digital_path: Option<String>,
    /// Rights statement or licence.
    pub rights: String,
    /// Access control level.
    pub access_level: AccessLevel,
}

impl CatalogEntry {
    /// Create a new catalog entry with mandatory fields.
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        title: impl Into<String>,
        format: impl Into<String>,
        date_created_ms: u64,
        rights: impl Into<String>,
        access_level: AccessLevel,
    ) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            description: String::new(),
            date_created_ms,
            format: format.into(),
            duration_secs: None,
            physical_location: None,
            digital_path: None,
            rights: rights.into(),
            access_level,
        }
    }
}

/// In-memory catalog index supporting search operations.
#[derive(Default)]
pub struct CatalogIndex {
    entries: Vec<CatalogEntry>,
}

impl CatalogIndex {
    /// Create an empty index.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an entry to the index.
    pub fn add(&mut self, entry: CatalogEntry) {
        self.entries.push(entry);
    }

    /// Search entries whose `title` contains `query` (case-insensitive).
    #[must_use]
    pub fn search_by_title(&self, query: &str) -> Vec<&CatalogEntry> {
        let q = query.to_lowercase();
        self.entries
            .iter()
            .filter(|e| e.title.to_lowercase().contains(&q))
            .collect()
    }

    /// Return entries created within the given millisecond timestamp range (inclusive).
    #[must_use]
    pub fn search_by_date_range(&self, start_ms: u64, end_ms: u64) -> Vec<&CatalogEntry> {
        self.entries
            .iter()
            .filter(|e| e.date_created_ms >= start_ms && e.date_created_ms <= end_ms)
            .collect()
    }

    /// Total number of entries in the index.
    #[must_use]
    pub fn total_count(&self) -> usize {
        self.entries.len()
    }

    /// Look up an entry by its exact ID.
    #[must_use]
    pub fn get_by_id(&self, id: &str) -> Option<&CatalogEntry> {
        self.entries.iter().find(|e| e.id == id)
    }
}

/// Catalog export utilities.
pub struct CatalogExport;

impl CatalogExport {
    /// Export entries to CSV format.
    ///
    /// Columns: id, title, format, date_created_ms, duration_secs, rights, access_level
    #[must_use]
    pub fn to_csv(entries: &[CatalogEntry]) -> String {
        let mut out =
            String::from("id,title,format,date_created_ms,duration_secs,rights,access_level\n");
        for e in entries {
            let duration = e.duration_secs.map(|d| d.to_string()).unwrap_or_default();
            out.push_str(&format!(
                "{},{},{},{},{},{},{}\n",
                csv_escape(&e.id),
                csv_escape(&e.title),
                csv_escape(&e.format),
                e.date_created_ms,
                duration,
                csv_escape(&e.rights),
                e.access_level.label(),
            ));
        }
        out
    }

    /// Export entries as a minimal OAI-PMH `ListRecords` XML response.
    #[must_use]
    pub fn to_oai_pmh(entries: &[CatalogEntry]) -> String {
        let mut out = String::from(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
             <OAI-PMH xmlns=\"http://www.openarchives.org/OAI/2.0/\">\n\
             <responseDate>2026-01-01T00:00:00Z</responseDate>\n\
             <request verb=\"ListRecords\"/>\n\
             <ListRecords>\n",
        );

        for e in entries {
            out.push_str("  <record>\n    <header>\n");
            out.push_str(&format!(
                "      <identifier>{}</identifier>\n",
                xml_escape(&e.id)
            ));
            out.push_str(&format!(
                "      <datestamp>{}</datestamp>\n",
                ms_to_iso8601(e.date_created_ms)
            ));
            out.push_str("    </header>\n    <metadata>\n      <oai_dc:dc\n");
            out.push_str("        xmlns:oai_dc=\"http://www.openarchives.org/OAI/2.0/oai_dc/\"\n");
            out.push_str("        xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n");
            out.push_str(&format!(
                "        <dc:title>{}</dc:title>\n",
                xml_escape(&e.title)
            ));
            if !e.description.is_empty() {
                out.push_str(&format!(
                    "        <dc:description>{}</dc:description>\n",
                    xml_escape(&e.description)
                ));
            }
            out.push_str(&format!(
                "        <dc:format>{}</dc:format>\n",
                xml_escape(&e.format)
            ));
            out.push_str(&format!(
                "        <dc:rights>{}</dc:rights>\n",
                xml_escape(&e.rights)
            ));
            out.push_str("      </oai_dc:dc>\n    </metadata>\n  </record>\n");
        }

        out.push_str("</ListRecords>\n</OAI-PMH>");
        out
    }
}

/// Catalog import utilities.
pub struct CatalogImport;

impl CatalogImport {
    /// Parse catalog entries from a CSV string.
    ///
    /// Expects the header row `id,title,format,date_created_ms,duration_secs,rights,access_level`.
    /// Lines that cannot be parsed are silently skipped.
    #[must_use]
    pub fn from_csv(csv: &str) -> Vec<CatalogEntry> {
        let mut entries = Vec::new();
        let mut lines = csv.lines();

        // Skip header
        if lines.next().is_none() {
            return entries;
        }

        for line in lines {
            let cols: Vec<&str> = line.splitn(7, ',').collect();
            if cols.len() < 7 {
                continue;
            }

            let id = csv_unescape(cols[0]);
            let title = csv_unescape(cols[1]);
            let format = csv_unescape(cols[2]);
            let date_created_ms: u64 = cols[3].trim().parse().unwrap_or(0);
            let duration_secs: Option<f64> = cols[4]
                .trim()
                .parse()
                .ok()
                .filter(|_| !cols[4].trim().is_empty());
            let rights = csv_unescape(cols[5]);
            let access_level = match cols[6].trim() {
                "public" => AccessLevel::Public,
                "restricted" => AccessLevel::Restricted,
                "confidential" => AccessLevel::Confidential,
                "internal" => AccessLevel::Internal,
                _ => AccessLevel::Public,
            };

            let mut entry =
                CatalogEntry::new(id, title, format, date_created_ms, rights, access_level);
            entry.duration_secs = duration_secs;
            entries.push(entry);
        }

        entries
    }
}

// ── Internal helpers ──────────────────────────────────────────────────────────

/// Wrap a CSV field in quotes if it contains a comma, newline, or quote.
fn csv_escape(s: &str) -> String {
    if s.contains(',') || s.contains('\n') || s.contains('"') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

/// Strip surrounding quotes from a CSV field.
fn csv_unescape(s: &str) -> String {
    let s = s.trim();
    if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
        s[1..s.len() - 1].replace("\"\"", "\"")
    } else {
        s.to_string()
    }
}

/// Convert Unix milliseconds to a simplified ISO 8601 date string.
fn ms_to_iso8601(ms: u64) -> String {
    let secs = ms / 1_000;
    let days = secs / 86_400;
    let year = 1970 + days / 365;
    // Approximate month/day
    let day_of_year = days % 365;
    let month = day_of_year / 30 + 1;
    let day = day_of_year % 30 + 1;
    format!("{year:04}-{month:02}-{day:02}T00:00:00Z")
}

/// Minimal XML character escaping.
fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

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

    fn sample_entry(id: &str, title: &str, ms: u64) -> CatalogEntry {
        CatalogEntry::new(id, title, "dpx", ms, "CC0", AccessLevel::Public)
    }

    #[test]
    fn test_access_level_public() {
        assert!(AccessLevel::Public.can_access("anyone"));
        assert!(AccessLevel::Public.can_access("guest"));
    }

    #[test]
    fn test_access_level_restricted() {
        assert!(AccessLevel::Restricted.can_access("user"));
        assert!(!AccessLevel::Restricted.can_access("guest"));
    }

    #[test]
    fn test_access_level_internal() {
        assert!(AccessLevel::Internal.can_access("staff"));
        assert!(!AccessLevel::Internal.can_access("user"));
    }

    #[test]
    fn test_access_level_confidential() {
        assert!(AccessLevel::Confidential.can_access("admin"));
        assert!(!AccessLevel::Confidential.can_access("staff"));
    }

    #[test]
    fn test_catalog_index_add_and_count() {
        let mut idx = CatalogIndex::new();
        idx.add(sample_entry("a1", "Sunset Reel", 1_000_000));
        idx.add(sample_entry("a2", "Night Scene", 2_000_000));
        assert_eq!(idx.total_count(), 2);
    }

    #[test]
    fn test_search_by_title() {
        let mut idx = CatalogIndex::new();
        idx.add(sample_entry("a1", "Sunset Reel", 1_000_000));
        idx.add(sample_entry("a2", "Night Scene", 2_000_000));
        idx.add(sample_entry("a3", "Sunset Beach", 3_000_000));

        let results = idx.search_by_title("sunset");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_search_by_date_range() {
        let mut idx = CatalogIndex::new();
        idx.add(sample_entry("a1", "A", 1_000));
        idx.add(sample_entry("a2", "B", 5_000));
        idx.add(sample_entry("a3", "C", 9_000));

        let results = idx.search_by_date_range(2_000, 8_000);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].id, "a2");
    }

    #[test]
    fn test_catalog_export_csv_header() {
        let entries = vec![sample_entry("id1", "My Film", 0)];
        let csv = CatalogExport::to_csv(&entries);
        assert!(csv.starts_with("id,title,format,"));
        assert!(csv.contains("My Film"));
    }

    #[test]
    fn test_catalog_export_oai_pmh() {
        let entries = vec![sample_entry("oai:1", "Test", 86_400_000)];
        let xml = CatalogExport::to_oai_pmh(&entries);
        assert!(xml.contains("<OAI-PMH"));
        assert!(xml.contains("<dc:title>Test</dc:title>"));
        assert!(xml.contains("oai:1"));
    }

    #[test]
    fn test_catalog_import_from_csv() {
        let csv = "id,title,format,date_created_ms,duration_secs,rights,access_level\n\
                   film001,My Documentary,mp4,1700000000000,3600.5,CC-BY,public\n";
        let entries = CatalogImport::from_csv(csv);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].id, "film001");
        assert_eq!(entries[0].title, "My Documentary");
        assert_eq!(entries[0].format, "mp4");
        assert!((entries[0].duration_secs.expect("test expectation failed") - 3600.5).abs() < 1e-6);
        assert_eq!(entries[0].access_level, AccessLevel::Public);
    }

    #[test]
    fn test_catalog_csv_roundtrip() {
        let original = vec![
            sample_entry("r1", "Film A", 1_000_000),
            sample_entry("r2", "Film, B", 2_000_000),
        ];
        let csv = CatalogExport::to_csv(&original);
        let imported = CatalogImport::from_csv(&csv);
        assert_eq!(imported.len(), 2);
        assert_eq!(imported[0].id, original[0].id);
    }
}

// ── Hierarchical catalog organization ─────────────────────────────────────────

/// Unique collection identifier.
pub type CollectionId = String;

/// A collection node in the hierarchical catalog tree.
///
/// Collections form a tree: each collection may have zero or more
/// sub-collections and zero or more direct entry IDs.
#[derive(Clone, Debug)]
pub struct CatalogCollection {
    /// Unique identifier for this collection.
    pub id: CollectionId,
    /// Human-readable name.
    pub name: String,
    /// Optional description.
    pub description: String,
    /// Parent collection ID, or `None` for root-level collections.
    pub parent_id: Option<CollectionId>,
    /// IDs of entries directly belonging to this collection.
    pub entry_ids: Vec<String>,
    /// IDs of child sub-collections.
    pub child_ids: Vec<CollectionId>,
    /// Creation timestamp (Unix milliseconds).
    pub created_at_ms: u64,
}

impl CatalogCollection {
    /// Create a new root-level collection.
    #[must_use]
    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            description: String::new(),
            parent_id: None,
            entry_ids: Vec::new(),
            child_ids: Vec::new(),
            created_at_ms: 0,
        }
    }

    /// Create a sub-collection under a parent.
    #[must_use]
    pub fn with_parent(mut self, parent_id: impl Into<String>) -> Self {
        self.parent_id = Some(parent_id.into());
        self
    }

    /// Set the description.
    #[must_use]
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Set the creation timestamp.
    #[must_use]
    pub fn with_created_at(mut self, ms: u64) -> Self {
        self.created_at_ms = ms;
        self
    }

    /// Add an entry ID to this collection.
    pub fn add_entry(&mut self, entry_id: impl Into<String>) {
        self.entry_ids.push(entry_id.into());
    }

    /// Number of direct entries.
    #[must_use]
    pub fn entry_count(&self) -> usize {
        self.entry_ids.len()
    }

    /// Number of direct child sub-collections.
    #[must_use]
    pub fn child_count(&self) -> usize {
        self.child_ids.len()
    }

    /// Whether this is a root collection (no parent).
    #[must_use]
    pub fn is_root(&self) -> bool {
        self.parent_id.is_none()
    }
}

/// Error type for hierarchical catalog operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HierarchyError {
    /// Collection not found.
    CollectionNotFound(String),
    /// Duplicate collection ID.
    DuplicateCollection(String),
    /// Cycle detected (a collection cannot be its own ancestor).
    CycleDetected(String),
    /// Entry not found in collection.
    EntryNotFound(String),
}

impl std::fmt::Display for HierarchyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CollectionNotFound(id) => write!(f, "collection not found: {id}"),
            Self::DuplicateCollection(id) => write!(f, "duplicate collection: {id}"),
            Self::CycleDetected(id) => write!(f, "cycle detected at: {id}"),
            Self::EntryNotFound(id) => write!(f, "entry not found: {id}"),
        }
    }
}

/// Hierarchical catalog index supporting collections and sub-collections.
///
/// Provides tree-structured organization, breadcrumb path computation,
/// recursive entry collection, and move/rename operations.
#[derive(Debug, Default)]
pub struct HierarchicalCatalog {
    /// All collections keyed by ID.
    collections: std::collections::HashMap<CollectionId, CatalogCollection>,
    /// All entries keyed by entry ID -> set of collection IDs they belong to.
    entry_memberships: std::collections::HashMap<String, Vec<CollectionId>>,
}

impl HierarchicalCatalog {
    /// Create an empty hierarchical catalog.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a collection to the catalog.
    pub fn add_collection(&mut self, collection: CatalogCollection) -> Result<(), HierarchyError> {
        if self.collections.contains_key(&collection.id) {
            return Err(HierarchyError::DuplicateCollection(collection.id.clone()));
        }
        // If it has a parent, register as child of parent.
        if let Some(ref parent_id) = collection.parent_id {
            let parent = self
                .collections
                .get_mut(parent_id)
                .ok_or_else(|| HierarchyError::CollectionNotFound(parent_id.clone()))?;
            parent.child_ids.push(collection.id.clone());
        }
        self.collections.insert(collection.id.clone(), collection);
        Ok(())
    }

    /// Get a collection by its ID.
    #[must_use]
    pub fn get_collection(&self, id: &str) -> Option<&CatalogCollection> {
        self.collections.get(id)
    }

    /// Get a mutable reference to a collection.
    pub fn get_collection_mut(&mut self, id: &str) -> Option<&mut CatalogCollection> {
        self.collections.get_mut(id)
    }

    /// Total number of collections.
    #[must_use]
    pub fn collection_count(&self) -> usize {
        self.collections.len()
    }

    /// Return all root-level collections (those with no parent).
    #[must_use]
    pub fn root_collections(&self) -> Vec<&CatalogCollection> {
        self.collections.values().filter(|c| c.is_root()).collect()
    }

    /// Return the direct children of a collection.
    #[must_use]
    pub fn children_of(&self, collection_id: &str) -> Vec<&CatalogCollection> {
        self.collections
            .get(collection_id)
            .map(|c| {
                c.child_ids
                    .iter()
                    .filter_map(|cid| self.collections.get(cid))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Assign an entry to a collection.
    pub fn assign_entry(
        &mut self,
        entry_id: &str,
        collection_id: &str,
    ) -> Result<(), HierarchyError> {
        let col = self
            .collections
            .get_mut(collection_id)
            .ok_or_else(|| HierarchyError::CollectionNotFound(collection_id.to_string()))?;
        if !col.entry_ids.contains(&entry_id.to_string()) {
            col.entry_ids.push(entry_id.to_string());
        }
        self.entry_memberships
            .entry(entry_id.to_string())
            .or_default()
            .push(collection_id.to_string());
        Ok(())
    }

    /// Remove an entry from a collection.
    pub fn remove_entry_from(
        &mut self,
        entry_id: &str,
        collection_id: &str,
    ) -> Result<(), HierarchyError> {
        let col = self
            .collections
            .get_mut(collection_id)
            .ok_or_else(|| HierarchyError::CollectionNotFound(collection_id.to_string()))?;
        let before = col.entry_ids.len();
        col.entry_ids.retain(|eid| eid != entry_id);
        if col.entry_ids.len() == before {
            return Err(HierarchyError::EntryNotFound(entry_id.to_string()));
        }
        if let Some(memberships) = self.entry_memberships.get_mut(entry_id) {
            memberships.retain(|cid| cid != collection_id);
        }
        Ok(())
    }

    /// Get the breadcrumb path from root to the given collection.
    ///
    /// Returns a vector of `(id, name)` pairs from root to the target.
    #[must_use]
    pub fn breadcrumb_path(&self, collection_id: &str) -> Vec<(String, String)> {
        let mut path = Vec::new();
        let mut current_id = Some(collection_id.to_string());
        let mut seen = std::collections::HashSet::new();

        while let Some(ref cid) = current_id {
            if seen.contains(cid) {
                break; // cycle protection
            }
            seen.insert(cid.clone());
            if let Some(col) = self.collections.get(cid) {
                path.push((col.id.clone(), col.name.clone()));
                current_id = col.parent_id.clone();
            } else {
                break;
            }
        }
        path.reverse();
        path
    }

    /// Recursively collect all entry IDs in a collection and its sub-collections.
    #[must_use]
    pub fn all_entries_recursive(&self, collection_id: &str) -> Vec<String> {
        let mut result = Vec::new();
        let mut stack = vec![collection_id.to_string()];
        let mut visited = std::collections::HashSet::new();

        while let Some(cid) = stack.pop() {
            if visited.contains(&cid) {
                continue;
            }
            visited.insert(cid.clone());
            if let Some(col) = self.collections.get(&cid) {
                result.extend(col.entry_ids.iter().cloned());
                for child_id in &col.child_ids {
                    stack.push(child_id.clone());
                }
            }
        }
        result
    }

    /// Compute the depth of a collection in the hierarchy (root = 0).
    #[must_use]
    pub fn depth(&self, collection_id: &str) -> usize {
        let path = self.breadcrumb_path(collection_id);
        if path.is_empty() {
            0
        } else {
            path.len() - 1
        }
    }

    /// Get all collections an entry belongs to.
    #[must_use]
    pub fn entry_collections(&self, entry_id: &str) -> Vec<&CatalogCollection> {
        self.entry_memberships
            .get(entry_id)
            .map(|cids| {
                cids.iter()
                    .filter_map(|cid| self.collections.get(cid))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Remove a leaf collection (must have no children).
    pub fn remove_collection(
        &mut self,
        collection_id: &str,
    ) -> Result<CatalogCollection, HierarchyError> {
        let col = self
            .collections
            .get(collection_id)
            .ok_or_else(|| HierarchyError::CollectionNotFound(collection_id.to_string()))?;
        if !col.child_ids.is_empty() {
            return Err(HierarchyError::CycleDetected(format!(
                "collection '{}' has {} children; remove children first",
                collection_id,
                col.child_ids.len()
            )));
        }
        // Unlink from parent
        let parent_id = col.parent_id.clone();
        let col = self
            .collections
            .remove(collection_id)
            .ok_or_else(|| HierarchyError::CollectionNotFound(collection_id.to_string()))?;
        if let Some(ref pid) = parent_id {
            if let Some(parent) = self.collections.get_mut(pid) {
                parent.child_ids.retain(|cid| cid != collection_id);
            }
        }
        // Remove entry memberships
        for entry_id in &col.entry_ids {
            if let Some(memberships) = self.entry_memberships.get_mut(entry_id) {
                memberships.retain(|cid| cid != collection_id);
            }
        }
        Ok(col)
    }
}

impl HierarchicalCatalog {
    /// Compute the depth from the breadcrumb path length.
    fn _depth_from_breadcrumb(&self, collection_id: &str) -> usize {
        let path = self.breadcrumb_path(collection_id);
        if path.is_empty() {
            0
        } else {
            path.len() - 1
        }
    }
}

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

    fn build_hierarchy() -> HierarchicalCatalog {
        let mut h = HierarchicalCatalog::new();
        h.add_collection(CatalogCollection::new("root", "Root Collection").with_created_at(1000))
            .expect("add root");
        h.add_collection(
            CatalogCollection::new("films", "Films")
                .with_parent("root")
                .with_description("All film assets"),
        )
        .expect("add films");
        h.add_collection(CatalogCollection::new("docs", "Documentaries").with_parent("films"))
            .expect("add docs");
        h.add_collection(CatalogCollection::new("music", "Music Videos").with_parent("films"))
            .expect("add music");
        h.add_collection(CatalogCollection::new("audio", "Audio Collection").with_created_at(2000))
            .expect("add audio");
        h
    }

    #[test]
    fn test_add_and_count() {
        let h = build_hierarchy();
        assert_eq!(h.collection_count(), 5);
    }

    #[test]
    fn test_root_collections() {
        let h = build_hierarchy();
        let roots = h.root_collections();
        assert_eq!(roots.len(), 2);
    }

    #[test]
    fn test_children_of() {
        let h = build_hierarchy();
        let children = h.children_of("films");
        assert_eq!(children.len(), 2);
    }

    #[test]
    fn test_children_of_leaf() {
        let h = build_hierarchy();
        let children = h.children_of("docs");
        assert!(children.is_empty());
    }

    #[test]
    fn test_assign_entry() {
        let mut h = build_hierarchy();
        h.assign_entry("film001", "docs").expect("assign entry");
        let col = h.get_collection("docs").expect("get docs");
        assert_eq!(col.entry_count(), 1);
        assert!(col.entry_ids.contains(&"film001".to_string()));
    }

    #[test]
    fn test_remove_entry() {
        let mut h = build_hierarchy();
        h.assign_entry("film001", "docs").expect("assign");
        h.remove_entry_from("film001", "docs").expect("remove");
        let col = h.get_collection("docs").expect("get docs");
        assert_eq!(col.entry_count(), 0);
    }

    #[test]
    fn test_remove_entry_not_found() {
        let mut h = build_hierarchy();
        let result = h.remove_entry_from("ghost", "docs");
        assert!(matches!(result, Err(HierarchyError::EntryNotFound(_))));
    }

    #[test]
    fn test_breadcrumb_path() {
        let h = build_hierarchy();
        let path = h.breadcrumb_path("docs");
        assert_eq!(path.len(), 3);
        assert_eq!(path[0].0, "root");
        assert_eq!(path[1].0, "films");
        assert_eq!(path[2].0, "docs");
    }

    #[test]
    fn test_breadcrumb_path_root() {
        let h = build_hierarchy();
        let path = h.breadcrumb_path("root");
        assert_eq!(path.len(), 1);
        assert_eq!(path[0].0, "root");
    }

    #[test]
    fn test_all_entries_recursive() {
        let mut h = build_hierarchy();
        h.assign_entry("film001", "docs").expect("assign");
        h.assign_entry("film002", "music").expect("assign");
        h.assign_entry("film003", "films").expect("assign");
        let all = h.all_entries_recursive("films");
        assert_eq!(all.len(), 3);
    }

    #[test]
    fn test_all_entries_recursive_leaf() {
        let mut h = build_hierarchy();
        h.assign_entry("film001", "docs").expect("assign");
        let all = h.all_entries_recursive("docs");
        assert_eq!(all.len(), 1);
    }

    #[test]
    fn test_duplicate_collection_error() {
        let mut h = build_hierarchy();
        let result = h.add_collection(CatalogCollection::new("root", "Duplicate"));
        assert!(matches!(
            result,
            Err(HierarchyError::DuplicateCollection(_))
        ));
    }

    #[test]
    fn test_parent_not_found_error() {
        let mut h = HierarchicalCatalog::new();
        let result =
            h.add_collection(CatalogCollection::new("child", "Child").with_parent("nonexistent"));
        assert!(matches!(result, Err(HierarchyError::CollectionNotFound(_))));
    }

    #[test]
    fn test_remove_leaf_collection() {
        let mut h = build_hierarchy();
        let removed = h.remove_collection("docs").expect("remove docs");
        assert_eq!(removed.id, "docs");
        assert_eq!(h.collection_count(), 4);
        // Parent should no longer list "docs"
        let films = h.get_collection("films").expect("get films");
        assert!(!films.child_ids.contains(&"docs".to_string()));
    }

    #[test]
    fn test_remove_non_leaf_fails() {
        let mut h = build_hierarchy();
        let result = h.remove_collection("films");
        assert!(result.is_err());
    }

    #[test]
    fn test_entry_collections() {
        let mut h = build_hierarchy();
        h.assign_entry("film001", "docs").expect("assign");
        h.assign_entry("film001", "music").expect("assign");
        let cols = h.entry_collections("film001");
        assert_eq!(cols.len(), 2);
    }

    #[test]
    fn test_collection_is_root() {
        let h = build_hierarchy();
        assert!(h.get_collection("root").expect("root").is_root());
        assert!(!h.get_collection("films").expect("films").is_root());
    }

    #[test]
    fn test_hierarchy_error_display() {
        let e = HierarchyError::CollectionNotFound("test".into());
        assert!(e.to_string().contains("test"));
    }
}

// ── New asset-catalog types ───────────────────────────────────────────────────

/// Classification of a media asset.
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AssetKind {
    /// Motion picture or video clip.
    Video,
    /// Audio-only file.
    Audio,
    /// Still image.
    Image,
    /// Text document or PDF.
    Document,
    /// Subtitle or caption file.
    Subtitle,
    /// Sidecar / companion file.
    Sidecar,
}

impl AssetKind {
    /// Returns `true` for primary media kinds (Video, Audio, Image).
    #[must_use]
    pub const fn is_media(self) -> bool {
        matches!(self, Self::Video | Self::Audio | Self::Image)
    }
}

/// A single entry in the asset inventory.
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct AssetCatalogEntry {
    /// Unique numeric identifier.
    pub id: u64,
    /// Relative or absolute path.
    pub path: String,
    /// Asset classification.
    pub kind: AssetKind,
    /// File size in bytes.
    pub size_bytes: u64,
    /// Creation time as Unix epoch seconds.
    pub created_epoch: u64,
    /// Arbitrary string tags for this asset.
    pub tags: Vec<String>,
}

impl AssetCatalogEntry {
    /// Returns `true` if `t` is in the tag list (exact match).
    #[must_use]
    pub fn has_tag(&self, t: &str) -> bool {
        self.tags.iter().any(|tag| tag == t)
    }
}

/// In-memory searchable asset inventory.
#[allow(dead_code)]
#[derive(Default, Debug)]
pub struct ArchiveCatalog {
    /// All catalog entries.
    pub entries: Vec<AssetCatalogEntry>,
    next_id: u64,
}

impl ArchiveCatalog {
    /// Create an empty catalog.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an entry; assigns and returns a unique id.
    pub fn add(
        &mut self,
        path: impl Into<String>,
        kind: AssetKind,
        size_bytes: u64,
        created_epoch: u64,
        tags: Vec<String>,
    ) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        self.entries.push(AssetCatalogEntry {
            id,
            path: path.into(),
            kind,
            size_bytes,
            created_epoch,
            tags,
        });
        id
    }

    /// Find an entry by its numeric id.
    #[must_use]
    pub fn find_by_id(&self, id: u64) -> Option<&AssetCatalogEntry> {
        self.entries.iter().find(|e| e.id == id)
    }

    /// Find all entries that carry the given tag.
    #[must_use]
    pub fn find_by_tag(&self, tag: &str) -> Vec<&AssetCatalogEntry> {
        self.entries.iter().filter(|e| e.has_tag(tag)).collect()
    }

    /// Find entries whose path contains `query` (case-insensitive).
    #[must_use]
    pub fn search_path(&self, query: &str) -> Vec<&AssetCatalogEntry> {
        let q = query.to_lowercase();
        self.entries
            .iter()
            .filter(|e| e.path.to_lowercase().contains(&q))
            .collect()
    }

    /// Sum of all entry sizes.
    #[must_use]
    pub fn total_size_bytes(&self) -> u64 {
        self.entries.iter().map(|e| e.size_bytes).sum()
    }

    /// Count of entries matching `kind`.
    #[must_use]
    pub fn kind_count(&self, kind: AssetKind) -> usize {
        self.entries.iter().filter(|e| e.kind == kind).count()
    }
}

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

    fn make_catalog() -> ArchiveCatalog {
        let mut c = ArchiveCatalog::new();
        c.add(
            "videos/intro.mp4",
            AssetKind::Video,
            1_000_000,
            1_000,
            vec!["featured".into()],
        );
        c.add(
            "audio/bg.wav",
            AssetKind::Audio,
            500_000,
            2_000,
            vec!["music".into(), "featured".into()],
        );
        c.add(
            "images/thumb.jpg",
            AssetKind::Image,
            200_000,
            3_000,
            vec!["thumbnail".into()],
        );
        c.add(
            "docs/readme.pdf",
            AssetKind::Document,
            50_000,
            4_000,
            vec![],
        );
        c
    }

    #[test]
    fn test_asset_kind_is_media_video() {
        assert!(AssetKind::Video.is_media());
    }

    #[test]
    fn test_asset_kind_is_media_audio() {
        assert!(AssetKind::Audio.is_media());
    }

    #[test]
    fn test_asset_kind_not_media_document() {
        assert!(!AssetKind::Document.is_media());
    }

    #[test]
    fn test_asset_kind_not_media_sidecar() {
        assert!(!AssetKind::Sidecar.is_media());
    }

    #[test]
    fn test_has_tag_true() {
        let c = make_catalog();
        assert!(c
            .find_by_id(0)
            .expect("find_by_id should succeed")
            .has_tag("featured"));
    }

    #[test]
    fn test_has_tag_false() {
        let c = make_catalog();
        assert!(!c
            .find_by_id(0)
            .expect("find_by_id should succeed")
            .has_tag("music"));
    }

    #[test]
    fn test_find_by_id_present() {
        let c = make_catalog();
        assert!(c.find_by_id(2).is_some());
    }

    #[test]
    fn test_find_by_id_missing() {
        let c = make_catalog();
        assert!(c.find_by_id(999).is_none());
    }

    #[test]
    fn test_find_by_tag() {
        let c = make_catalog();
        let results = c.find_by_tag("featured");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_search_path_case_insensitive() {
        let c = make_catalog();
        let results = c.search_path("VIDEOS");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].path, "videos/intro.mp4");
    }

    #[test]
    fn test_total_size_bytes() {
        let c = make_catalog();
        assert_eq!(c.total_size_bytes(), 1_750_000);
    }

    #[test]
    fn test_kind_count_video() {
        let c = make_catalog();
        assert_eq!(c.kind_count(AssetKind::Video), 1);
    }

    #[test]
    fn test_kind_count_zero() {
        let c = make_catalog();
        assert_eq!(c.kind_count(AssetKind::Subtitle), 0);
    }
}