datasynth-graph 2.4.0

Graph/network export for synthetic accounting data - supports PyTorch Geometric, Neo4j, and DGL formats
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
//! RustGraph Unified Hypergraph exporter.
//!
//! Maps internal hypergraph types to RustGraph's expected unified format:
//! - `entity_type` → `node_type`
//! - `source_id`/`target_id` → `source`/`target`
//! - `label` → `name`
//! - `HypergraphLayer` enum → `layer` as `u8`
//!
//! Preserves backward compatibility by wrapping rather than renaming internal fields.

use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::Path;

use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::models::hypergraph::{
    CrossLayerEdge, Hyperedge, HyperedgeParticipant, Hypergraph, HypergraphMetadata,
    HypergraphNode, NodeBudgetReport,
};

/// A node in the RustGraph unified format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawUnifiedNode {
    /// Unique node identifier.
    pub id: String,
    /// Entity type name (mapped from `entity_type`).
    pub node_type: String,
    /// RustGraph entity type code.
    pub entity_type_code: u32,
    /// Layer index (1-3) instead of enum string.
    pub layer: u8,
    /// External identifier from the source system.
    pub external_id: String,
    /// Human-readable name (mapped from `label`).
    pub name: String,
    /// Additional properties as key-value pairs.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub properties: HashMap<String, Value>,
    /// Numeric feature vector for ML.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<f64>,
    /// Whether this node represents an anomaly.
    #[serde(default)]
    pub is_anomaly: bool,
    /// Anomaly type if anomalous.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anomaly_type: Option<String>,
    /// Whether this is an aggregate (pool) node from budget compression.
    #[serde(default)]
    pub is_aggregate: bool,
    /// Number of original entities this aggregate node represents.
    #[serde(default)]
    pub aggregate_count: usize,
}

impl RawUnifiedNode {
    /// Convert from internal `HypergraphNode` to unified format.
    pub fn from_hypergraph_node(node: &HypergraphNode) -> Self {
        Self {
            id: node.id.clone(),
            node_type: node.entity_type.clone(),
            entity_type_code: node.entity_type_code,
            layer: node.layer.index(),
            external_id: node.external_id.clone(),
            name: node.label.clone(),
            properties: node.properties.clone(),
            features: node.features.clone(),
            is_anomaly: node.is_anomaly,
            anomaly_type: node.anomaly_type.clone(),
            is_aggregate: node.is_aggregate,
            aggregate_count: node.aggregate_count,
        }
    }
}

/// An edge in the RustGraph unified format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawUnifiedEdge {
    /// Source node ID (mapped from `source_id`).
    pub source: String,
    /// Target node ID (mapped from `target_id`).
    pub target: String,
    /// Source layer index (1-3).
    pub source_layer: u8,
    /// Target layer index (1-3).
    pub target_layer: u8,
    /// Edge type name.
    pub edge_type: String,
    /// RustGraph edge type code.
    pub edge_type_code: u32,
    /// Edge weight (default 1.0).
    pub weight: f32,
    /// Additional properties as key-value pairs.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub properties: HashMap<String, Value>,
}

impl RawUnifiedEdge {
    /// Convert from internal `CrossLayerEdge` to unified format.
    pub fn from_cross_layer_edge(edge: &CrossLayerEdge) -> Self {
        Self {
            source: edge.source_id.clone(),
            target: edge.target_id.clone(),
            source_layer: edge.source_layer.index(),
            target_layer: edge.target_layer.index(),
            edge_type: edge.edge_type.clone(),
            edge_type_code: edge.edge_type_code,
            weight: 1.0,
            properties: edge.properties.clone(),
        }
    }
}

/// A hyperedge in the RustGraph unified format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawUnifiedHyperedge {
    /// Unique hyperedge identifier.
    pub id: String,
    /// High-level type: "ProcessFamily", "MultiRelation", "JournalEntry".
    pub hyperedge_type: String,
    /// Subtype with more detail.
    pub subtype: String,
    /// IDs of all member nodes (extracted from participants).
    pub member_ids: Vec<String>,
    /// Layer index (1-3).
    pub layer: u8,
    /// Full participant details with roles and weights.
    pub participants: Vec<HyperedgeParticipant>,
    /// Additional properties as key-value pairs.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub properties: HashMap<String, Value>,
    /// Optional timestamp for temporal hyperedges.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<NaiveDate>,
    /// Whether this hyperedge represents an anomaly.
    #[serde(default)]
    pub is_anomaly: bool,
    /// Anomaly type if anomalous.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anomaly_type: Option<String>,
    /// Numeric feature vector for ML.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<f64>,
}

impl RawUnifiedHyperedge {
    /// Convert from internal `Hyperedge` to unified format.
    pub fn from_hyperedge(he: &Hyperedge) -> Self {
        Self {
            id: he.id.clone(),
            hyperedge_type: he.hyperedge_type.clone(),
            subtype: he.subtype.clone(),
            member_ids: he.participants.iter().map(|p| p.node_id.clone()).collect(),
            layer: he.layer.index(),
            participants: he.participants.clone(),
            properties: he.properties.clone(),
            timestamp: he.timestamp,
            is_anomaly: he.is_anomaly,
            anomaly_type: he.anomaly_type.clone(),
            features: he.features.clone(),
        }
    }
}

/// Metadata for the unified hypergraph export.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnifiedHypergraphMetadata {
    /// Format identifier for RustGraph import.
    pub format: String,
    /// Name of this hypergraph export.
    pub name: String,
    /// Total number of nodes.
    pub num_nodes: usize,
    /// Total number of pairwise edges.
    pub num_edges: usize,
    /// Total number of hyperedges.
    pub num_hyperedges: usize,
    /// Node counts per layer.
    pub layer_node_counts: HashMap<String, usize>,
    /// Node counts per entity type.
    pub node_type_counts: HashMap<String, usize>,
    /// Edge counts per edge type.
    pub edge_type_counts: HashMap<String, usize>,
    /// Hyperedge counts per type.
    pub hyperedge_type_counts: HashMap<String, usize>,
    /// Number of anomalous nodes.
    pub anomalous_nodes: usize,
    /// Number of anomalous hyperedges.
    pub anomalous_hyperedges: usize,
    /// Source system identifier.
    pub source: String,
    /// Generation timestamp (ISO 8601).
    pub generated_at: String,
    /// Budget utilization report.
    pub budget_report: NodeBudgetReport,
    /// Files included in export.
    pub files: Vec<String>,
}

impl UnifiedHypergraphMetadata {
    /// Create unified metadata from internal `HypergraphMetadata`.
    pub fn from_metadata(meta: &HypergraphMetadata) -> Self {
        Self {
            format: "rustgraph_unified_v1".to_string(),
            name: meta.name.clone(),
            num_nodes: meta.num_nodes,
            num_edges: meta.num_edges,
            num_hyperedges: meta.num_hyperedges,
            layer_node_counts: meta.layer_node_counts.clone(),
            node_type_counts: meta.node_type_counts.clone(),
            edge_type_counts: meta.edge_type_counts.clone(),
            hyperedge_type_counts: meta.hyperedge_type_counts.clone(),
            anomalous_nodes: meta.anomalous_nodes,
            anomalous_hyperedges: meta.anomalous_hyperedges,
            source: meta.source.clone(),
            generated_at: meta.generated_at.clone(),
            budget_report: meta.budget_report.clone(),
            files: meta.files.clone(),
        }
    }
}

/// Configuration for the RustGraph unified exporter.
#[derive(Debug, Clone, Default)]
pub struct UnifiedExportConfig {
    /// Pretty-print metadata.json (for debugging).
    pub pretty_print: bool,
}

/// Exports a `Hypergraph` to JSONL files in RustGraph's unified format.
pub struct RustGraphUnifiedExporter {
    config: UnifiedExportConfig,
}

impl RustGraphUnifiedExporter {
    /// Create a new unified exporter with the given configuration.
    pub fn new(config: UnifiedExportConfig) -> Self {
        Self { config }
    }

    /// Export the hypergraph to the given output directory in unified format.
    ///
    /// Creates:
    /// - `nodes.jsonl` (one JSON object per line, unified field names)
    /// - `edges.jsonl` (one JSON object per line, unified field names)
    /// - `hyperedges.jsonl` (one JSON object per line, unified field names)
    /// - `metadata.json` (export metadata with `format: "rustgraph_unified_v1"`)
    pub fn export(
        &self,
        hypergraph: &Hypergraph,
        output_dir: &Path,
    ) -> std::io::Result<UnifiedHypergraphMetadata> {
        fs::create_dir_all(output_dir)?;

        // Export nodes
        let nodes_path = output_dir.join("nodes.jsonl");
        let file = File::create(nodes_path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);
        for node in &hypergraph.nodes {
            let unified = RawUnifiedNode::from_hypergraph_node(node);
            serde_json::to_writer(&mut writer, &unified)?;
            writeln!(writer)?;
        }
        writer.flush()?;

        // Export edges
        let edges_path = output_dir.join("edges.jsonl");
        let file = File::create(edges_path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);
        for edge in &hypergraph.edges {
            let unified = RawUnifiedEdge::from_cross_layer_edge(edge);
            serde_json::to_writer(&mut writer, &unified)?;
            writeln!(writer)?;
        }
        writer.flush()?;

        // Export hyperedges
        let hyperedges_path = output_dir.join("hyperedges.jsonl");
        let file = File::create(hyperedges_path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);
        for he in &hypergraph.hyperedges {
            let unified = RawUnifiedHyperedge::from_hyperedge(he);
            serde_json::to_writer(&mut writer, &unified)?;
            writeln!(writer)?;
        }
        writer.flush()?;

        // Build unified metadata
        let mut metadata = UnifiedHypergraphMetadata::from_metadata(&hypergraph.metadata);
        metadata.files = vec![
            "nodes.jsonl".to_string(),
            "edges.jsonl".to_string(),
            "hyperedges.jsonl".to_string(),
            "metadata.json".to_string(),
        ];

        // Export metadata
        let metadata_path = output_dir.join("metadata.json");
        let file = File::create(metadata_path)?;
        if self.config.pretty_print {
            serde_json::to_writer_pretty(file, &metadata)?;
        } else {
            serde_json::to_writer(file, &metadata)?;
        }

        Ok(metadata)
    }

    /// Export the hypergraph to a writer in unified JSONL format (for streaming).
    ///
    /// Writes all nodes, edges, and hyperedges as JSONL to the writer.
    /// Each line is prefixed with a type tag for demultiplexing:
    /// `{"_type":"node",...}`, `{"_type":"edge",...}`, `{"_type":"hyperedge",...}`
    pub fn export_to_writer<W: Write>(
        &self,
        hypergraph: &Hypergraph,
        writer: &mut W,
    ) -> std::io::Result<UnifiedHypergraphMetadata> {
        // Write nodes
        for node in &hypergraph.nodes {
            let unified = RawUnifiedNode::from_hypergraph_node(node);
            let mut obj = serde_json::to_value(&unified)?;
            obj.as_object_mut()
                .expect("serialized struct is always a JSON object")
                .insert("_type".to_string(), Value::String("node".to_string()));
            serde_json::to_writer(&mut *writer, &obj)?;
            writeln!(writer)?;
        }

        // Write edges
        for edge in &hypergraph.edges {
            let unified = RawUnifiedEdge::from_cross_layer_edge(edge);
            let mut obj = serde_json::to_value(&unified)?;
            obj.as_object_mut()
                .expect("serialized struct is always a JSON object")
                .insert("_type".to_string(), Value::String("edge".to_string()));
            serde_json::to_writer(&mut *writer, &obj)?;
            writeln!(writer)?;
        }

        // Write hyperedges
        for he in &hypergraph.hyperedges {
            let unified = RawUnifiedHyperedge::from_hyperedge(he);
            let mut obj = serde_json::to_value(&unified)?;
            obj.as_object_mut()
                .expect("serialized struct is always a JSON object")
                .insert("_type".to_string(), Value::String("hyperedge".to_string()));
            serde_json::to_writer(&mut *writer, &obj)?;
            writeln!(writer)?;
        }

        let mut metadata = UnifiedHypergraphMetadata::from_metadata(&hypergraph.metadata);
        metadata.files = vec![];

        Ok(metadata)
    }
}

#[cfg(feature = "rustgraph")]
mod bulk_export {
    use super::*;
    use rustgraph_api_types::bulk::{BulkEdgeData, BulkNodeData};

    /// Result of converting a `Hypergraph` to RustGraph bulk import types.
    ///
    /// Contains the canonical `BulkNodeData`/`BulkEdgeData` types from
    /// `rustgraph-api-types` that the RustGraph server accepts directly.
    /// Hyperedges are returned separately (no bulk API for them yet).
    #[derive(Debug, Clone)]
    pub struct RustGraphBulkExport {
        /// Nodes in canonical bulk import format (u64 IDs, u32 type codes).
        pub nodes: Vec<BulkNodeData>,
        /// Edges in canonical bulk import format (u64 source/target).
        pub edges: Vec<BulkEdgeData>,
        /// Hyperedges (not part of the bulk import API, handled separately).
        pub hyperedges: Vec<RawUnifiedHyperedge>,
        /// Mapping from original string IDs to assigned u64 IDs.
        pub id_map: HashMap<String, u64>,
    }

    impl RustGraphUnifiedExporter {
        /// Convert a `Hypergraph` to RustGraph bulk import types.
        ///
        /// Assigns sequential u64 IDs to nodes (starting at 1) and maps
        /// edge source/target string IDs to u64 via the returned `id_map`.
        /// Properties include the original string ID as `"entity_id"` and
        /// the type name as `"node_type_name"` for reverse lookups.
        pub fn to_bulk_import(&self, hypergraph: &Hypergraph) -> RustGraphBulkExport {
            let mut id_map: HashMap<String, u64> = HashMap::with_capacity(hypergraph.nodes.len());
            let mut nodes = Vec::with_capacity(hypergraph.nodes.len());

            // Convert nodes: assign sequential u64 IDs
            for (idx, hg_node) in hypergraph.nodes.iter().enumerate() {
                let id = (idx as u64) + 1; // 1-based IDs
                id_map.insert(hg_node.id.clone(), id);

                let mut properties = hg_node.properties.clone();
                properties.insert("entity_id".to_string(), Value::String(hg_node.id.clone()));
                properties.insert(
                    "node_type_name".to_string(),
                    Value::String(hg_node.entity_type.clone()),
                );
                properties.insert(
                    "external_id".to_string(),
                    Value::String(hg_node.external_id.clone()),
                );
                if hg_node.is_anomaly {
                    properties.insert("is_anomaly".to_string(), Value::Bool(true));
                    if let Some(ref at) = hg_node.anomaly_type {
                        properties.insert("anomaly_type".to_string(), Value::String(at.clone()));
                    }
                }
                if !hg_node.features.is_empty() {
                    properties.insert(
                        "features".to_string(),
                        Value::Array(
                            hg_node
                                .features
                                .iter()
                                .map(|f| serde_json::json!(f))
                                .collect(),
                        ),
                    );
                }

                nodes.push(BulkNodeData {
                    id: Some(id),
                    node_type: hg_node.entity_type_code,
                    layer: Some(hg_node.layer.index()),
                    labels: vec![hg_node.label.clone()],
                    properties,
                });
            }

            // Convert edges: resolve String IDs to u64 via id_map
            let mut edges = Vec::with_capacity(hypergraph.edges.len());
            for edge in &hypergraph.edges {
                let source = match id_map.get(&edge.source_id) {
                    Some(&id) => id,
                    None => continue, // Skip edges with unknown source
                };
                let target = match id_map.get(&edge.target_id) {
                    Some(&id) => id,
                    None => continue, // Skip edges with unknown target
                };

                let mut properties = edge.properties.clone();
                properties.insert(
                    "edge_type_name".to_string(),
                    Value::String(edge.edge_type.clone()),
                );

                edges.push(BulkEdgeData {
                    source,
                    target,
                    edge_type: edge.edge_type_code,
                    weight: 1.0,
                    properties,
                });
            }

            // Convert hyperedges (not part of bulk import API)
            let hyperedges: Vec<RawUnifiedHyperedge> = hypergraph
                .hyperedges
                .iter()
                .map(RawUnifiedHyperedge::from_hyperedge)
                .collect();

            RustGraphBulkExport {
                nodes,
                edges,
                hyperedges,
                id_map,
            }
        }
    }
}

#[cfg(feature = "rustgraph")]
pub use bulk_export::RustGraphBulkExport;

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::builders::hypergraph::{HypergraphBuilder, HypergraphConfig};
    use crate::models::hypergraph::HypergraphLayer;
    use tempfile::tempdir;

    fn build_test_hypergraph() -> Hypergraph {
        let config = HypergraphConfig {
            max_nodes: 1000,
            include_p2p: false,
            include_o2c: false,
            include_vendors: false,
            include_customers: false,
            include_employees: false,
            ..Default::default()
        };
        let mut builder = HypergraphBuilder::new(config);
        builder.add_coso_framework();
        builder.build()
    }

    #[test]
    fn test_node_conversion() {
        let node = HypergraphNode {
            id: "node_1".to_string(),
            entity_type: "Account".to_string(),
            entity_type_code: 100,
            layer: HypergraphLayer::AccountingNetwork,
            external_id: "1000".to_string(),
            label: "Cash".to_string(),
            properties: HashMap::new(),
            features: vec![1.0, 2.0],
            is_anomaly: false,
            anomaly_type: None,
            is_aggregate: false,
            aggregate_count: 0,
        };

        let unified = RawUnifiedNode::from_hypergraph_node(&node);
        assert_eq!(unified.id, "node_1");
        assert_eq!(unified.node_type, "Account");
        assert_eq!(unified.name, "Cash");
        assert_eq!(unified.layer, 3); // AccountingNetwork = 3
        assert_eq!(unified.entity_type_code, 100);
        assert_eq!(unified.external_id, "1000");
        assert_eq!(unified.features, vec![1.0, 2.0]);
    }

    #[test]
    fn test_edge_conversion() {
        let edge = CrossLayerEdge {
            source_id: "ctrl_C001".to_string(),
            source_layer: HypergraphLayer::GovernanceControls,
            target_id: "acct_1000".to_string(),
            target_layer: HypergraphLayer::AccountingNetwork,
            edge_type: "ImplementsControl".to_string(),
            edge_type_code: 40,
            properties: HashMap::new(),
        };

        let unified = RawUnifiedEdge::from_cross_layer_edge(&edge);
        assert_eq!(unified.source, "ctrl_C001");
        assert_eq!(unified.target, "acct_1000");
        assert_eq!(unified.source_layer, 1); // GovernanceControls = 1
        assert_eq!(unified.target_layer, 3); // AccountingNetwork = 3
        assert_eq!(unified.edge_type, "ImplementsControl");
        assert_eq!(unified.edge_type_code, 40);
        assert_eq!(unified.weight, 1.0);
    }

    #[test]
    fn test_hyperedge_conversion() {
        let he = Hyperedge {
            id: "he_1".to_string(),
            hyperedge_type: "JournalEntry".to_string(),
            subtype: "R2R".to_string(),
            participants: vec![
                HyperedgeParticipant {
                    node_id: "acct_1000".to_string(),
                    role: "debit".to_string(),
                    weight: Some(500.0),
                },
                HyperedgeParticipant {
                    node_id: "acct_2000".to_string(),
                    role: "credit".to_string(),
                    weight: Some(500.0),
                },
            ],
            layer: HypergraphLayer::AccountingNetwork,
            properties: HashMap::new(),
            timestamp: Some(NaiveDate::from_ymd_opt(2024, 6, 15).unwrap()),
            is_anomaly: true,
            anomaly_type: Some("split_transaction".to_string()),
            features: vec![6.2, 1.0],
        };

        let unified = RawUnifiedHyperedge::from_hyperedge(&he);
        assert_eq!(unified.id, "he_1");
        assert_eq!(unified.hyperedge_type, "JournalEntry");
        assert_eq!(unified.layer, 3); // AccountingNetwork = 3
        assert_eq!(unified.member_ids, vec!["acct_1000", "acct_2000"]);
        assert_eq!(unified.participants.len(), 2);
        assert!(unified.is_anomaly);
        assert_eq!(unified.anomaly_type, Some("split_transaction".to_string()));
    }

    #[test]
    fn test_unified_export_creates_all_files() {
        let hypergraph = build_test_hypergraph();
        let dir = tempdir().unwrap();

        let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig::default());
        let metadata = exporter.export(&hypergraph, dir.path()).unwrap();

        assert!(dir.path().join("nodes.jsonl").exists());
        assert!(dir.path().join("edges.jsonl").exists());
        assert!(dir.path().join("hyperedges.jsonl").exists());
        assert!(dir.path().join("metadata.json").exists());

        assert_eq!(metadata.num_nodes, 22); // 5 components + 17 principles
        assert_eq!(metadata.format, "rustgraph_unified_v1");
    }

    #[test]
    fn test_unified_nodes_jsonl_parseable() {
        let hypergraph = build_test_hypergraph();
        let dir = tempdir().unwrap();

        let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig::default());
        exporter.export(&hypergraph, dir.path()).unwrap();

        let content = std::fs::read_to_string(dir.path().join("nodes.jsonl")).unwrap();
        let mut count = 0;
        for line in content.lines() {
            let node: RawUnifiedNode = serde_json::from_str(line).unwrap();
            assert!(!node.id.is_empty());
            assert!(!node.node_type.is_empty());
            assert!(!node.name.is_empty());
            // Layer should be u8, not string
            assert!(node.layer >= 1 && node.layer <= 3);
            count += 1;
        }
        assert_eq!(count, 22);
    }

    #[test]
    fn test_unified_edges_jsonl_uses_source_target() {
        let hypergraph = build_test_hypergraph();
        let dir = tempdir().unwrap();

        let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig::default());
        exporter.export(&hypergraph, dir.path()).unwrap();

        let content = std::fs::read_to_string(dir.path().join("edges.jsonl")).unwrap();
        for line in content.lines() {
            let edge: RawUnifiedEdge = serde_json::from_str(line).unwrap();
            // Verify unified field names work
            assert!(!edge.source.is_empty());
            assert!(!edge.target.is_empty());
            assert!(edge.source_layer >= 1 && edge.source_layer <= 3);
            assert!(edge.target_layer >= 1 && edge.target_layer <= 3);
            assert_eq!(edge.weight, 1.0);
        }
    }

    #[test]
    fn test_unified_metadata_has_format_field() {
        let hypergraph = build_test_hypergraph();
        let dir = tempdir().unwrap();

        let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig { pretty_print: true });
        exporter.export(&hypergraph, dir.path()).unwrap();

        let content = std::fs::read_to_string(dir.path().join("metadata.json")).unwrap();
        let metadata: UnifiedHypergraphMetadata = serde_json::from_str(&content).unwrap();
        assert_eq!(metadata.format, "rustgraph_unified_v1");
        assert_eq!(metadata.source, "datasynth");
    }

    #[cfg(feature = "rustgraph")]
    #[test]
    fn test_to_bulk_import_nodes() {
        let hypergraph = build_test_hypergraph();
        let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig::default());
        let export = exporter.to_bulk_import(&hypergraph);

        assert_eq!(export.nodes.len(), 22); // 5 components + 17 principles
        assert_eq!(export.id_map.len(), 22);

        // Verify first node has expected structure
        let first = &export.nodes[0];
        assert_eq!(first.id, Some(1)); // 1-based
        assert!(first.node_type > 0); // entity_type_code set
        assert!(first.layer.is_some());
        assert!(!first.labels.is_empty());
        // Properties should contain entity_id and node_type_name
        assert!(first.properties.contains_key("entity_id"));
        assert!(first.properties.contains_key("node_type_name"));
    }

    #[cfg(feature = "rustgraph")]
    #[test]
    fn test_to_bulk_import_edges() {
        let hypergraph = build_test_hypergraph();
        let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig::default());
        let export = exporter.to_bulk_import(&hypergraph);

        // COSO edges should exist
        assert!(!export.edges.is_empty());

        // All edge source/target should be valid u64 IDs in the id_map
        for edge in &export.edges {
            assert!(export.id_map.values().any(|&id| id == edge.source));
            assert!(export.id_map.values().any(|&id| id == edge.target));
            assert!(edge.properties.contains_key("edge_type_name"));
        }
    }

    #[cfg(feature = "rustgraph")]
    #[test]
    fn test_to_bulk_import_id_mapping() {
        let hypergraph = build_test_hypergraph();
        let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig::default());
        let export = exporter.to_bulk_import(&hypergraph);

        // All node IDs should be sequential starting at 1
        let mut ids: Vec<u64> = export.nodes.iter().filter_map(|n| n.id).collect();
        ids.sort();
        assert_eq!(ids.first(), Some(&1u64));
        assert_eq!(ids.last(), Some(&(export.nodes.len() as u64)));

        // id_map should match
        for node in &export.nodes {
            let string_id = node
                .properties
                .get("entity_id")
                .and_then(|v| v.as_str())
                .expect("entity_id should be a string");
            assert_eq!(export.id_map.get(string_id).copied(), node.id);
        }
    }

    #[test]
    fn test_export_to_writer() {
        let hypergraph = build_test_hypergraph();
        let mut buffer = Vec::new();

        let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig::default());
        let metadata = exporter.export_to_writer(&hypergraph, &mut buffer).unwrap();

        assert_eq!(metadata.num_nodes, 22);

        // Verify each line is valid JSONL with a _type field
        let content = String::from_utf8(buffer).unwrap();
        let mut node_count = 0;
        let mut edge_count = 0;
        for line in content.lines() {
            let obj: serde_json::Value = serde_json::from_str(line).unwrap();
            let record_type = obj.get("_type").unwrap().as_str().unwrap();
            match record_type {
                "node" => node_count += 1,
                "edge" => edge_count += 1,
                "hyperedge" => {}
                _ => panic!("Unexpected _type: {}", record_type),
            }
        }
        assert_eq!(node_count, 22);
        assert!(edge_count > 0); // COSO edges
    }
}