trustformers-debug 0.1.4

Advanced debugging tools for TrustformeRS models
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
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
//! Data export capabilities for debugging tools
//!
//! This module provides comprehensive data export functionality supporting
//! multiple formats including CSV, Excel, JSON, HDF5, and more.

use anyhow::Result;
use chrono::{DateTime, Utc};
use oxisql_sqlite_compat::blocking::SqliteConnectionBlocking;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use uuid::Uuid;

/// Data export manager for debugging tools
#[derive(Debug, Clone)]
pub struct DataExportManager {
    /// Export configuration
    config: ExportConfig,
    /// Active export jobs
    active_jobs: HashMap<Uuid, ExportJob>,
    /// Export history
    export_history: Vec<ExportRecord>,
    /// Supported formats
    supported_formats: Vec<ExportFormat>,
}

/// Export configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportConfig {
    /// Default export directory
    pub default_directory: String,
    /// Maximum file size (bytes)
    pub max_file_size: u64,
    /// Enable compression
    pub enable_compression: bool,
    /// Default format
    pub default_format: ExportFormat,
    /// Include metadata
    pub include_metadata: bool,
    /// Export templates
    pub templates: Vec<ExportTemplate>,
}

/// Export job tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportJob {
    /// Job identifier
    pub id: Uuid,
    /// Job name
    pub name: String,
    /// Export format
    pub format: ExportFormat,
    /// Output path
    pub output_path: String,
    /// Job status
    pub status: ExportStatus,
    /// Progress percentage
    pub progress: f64,
    /// Start time
    pub started_at: DateTime<Utc>,
    /// Completion time
    pub completed_at: Option<DateTime<Utc>>,
    /// Data size (bytes)
    pub data_size: u64,
    /// Error message (if failed)
    pub error_message: Option<String>,
    /// Export options
    pub options: ExportOptions,
}

/// Export record for history
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportRecord {
    /// Record identifier
    pub id: Uuid,
    /// Export job ID
    pub job_id: Uuid,
    /// Export timestamp
    pub timestamp: DateTime<Utc>,
    /// File path
    pub file_path: String,
    /// File size
    pub file_size: u64,
    /// Export format
    pub format: ExportFormat,
    /// Success status
    pub success: bool,
    /// Duration (seconds)
    pub duration: f64,
}

/// Export template for common configurations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportTemplate {
    /// Template identifier
    pub id: String,
    /// Template name
    pub name: String,
    /// Description
    pub description: String,
    /// Export format
    pub format: ExportFormat,
    /// Export options
    pub options: ExportOptions,
    /// Data filters
    pub filters: DataFilters,
    /// Template tags
    pub tags: Vec<String>,
}

/// Export options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportOptions {
    /// Include headers (for CSV/Excel)
    pub include_headers: bool,
    /// Date format
    pub date_format: String,
    /// Precision for floats
    pub float_precision: u32,
    /// Field separator (for CSV)
    pub separator: String,
    /// Compression level (0-9)
    pub compression_level: u32,
    /// Include metadata
    pub include_metadata: bool,
    /// Custom formatting options
    pub custom_options: HashMap<String, serde_json::Value>,
}

/// Data filters for selective export
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataFilters {
    /// Date range filter
    pub date_range: Option<DateRange>,
    /// Include specific data types
    pub data_types: Vec<DataType>,
    /// Exclude fields
    pub exclude_fields: Vec<String>,
    /// Include only fields
    pub include_fields: Option<Vec<String>>,
    /// Custom filters
    pub custom_filters: HashMap<String, serde_json::Value>,
}

/// Date range for filtering
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DateRange {
    /// Start date
    pub start: DateTime<Utc>,
    /// End date
    pub end: DateTime<Utc>,
}

/// Export formats supported
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Hash, Eq)]
pub enum ExportFormat {
    /// Comma-separated values
    Csv,
    /// Excel workbook
    Excel,
    /// JSON format
    Json,
    /// Pretty-printed JSON
    JsonPretty,
    /// HDF5 format
    Hdf5,
    /// Parquet format
    Parquet,
    /// XML format
    Xml,
    /// YAML format
    Yaml,
    /// SQLite database
    Sqlite,
    /// MessagePack
    MessagePack,
    /// Apache Arrow
    Arrow,
    /// Custom format
    Custom(String),
}

/// Export status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExportStatus {
    Pending,
    InProgress,
    Completed,
    Failed,
    Cancelled,
}

/// Data types that can be exported
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DataType {
    TensorData,
    GradientData,
    PerformanceMetrics,
    MemoryProfiles,
    ActivityLogs,
    AnnotationData,
    CommentData,
    ModelDiagnostics,
    TrainingDynamics,
    ArchitectureAnalysis,
    Custom(String),
}

/// Exportable data container
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportableData {
    /// Data identifier
    pub id: Uuid,
    /// Data name
    pub name: String,
    /// Data type
    pub data_type: DataType,
    /// Creation timestamp
    pub timestamp: DateTime<Utc>,
    /// Data content
    pub content: ExportDataContent,
    /// Metadata
    pub metadata: HashMap<String, serde_json::Value>,
    /// Data size
    pub size: u64,
}

/// Content of exportable data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExportDataContent {
    /// Tabular data
    Table(TableData),
    /// Time series data
    TimeSeries(TimeSeriesData),
    /// Key-value pairs
    KeyValue(HashMap<String, serde_json::Value>),
    /// Structured data
    Structured(serde_json::Value),
    /// Binary data
    Binary(Vec<u8>),
    /// Text data
    Text(String),
}

/// Tabular data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableData {
    /// Column headers
    pub headers: Vec<String>,
    /// Data rows
    pub rows: Vec<Vec<serde_json::Value>>,
    /// Column types
    pub column_types: HashMap<String, ColumnType>,
}

/// Time series data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimeSeriesData {
    /// Timestamps
    pub timestamps: Vec<DateTime<Utc>>,
    /// Data series
    pub series: HashMap<String, Vec<f64>>,
    /// Series metadata
    pub metadata: HashMap<String, String>,
}

/// Column data types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ColumnType {
    Integer,
    Float,
    String,
    Boolean,
    DateTime,
    Binary,
}

impl DataExportManager {
    /// Create a new data export manager
    pub fn new(config: ExportConfig) -> Self {
        let supported_formats = vec![
            ExportFormat::Csv,
            ExportFormat::Excel,
            ExportFormat::Json,
            ExportFormat::JsonPretty,
            ExportFormat::Xml,
            ExportFormat::Yaml,
            ExportFormat::Sqlite,
        ];

        Self {
            config,
            active_jobs: HashMap::new(),
            export_history: Vec::new(),
            supported_formats,
        }
    }

    /// Start an export job
    pub fn start_export(
        &mut self,
        name: String,
        data: Vec<ExportableData>,
        format: ExportFormat,
        output_path: String,
        options: ExportOptions,
    ) -> Result<Uuid> {
        let job_id = Uuid::new_v4();

        // Calculate total data size
        let data_size: u64 = data.iter().map(|d| d.size).sum();

        // Check file size limit
        if data_size > self.config.max_file_size {
            return Err(anyhow::anyhow!("Data size exceeds maximum file size limit"));
        }

        let job = ExportJob {
            id: job_id,
            name: name.clone(),
            format: format.clone(),
            output_path: output_path.clone(),
            status: ExportStatus::Pending,
            progress: 0.0,
            started_at: Utc::now(),
            completed_at: None,
            data_size,
            error_message: None,
            options: options.clone(),
        };

        self.active_jobs.insert(job_id, job);

        // Start the actual export process
        self.execute_export(job_id, data, options)?;

        Ok(job_id)
    }

    /// Execute the export process
    fn execute_export(
        &mut self,
        job_id: Uuid,
        data: Vec<ExportableData>,
        options: ExportOptions,
    ) -> Result<()> {
        // Extract job info to avoid multiple mutable borrows
        let (format, output_path) = {
            if let Some(job) = self.active_jobs.get_mut(&job_id) {
                job.status = ExportStatus::InProgress;
                (job.format.clone(), job.output_path.clone())
            } else {
                return Err(anyhow::anyhow!("Export job not found"));
            }
        };

        let result = match format {
            ExportFormat::Csv => self.export_csv(&data, &output_path, &options),
            ExportFormat::Json => self.export_json(&data, &output_path, &options),
            ExportFormat::JsonPretty => self.export_json_pretty(&data, &output_path, &options),
            ExportFormat::Excel => self.export_excel(&data, &output_path, &options),
            ExportFormat::Xml => self.export_xml(&data, &output_path, &options),
            ExportFormat::Yaml => self.export_yaml(&data, &output_path, &options),
            ExportFormat::Sqlite => self.export_sqlite(&data, &output_path, &options),
            // Binary/columnar formats that require optional external crates or services.
            // These are intentionally not implemented to keep the core dependency set
            // minimal.  Callers should use JSON or CSV as a universal fallback.
            ExportFormat::Hdf5 => Err(anyhow::anyhow!(
                "HDF5 export is not supported in this build. Use JSON or CSV instead."
            )),
            ExportFormat::Parquet => Err(anyhow::anyhow!(
                "Parquet export is not supported in this build. Use JSON or CSV instead."
            )),
            ExportFormat::MessagePack => Err(anyhow::anyhow!(
                "MessagePack export is not supported in this build. Use JSON instead."
            )),
            ExportFormat::Arrow => Err(anyhow::anyhow!(
                "Apache Arrow export is not supported in this build. Use JSON or CSV instead."
            )),
            ExportFormat::Custom(ref name) => Err(anyhow::anyhow!(
                "Custom export format '{}' is not registered. \
                 Register a handler or use one of the built-in formats.",
                name
            )),
        };

        // Update job status
        if let Some(job) = self.active_jobs.get_mut(&job_id) {
            match result {
                Ok(_) => {
                    job.status = ExportStatus::Completed;
                    job.progress = 100.0;
                    job.completed_at = Some(Utc::now());

                    // Add to history by cloning the job
                    let job_copy = job.clone();
                    self.add_export_record(&job_copy);
                },
                Err(e) => {
                    job.status = ExportStatus::Failed;
                    job.error_message = Some(e.to_string());
                },
            }
        }

        Ok(())
    }

    /// Export to CSV format
    fn export_csv(
        &mut self,
        data: &[ExportableData],
        output_path: &str,
        options: &ExportOptions,
    ) -> Result<()> {
        use std::fs::File;
        use std::io::Write;

        let mut file = File::create(output_path)?;

        for item in data {
            match &item.content {
                ExportDataContent::Table(table_data) => {
                    // Write headers
                    if options.include_headers {
                        let header_line = table_data.headers.join(&options.separator);
                        writeln!(file, "{}", header_line)?;
                    }

                    // Write data rows
                    for row in &table_data.rows {
                        let row_values: Vec<String> =
                            row.iter().map(|v| self.format_value_for_csv(v, options)).collect();
                        let row_line = row_values.join(&options.separator);
                        writeln!(file, "{}", row_line)?;
                    }
                },
                ExportDataContent::TimeSeries(ts_data) => {
                    // Write time series data
                    if options.include_headers {
                        let mut headers = vec!["timestamp".to_string()];
                        headers.extend(ts_data.series.keys().cloned());
                        let header_line = headers.join(&options.separator);
                        writeln!(file, "{}", header_line)?;
                    }

                    for (i, timestamp) in ts_data.timestamps.iter().enumerate() {
                        let mut row = vec![timestamp.format(&options.date_format).to_string()];
                        for series_name in ts_data.series.keys() {
                            if let Some(series) = ts_data.series.get(series_name) {
                                if let Some(value) = series.get(i) {
                                    row.push(format!(
                                        "{:.precision$}",
                                        value,
                                        precision = options.float_precision as usize
                                    ));
                                } else {
                                    row.push("".to_string());
                                }
                            }
                        }
                        let row_line = row.join(&options.separator);
                        writeln!(file, "{}", row_line)?;
                    }
                },
                _ => {
                    // Convert other formats to JSON and then to CSV-like representation
                    let json_str = serde_json::to_string(&item.content)?;
                    writeln!(file, "{}", json_str)?;
                },
            }
        }

        Ok(())
    }

    /// Export to JSON format
    fn export_json(
        &mut self,
        data: &[ExportableData],
        output_path: &str,
        _options: &ExportOptions,
    ) -> Result<()> {
        use std::fs::File;

        let file = File::create(output_path)?;
        serde_json::to_writer(file, data)?;
        Ok(())
    }

    /// Export to pretty JSON format
    fn export_json_pretty(
        &mut self,
        data: &[ExportableData],
        output_path: &str,
        _options: &ExportOptions,
    ) -> Result<()> {
        use std::fs::File;

        let file = File::create(output_path)?;
        serde_json::to_writer_pretty(file, data)?;
        Ok(())
    }

    /// Export to Excel (.xlsx) format as a real Office Open XML workbook
    fn export_excel(
        &mut self,
        data: &[ExportableData],
        output_path: &str,
        options: &ExportOptions,
    ) -> Result<()> {
        use oxiarc_archive::zip::ZipWriter;

        let rows = build_xlsx_rows(data, options)?;
        let sheet_xml = build_xlsx_sheet(&rows);

        let mut buffer: Vec<u8> = Vec::new();
        {
            let mut writer = ZipWriter::new(&mut buffer);
            writer
                .add_file("[Content_Types].xml", XLSX_CONTENT_TYPES.as_bytes())
                .map_err(|e| anyhow::anyhow!("xlsx: failed to write [Content_Types].xml: {e}"))?;
            writer
                .add_file("_rels/.rels", XLSX_ROOT_RELS.as_bytes())
                .map_err(|e| anyhow::anyhow!("xlsx: failed to write _rels/.rels: {e}"))?;
            writer
                .add_file("xl/workbook.xml", XLSX_WORKBOOK.as_bytes())
                .map_err(|e| anyhow::anyhow!("xlsx: failed to write xl/workbook.xml: {e}"))?;
            writer
                .add_file("xl/_rels/workbook.xml.rels", XLSX_WORKBOOK_RELS.as_bytes())
                .map_err(|e| {
                    anyhow::anyhow!("xlsx: failed to write xl/_rels/workbook.xml.rels: {e}")
                })?;
            writer.add_file("xl/worksheets/sheet1.xml", sheet_xml.as_bytes()).map_err(|e| {
                anyhow::anyhow!("xlsx: failed to write xl/worksheets/sheet1.xml: {e}")
            })?;
            writer
                .finish()
                .map_err(|e| anyhow::anyhow!("xlsx: failed to finalize workbook package: {e}"))?;
        }

        std::fs::write(output_path, &buffer)?;
        Ok(())
    }

    /// Export to XML format
    fn export_xml(
        &mut self,
        data: &[ExportableData],
        output_path: &str,
        _options: &ExportOptions,
    ) -> Result<()> {
        use std::fs::File;
        use std::io::Write;

        let mut file = File::create(output_path)?;

        writeln!(file, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")?;
        writeln!(file, "<export_data>")?;

        for item in data {
            writeln!(
                file,
                "  <data_item id=\"{}\" type=\"{:?}\">",
                item.id, item.data_type
            )?;
            writeln!(file, "    <name>{}</name>", item.name)?;
            writeln!(
                file,
                "    <timestamp>{}</timestamp>",
                item.timestamp.to_rfc3339()
            )?;
            writeln!(file, "    <size>{}</size>", item.size)?;

            // Convert content to XML (simplified)
            let content_json = serde_json::to_string(&item.content)?;
            writeln!(file, "    <content><![CDATA[{}]]></content>", content_json)?;

            writeln!(file, "  </data_item>")?;
        }

        writeln!(file, "</export_data>")?;
        Ok(())
    }

    /// Export to YAML format
    fn export_yaml(
        &mut self,
        data: &[ExportableData],
        output_path: &str,
        _options: &ExportOptions,
    ) -> Result<()> {
        use std::fs::File;

        let file = File::create(output_path)?;
        serde_json::to_writer_pretty(file, data)?;
        Ok(())
    }

    /// Export to a real SQLite database file.
    ///
    /// Uses the COOLJAPAN Pure-Rust `oxisql-sqlite-compat` backend (a C-free fork
    /// of Limbo) — never `libsqlite3`/`rusqlite`. Each [`ExportableData`] item is
    /// written into its own table:
    ///
    /// * [`ExportDataContent::Table`] → a table with one column per header,
    ///   with SQL column types taken from the explicit `column_types` map or
    ///   inferred from the data (`INTEGER` / `REAL` / `TEXT`).
    /// * [`ExportDataContent::TimeSeries`] → a table with a `timestamp` column
    ///   plus one `REAL` column per series.
    /// * Any other content → a single-column `content TEXT` table holding the
    ///   JSON serialization so nothing is silently dropped.
    fn export_sqlite(
        &mut self,
        data: &[ExportableData],
        output_path: &str,
        options: &ExportOptions,
    ) -> Result<()> {
        // Create the database file fresh so the export is deterministic.
        if std::path::Path::new(output_path).exists() {
            std::fs::remove_file(output_path).map_err(|e| {
                anyhow::anyhow!("failed to clear existing SQLite file '{output_path}': {e}")
            })?;
        }

        let conn = SqliteConnectionBlocking::open(output_path)
            .map_err(|e| anyhow::anyhow!("failed to open SQLite database '{output_path}': {e}"))?;

        let mut used_names: HashSet<String> = HashSet::new();
        for (index, item) in data.iter().enumerate() {
            let table_name = unique_table_name(&item.name, index, &mut used_names);
            match &item.content {
                ExportDataContent::Table(table) => {
                    write_sqlite_table(
                        &conn,
                        &table_name,
                        &table.headers,
                        &table.rows,
                        &table.column_types,
                    )?;
                },
                ExportDataContent::TimeSeries(ts) => {
                    write_sqlite_timeseries(&conn, &table_name, ts, options)?;
                },
                other => {
                    let json = serde_json::to_string(other)?;
                    conn.execute(
                        &format!("CREATE TABLE IF NOT EXISTS \"{table_name}\" (content TEXT)"),
                        &[],
                    )
                    .map_err(|e| anyhow::anyhow!("CREATE TABLE '{table_name}' failed: {e}"))?;
                    conn.execute(
                        &format!(
                            "INSERT INTO \"{table_name}\" (content) VALUES ({})",
                            quote_sql_string(&json)
                        ),
                        &[],
                    )
                    .map_err(|e| anyhow::anyhow!("INSERT into '{table_name}' failed: {e}"))?;
                },
            }
        }

        Ok(())
    }

    /// Helper function to format values for CSV
    fn format_value_for_csv(&self, value: &serde_json::Value, options: &ExportOptions) -> String {
        match value {
            serde_json::Value::Number(n) => {
                if let Some(f) = n.as_f64() {
                    format!(
                        "{:.precision$}",
                        f,
                        precision = options.float_precision as usize
                    )
                } else {
                    n.to_string()
                }
            },
            serde_json::Value::String(s) => {
                // Escape quotes and commas
                if s.contains(',') || s.contains('"') || s.contains('\n') {
                    format!("\"{}\"", s.replace('"', "\"\""))
                } else {
                    s.clone()
                }
            },
            _ => value.to_string(),
        }
    }

    /// Add export record to history
    fn add_export_record(&mut self, job: &ExportJob) {
        let record = ExportRecord {
            id: Uuid::new_v4(),
            job_id: job.id,
            timestamp: Utc::now(),
            file_path: job.output_path.clone(),
            file_size: job.data_size,
            format: job.format.clone(),
            success: matches!(job.status, ExportStatus::Completed),
            duration: job
                .completed_at
                .map(|end| (end - job.started_at).num_milliseconds() as f64 / 1000.0)
                .unwrap_or(0.0),
        };

        self.export_history.push(record);
    }

    /// Get export job status
    pub fn get_job_status(&self, job_id: Uuid) -> Option<&ExportJob> {
        self.active_jobs.get(&job_id)
    }

    /// Get export history
    pub fn get_export_history(&self) -> &[ExportRecord] {
        &self.export_history
    }

    /// Create export template
    pub fn create_template(
        &mut self,
        name: String,
        description: String,
        format: ExportFormat,
        options: ExportOptions,
        filters: DataFilters,
        tags: Vec<String>,
    ) -> String {
        let template_id = Uuid::new_v4().to_string();

        let template = ExportTemplate {
            id: template_id.clone(),
            name,
            description,
            format,
            options,
            filters,
            tags,
        };

        self.config.templates.push(template);
        template_id
    }

    /// Apply export template
    pub fn apply_template(
        &self,
        template_id: &str,
    ) -> Option<(&ExportFormat, &ExportOptions, &DataFilters)> {
        self.config
            .templates
            .iter()
            .find(|t| t.id == template_id)
            .map(|t| (&t.format, &t.options, &t.filters))
    }

    /// Get supported formats
    pub fn get_supported_formats(&self) -> &[ExportFormat] {
        &self.supported_formats
    }

    /// Cancel export job
    pub fn cancel_job(&mut self, job_id: Uuid) -> Result<()> {
        if let Some(job) = self.active_jobs.get_mut(&job_id) {
            if matches!(job.status, ExportStatus::Pending | ExportStatus::InProgress) {
                job.status = ExportStatus::Cancelled;
                Ok(())
            } else {
                Err(anyhow::anyhow!("Job cannot be cancelled in current status"))
            }
        } else {
            Err(anyhow::anyhow!("Job not found"))
        }
    }

    /// Get export statistics
    pub fn get_export_statistics(&self) -> ExportStatistics {
        let total_exports = self.export_history.len();
        let successful_exports = self.export_history.iter().filter(|r| r.success).count();
        let total_size: u64 = self.export_history.iter().map(|r| r.file_size).sum();
        let avg_duration = if total_exports > 0 {
            self.export_history.iter().map(|r| r.duration).sum::<f64>() / total_exports as f64
        } else {
            0.0
        };

        let format_stats: HashMap<ExportFormat, usize> =
            self.export_history.iter().fold(HashMap::new(), |mut acc, record| {
                *acc.entry(record.format.clone()).or_insert(0) += 1;
                acc
            });

        ExportStatistics {
            total_exports,
            successful_exports,
            failed_exports: total_exports - successful_exports,
            total_size_bytes: total_size,
            average_duration_seconds: avg_duration,
            format_statistics: format_stats,
            active_jobs: self.active_jobs.len(),
        }
    }
}

/// OOXML `[Content_Types].xml` part declaring the package content types.
const XLSX_CONTENT_TYPES: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>"#;

/// OOXML `_rels/.rels` package-level relationships part.
const XLSX_ROOT_RELS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#;

/// OOXML `xl/workbook.xml` part defining a single worksheet.
const XLSX_WORKBOOK: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>"#;

/// OOXML `xl/_rels/workbook.xml.rels` part linking the workbook to its worksheet.
const XLSX_WORKBOOK_RELS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"#;

/// A single spreadsheet cell value to emit into a worksheet.
enum XlsxCell {
    /// Inline (shared-string-free) text cell, emitted as `<c t="inlineStr">`.
    Inline(String),
    /// Numeric cell, emitted as `<c><v>..</v></c>` with the pre-formatted literal.
    Number(String),
    /// Empty placeholder cell.
    Empty,
}

/// XML-escape `&`, `<`, `>`, `"`, `'` for safe inclusion in OOXML parts.
fn xlsx_xml_escape(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            _ => out.push(ch),
        }
    }
    out
}

/// Convert a zero-based column index to an Excel column name (0 -> "A", 26 -> "AA").
fn xlsx_column_name(index: usize) -> String {
    let mut n = index + 1;
    let mut name = String::new();
    while n > 0 {
        let rem = (n - 1) % 26;
        name.insert(0, (b'A' + rem as u8) as char);
        n = (n - 1) / 26;
    }
    name
}

/// Map a JSON value to a worksheet cell, mirroring `format_value_for_csv` numeric rules.
fn xlsx_value_to_cell(value: &serde_json::Value, options: &ExportOptions) -> XlsxCell {
    match value {
        serde_json::Value::Number(n) => {
            if let Some(f) = n.as_f64() {
                XlsxCell::Number(format!(
                    "{:.precision$}",
                    f,
                    precision = options.float_precision as usize
                ))
            } else {
                XlsxCell::Number(n.to_string())
            }
        },
        serde_json::Value::String(s) => XlsxCell::Inline(s.clone()),
        _ => XlsxCell::Inline(value.to_string()),
    }
}

/// Build the worksheet rows from the export data, mirroring `export_csv` layout.
fn build_xlsx_rows(data: &[ExportableData], options: &ExportOptions) -> Result<Vec<Vec<XlsxCell>>> {
    let mut rows: Vec<Vec<XlsxCell>> = Vec::new();
    for item in data {
        match &item.content {
            ExportDataContent::Table(table_data) => {
                if options.include_headers {
                    rows.push(
                        table_data.headers.iter().map(|h| XlsxCell::Inline(h.clone())).collect(),
                    );
                }
                for row in &table_data.rows {
                    rows.push(row.iter().map(|v| xlsx_value_to_cell(v, options)).collect());
                }
            },
            ExportDataContent::TimeSeries(ts_data) => {
                if options.include_headers {
                    let mut header = vec![XlsxCell::Inline("timestamp".to_string())];
                    header.extend(ts_data.series.keys().map(|k| XlsxCell::Inline(k.clone())));
                    rows.push(header);
                }
                for (i, timestamp) in ts_data.timestamps.iter().enumerate() {
                    let mut cells = vec![XlsxCell::Inline(
                        timestamp.format(&options.date_format).to_string(),
                    )];
                    for series_name in ts_data.series.keys() {
                        if let Some(series) = ts_data.series.get(series_name) {
                            if let Some(value) = series.get(i) {
                                cells.push(XlsxCell::Number(format!(
                                    "{:.precision$}",
                                    value,
                                    precision = options.float_precision as usize
                                )));
                            } else {
                                cells.push(XlsxCell::Empty);
                            }
                        }
                    }
                    rows.push(cells);
                }
            },
            _ => {
                let json_str = serde_json::to_string(&item.content)?;
                rows.push(vec![XlsxCell::Inline(json_str)]);
            },
        }
    }
    Ok(rows)
}

/// Render worksheet rows into the `xl/worksheets/sheet1.xml` OOXML part.
fn build_xlsx_sheet(rows: &[Vec<XlsxCell>]) -> String {
    let mut sheet = String::new();
    sheet.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
    sheet.push_str(
        "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">",
    );
    sheet.push_str("<sheetData>");
    for (row_idx, row) in rows.iter().enumerate() {
        let row_num = row_idx + 1;
        sheet.push_str(&format!("<row r=\"{row_num}\">"));
        for (col_idx, cell) in row.iter().enumerate() {
            let cell_ref = format!("{}{row_num}", xlsx_column_name(col_idx));
            match cell {
                XlsxCell::Inline(text) => {
                    sheet.push_str(&format!(
                        "<c r=\"{cell_ref}\" t=\"inlineStr\"><is><t xml:space=\"preserve\">{}</t></is></c>",
                        xlsx_xml_escape(text)
                    ));
                },
                XlsxCell::Number(num) => {
                    sheet.push_str(&format!("<c r=\"{cell_ref}\"><v>{num}</v></c>"));
                },
                XlsxCell::Empty => {
                    sheet.push_str(&format!("<c r=\"{cell_ref}\"/>"));
                },
            }
        }
        sheet.push_str("</row>");
    }
    sheet.push_str("</sheetData></worksheet>");
    sheet
}

// ── SQLite export helpers ───────────────────────────────────────────────────────

/// Sanitize an arbitrary name into a safe, double-quotable SQL identifier.
///
/// Non-alphanumeric characters become `_`; a leading non-alphabetic character is
/// prefixed so the identifier is always valid.
fn sanitize_sql_identifier(name: &str) -> String {
    let mut sanitized: String = name
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' })
        .collect();
    let needs_prefix = sanitized
        .chars()
        .next()
        .map(|c| !(c.is_ascii_alphabetic() || c == '_'))
        .unwrap_or(true);
    if needs_prefix {
        sanitized = format!("t_{sanitized}");
    }
    sanitized
}

/// Produce a collision-free table name for the export, recording it in `used`.
fn unique_table_name(name: &str, index: usize, used: &mut HashSet<String>) -> String {
    let base = sanitize_sql_identifier(name);
    if used.insert(base.clone()) {
        return base;
    }
    let candidate = format!("{base}_{index}");
    used.insert(candidate.clone());
    candidate
}

/// Quote and escape a string for use as a SQL string literal.
fn quote_sql_string(value: &str) -> String {
    format!("'{}'", value.replace('\'', "''"))
}

/// Convert a single JSON value into an inline SQL literal.
///
/// * `null`  → `NULL`
/// * `bool`  → `1` / `0` (SQLite has no native boolean)
/// * number  → verbatim numeric literal
/// * string  → single-quote-escaped string literal
/// * array / object → JSON text stored as a string literal
fn json_value_to_sql_literal(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Null => "NULL".to_string(),
        serde_json::Value::Bool(b) => if *b { "1" } else { "0" }.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => quote_sql_string(s),
        other => quote_sql_string(&other.to_string()),
    }
}

/// Infer a SQL column affinity (`INTEGER` / `REAL` / `TEXT`) from the data in a
/// column when no explicit [`ColumnType`] is supplied.
fn infer_sql_column_type(rows: &[Vec<serde_json::Value>], col: usize) -> &'static str {
    let mut integers = 0usize;
    let mut floats = 0usize;
    let mut bools = 0usize;
    let mut others = 0usize;
    for row in rows {
        match row.get(col) {
            None | Some(serde_json::Value::Null) => {},
            Some(serde_json::Value::Number(n)) => {
                if n.is_i64() || n.is_u64() {
                    integers += 1;
                } else {
                    floats += 1;
                }
            },
            Some(serde_json::Value::Bool(_)) => bools += 1,
            Some(_) => others += 1,
        }
    }
    if others > 0 {
        "TEXT"
    } else if floats > 0 {
        "REAL"
    } else if integers > 0 || bools > 0 {
        "INTEGER"
    } else {
        "TEXT"
    }
}

/// Map an explicit [`ColumnType`] to its SQL affinity.
fn column_type_to_sql(column_type: &ColumnType) -> &'static str {
    match column_type {
        ColumnType::Integer | ColumnType::Boolean => "INTEGER",
        ColumnType::Float => "REAL",
        ColumnType::Binary => "BLOB",
        ColumnType::String | ColumnType::DateTime => "TEXT",
    }
}

/// Create and populate a SQLite table from [`TableData`].
fn write_sqlite_table(
    conn: &SqliteConnectionBlocking,
    table_name: &str,
    headers: &[String],
    rows: &[Vec<serde_json::Value>],
    column_types: &HashMap<String, ColumnType>,
) -> Result<()> {
    if headers.is_empty() {
        return Ok(());
    }

    let column_idents: Vec<String> = headers.iter().map(|h| sanitize_sql_identifier(h)).collect();
    let column_defs: Vec<String> = headers
        .iter()
        .enumerate()
        .map(|(idx, header)| {
            let sql_type = column_types
                .get(header)
                .map(column_type_to_sql)
                .unwrap_or_else(|| infer_sql_column_type(rows, idx));
            format!("\"{}\" {}", column_idents[idx], sql_type)
        })
        .collect();

    let create = format!(
        "CREATE TABLE IF NOT EXISTS \"{table_name}\" ({})",
        column_defs.join(", ")
    );
    conn.execute(&create, &[])
        .map_err(|e| anyhow::anyhow!("CREATE TABLE '{table_name}' failed: {e}"))?;

    let column_list =
        column_idents.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");

    for row in rows {
        let values: Vec<String> = (0..headers.len())
            .map(|idx| match row.get(idx) {
                Some(value) => json_value_to_sql_literal(value),
                None => "NULL".to_string(),
            })
            .collect();
        let insert = format!(
            "INSERT INTO \"{table_name}\" ({column_list}) VALUES ({})",
            values.join(", ")
        );
        conn.execute(&insert, &[])
            .map_err(|e| anyhow::anyhow!("INSERT into '{table_name}' failed: {e}"))?;
    }

    Ok(())
}

/// Create and populate a SQLite table from [`TimeSeriesData`].
fn write_sqlite_timeseries(
    conn: &SqliteConnectionBlocking,
    table_name: &str,
    ts: &TimeSeriesData,
    options: &ExportOptions,
) -> Result<()> {
    // Deterministic series ordering.
    let mut series_names: Vec<String> = ts.series.keys().cloned().collect();
    series_names.sort();

    let mut column_defs = vec!["\"timestamp\" TEXT".to_string()];
    for name in &series_names {
        column_defs.push(format!("\"{}\" REAL", sanitize_sql_identifier(name)));
    }
    let create = format!(
        "CREATE TABLE IF NOT EXISTS \"{table_name}\" ({})",
        column_defs.join(", ")
    );
    conn.execute(&create, &[])
        .map_err(|e| anyhow::anyhow!("CREATE TABLE '{table_name}' failed: {e}"))?;

    let mut column_list = vec!["\"timestamp\"".to_string()];
    for name in &series_names {
        column_list.push(format!("\"{}\"", sanitize_sql_identifier(name)));
    }
    let column_list = column_list.join(", ");

    for (i, timestamp) in ts.timestamps.iter().enumerate() {
        let mut values = vec![quote_sql_string(
            &timestamp.format(&options.date_format).to_string(),
        )];
        for name in &series_names {
            match ts.series.get(name).and_then(|series| series.get(i)) {
                Some(value) => values.push(value.to_string()),
                None => values.push("NULL".to_string()),
            }
        }
        let insert = format!(
            "INSERT INTO \"{table_name}\" ({column_list}) VALUES ({})",
            values.join(", ")
        );
        conn.execute(&insert, &[])
            .map_err(|e| anyhow::anyhow!("INSERT into '{table_name}' failed: {e}"))?;
    }

    Ok(())
}

/// Export statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportStatistics {
    pub total_exports: usize,
    pub successful_exports: usize,
    pub failed_exports: usize,
    pub total_size_bytes: u64,
    pub average_duration_seconds: f64,
    pub format_statistics: HashMap<ExportFormat, usize>,
    pub active_jobs: usize,
}

impl Default for ExportConfig {
    fn default() -> Self {
        Self {
            default_directory: "./exports".to_string(),
            max_file_size: 1024 * 1024 * 1024, // 1GB
            enable_compression: true,
            default_format: ExportFormat::Json,
            include_metadata: true,
            templates: Vec::new(),
        }
    }
}

impl Default for ExportOptions {
    fn default() -> Self {
        Self {
            include_headers: true,
            date_format: "%Y-%m-%d %H:%M:%S UTC".to_string(),
            float_precision: 6,
            separator: ",".to_string(),
            compression_level: 6,
            include_metadata: true,
            custom_options: HashMap::new(),
        }
    }
}

impl Default for DataFilters {
    fn default() -> Self {
        Self {
            date_range: None,
            data_types: vec![
                DataType::TensorData,
                DataType::GradientData,
                DataType::PerformanceMetrics,
            ],
            exclude_fields: Vec::new(),
            include_fields: None,
            custom_filters: HashMap::new(),
        }
    }
}

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

    // These values are test data, not approximations of mathematical constants
    #[allow(clippy::approx_constant)]
    fn create_test_data() -> Vec<ExportableData> {
        let table_data = TableData {
            headers: vec![
                "id".to_string(),
                "value".to_string(),
                "timestamp".to_string(),
            ],
            rows: vec![
                vec![
                    serde_json::Value::Number(serde_json::Number::from(1)),
                    serde_json::Value::Number(
                        serde_json::Number::from_f64(3.14).expect("operation failed in test"),
                    ),
                    serde_json::Value::String("2023-01-01T12:00:00Z".to_string()),
                ],
                vec![
                    serde_json::Value::Number(serde_json::Number::from(2)),
                    serde_json::Value::Number(
                        serde_json::Number::from_f64(2.71).expect("operation failed in test"),
                    ),
                    serde_json::Value::String("2023-01-01T12:01:00Z".to_string()),
                ],
            ],
            column_types: HashMap::new(),
        };

        vec![ExportableData {
            id: Uuid::new_v4(),
            name: "Test Data".to_string(),
            data_type: DataType::TensorData,
            timestamp: Utc::now(),
            content: ExportDataContent::Table(table_data),
            metadata: HashMap::new(),
            size: 1024,
        }]
    }

    #[test]
    fn test_export_manager_creation() {
        let config = ExportConfig::default();
        let manager = DataExportManager::new(config);

        assert!(manager.get_supported_formats().contains(&ExportFormat::Json));
        assert!(manager.get_supported_formats().contains(&ExportFormat::Csv));
    }

    #[test]
    fn test_csv_export() {
        let config = ExportConfig::default();
        let mut manager = DataExportManager::new(config);
        let test_data = create_test_data();

        let temp_dir = tempdir().expect("temp file creation failed");
        let output_path = temp_dir.path().join("test.csv").to_string_lossy().to_string();

        let job_id = manager
            .start_export(
                "Test CSV Export".to_string(),
                test_data,
                ExportFormat::Csv,
                output_path.clone(),
                ExportOptions::default(),
            )
            .expect("operation failed in test");

        // Check job was created
        assert!(manager.active_jobs.contains_key(&job_id));

        // Check file was created
        assert!(std::path::Path::new(&output_path).exists());
    }

    #[test]
    fn test_json_export() {
        let config = ExportConfig::default();
        let mut manager = DataExportManager::new(config);
        let test_data = create_test_data();

        let temp_dir = tempdir().expect("temp file creation failed");
        let output_path = temp_dir.path().join("test.json").to_string_lossy().to_string();

        let job_id = manager
            .start_export(
                "Test JSON Export".to_string(),
                test_data,
                ExportFormat::Json,
                output_path.clone(),
                ExportOptions::default(),
            )
            .expect("operation failed in test");

        assert!(manager.active_jobs.contains_key(&job_id));
        assert!(std::path::Path::new(&output_path).exists());
    }

    #[test]
    fn test_export_template() {
        let config = ExportConfig::default();
        let mut manager = DataExportManager::new(config);

        let template_id = manager.create_template(
            "CSV Template".to_string(),
            "Standard CSV export".to_string(),
            ExportFormat::Csv,
            ExportOptions::default(),
            DataFilters::default(),
            vec!["csv".to_string(), "standard".to_string()],
        );

        let (format, options, _filters) =
            manager.apply_template(&template_id).expect("temp file creation failed");
        assert_eq!(*format, ExportFormat::Csv);
        assert!(options.include_headers);
    }

    #[test]
    fn test_export_statistics() {
        let config = ExportConfig::default();
        let mut manager = DataExportManager::new(config);

        // Add some mock export records
        manager.export_history.push(ExportRecord {
            id: Uuid::new_v4(),
            job_id: Uuid::new_v4(),
            timestamp: Utc::now(),
            file_path: "test1.csv".to_string(),
            file_size: 1024,
            format: ExportFormat::Csv,
            success: true,
            duration: 2.5,
        });

        manager.export_history.push(ExportRecord {
            id: Uuid::new_v4(),
            job_id: Uuid::new_v4(),
            timestamp: Utc::now(),
            file_path: "test2.json".to_string(),
            file_size: 2048,
            format: ExportFormat::Json,
            success: true,
            duration: 1.8,
        });

        let stats = manager.get_export_statistics();
        assert_eq!(stats.total_exports, 2);
        assert_eq!(stats.successful_exports, 2);
        assert_eq!(stats.total_size_bytes, 3072);
    }

    #[test]
    fn test_excel_export_roundtrip() {
        use oxiarc_archive::zip::ZipReader;
        use std::io::Cursor;

        let config = ExportConfig::default();
        let mut manager = DataExportManager::new(config);
        let test_data = create_test_data();

        let file_name = format!("trustformers_xlsx_test_{}.xlsx", Uuid::new_v4());
        let output_path = std::env::temp_dir().join(file_name).to_string_lossy().to_string();

        manager
            .start_export(
                "Test Excel Export".to_string(),
                test_data,
                ExportFormat::Excel,
                output_path.clone(),
                ExportOptions::default(),
            )
            .expect("excel export should succeed");

        assert!(std::path::Path::new(&output_path).exists());

        let bytes = std::fs::read(&output_path).expect("read xlsx bytes");
        let mut reader = ZipReader::new(Cursor::new(bytes)).expect("open xlsx as zip");
        let entries = reader.entries().to_vec();
        let names: Vec<String> = entries.iter().map(|e| e.name.clone()).collect();

        assert!(
            names.iter().any(|n| n == "[Content_Types].xml"),
            "missing [Content_Types].xml; entries = {names:?}"
        );
        assert!(
            names.iter().any(|n| n == "xl/workbook.xml"),
            "missing xl/workbook.xml; entries = {names:?}"
        );
        assert!(
            names.iter().any(|n| n == "xl/worksheets/sheet1.xml"),
            "missing xl/worksheets/sheet1.xml; entries = {names:?}"
        );

        let sheet_entry = entries
            .iter()
            .find(|e| e.name == "xl/worksheets/sheet1.xml")
            .expect("sheet1.xml entry");
        let sheet_bytes = reader.extract(sheet_entry).expect("extract sheet1.xml");
        let sheet_xml = String::from_utf8(sheet_bytes).expect("sheet1.xml is utf8");

        assert!(sheet_xml.contains("<worksheet"));
        // Header text from create_test_data(): "id", "value", "timestamp".
        assert!(sheet_xml.contains("id"), "sheet missing header text");
        assert!(sheet_xml.contains("value"), "sheet missing header text");
        assert!(sheet_xml.contains("timestamp"), "sheet missing header text");

        let _ = std::fs::remove_file(&output_path);
    }

    #[test]
    // 3.14 is test data from create_test_data(), not an approximation of PI.
    #[allow(clippy::approx_constant)]
    fn test_sqlite_export_roundtrip() {
        let config = ExportConfig::default();
        let mut manager = DataExportManager::new(config);
        let test_data = create_test_data();

        let file_name = format!("trustformers_sqlite_test_{}.sqlite3", Uuid::new_v4());
        let output_path = std::env::temp_dir().join(file_name).to_string_lossy().to_string();

        let job_id = manager
            .start_export(
                "Test SQLite Export".to_string(),
                test_data,
                ExportFormat::Sqlite,
                output_path.clone(),
                ExportOptions::default(),
            )
            .expect("sqlite export should succeed");

        // The job must have completed (not silently failed back to JSON).
        let status = manager.get_job_status(job_id).expect("job should exist");
        assert!(
            matches!(status.status, ExportStatus::Completed),
            "export status = {:?}",
            status.status
        );
        assert!(
            std::path::Path::new(&output_path).exists(),
            "sqlite file should exist"
        );

        // Re-open the real SQLite file and read the rows back.
        let conn = SqliteConnectionBlocking::open(&output_path).expect("open sqlite file");
        let tables = conn.tables().expect("list tables");
        assert!(!tables.is_empty(), "expected at least one table");

        // create_test_data() names the item "Test Data" -> sanitized "Test_Data".
        let rows = conn
            .query(
                "SELECT \"id\", \"value\", \"timestamp\" FROM \"Test_Data\"",
                &[],
            )
            .expect("query rows back");
        assert_eq!(rows.len(), 2, "two rows should persist");

        // Collect ids to verify both rows persisted regardless of row order.
        let mut ids: Vec<i64> = rows
            .iter()
            .map(|r| r.try_get::<i64>("id").expect("id column is INTEGER"))
            .collect();
        ids.sort_unstable();
        assert_eq!(ids, vec![1, 2]);

        // Find the row with id == 1 and verify the float + string columns.
        let first = rows
            .iter()
            .find(|r| r.try_get::<i64>("id").map(|v| v == 1).unwrap_or(false))
            .expect("row with id=1");
        let value: f64 = first.try_get("value").expect("value column is REAL");
        assert!((value - 3.14).abs() < 1e-9, "value = {value}");
        let timestamp: String = first.try_get("timestamp").expect("timestamp column is TEXT");
        assert_eq!(timestamp, "2023-01-01T12:00:00Z");

        let _ = std::fs::remove_file(&output_path);
    }
}