oxirs 0.2.4

Command-line interface for OxiRS - import, export, migration, and benchmarking tools
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
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
//! # OxiRS CLI Tool
//!
//! [![Version](https://img.shields.io/badge/version-0.2.4-blue)](https://github.com/cool-japan/oxirs/releases)
//! [![docs.rs](https://docs.rs/oxirs/badge.svg)](https://docs.rs/oxirs)
//!
//! **Status**: Production Release (v0.2.4)
//! **Stability**: Public APIs are stable. Production-ready with comprehensive testing.
//!
//! Command-line interface for OxiRS providing import, export, SPARQL queries,
//! benchmarking, and server management tools.
//!
//! ## Features
//!
//! - ✅ **Persistent RDF Storage**: Data automatically saved to disk in N-Quads format
//! - ✅ **SPARQL Queries**: Support for SELECT, ASK, CONSTRUCT, and DESCRIBE queries
//! - ✅ **Multi-format Import/Export**: Turtle, N-Triples, RDF/XML, JSON-LD, N-Quads, TriG
//! - ✅ **Interactive REPL**: Explore RDF data interactively
//! - 🚧 **Prefix Support**: Coming soon in next release
//!
//! ## Commands
//!
//! ### Core RDF Operations
//! - `init`: Initialize a new knowledge graph dataset
//! - `import`: Import RDF data from various formats (data persisted automatically)
//! - `query`: Execute SPARQL queries (SELECT, ASK, CONSTRUCT, DESCRIBE)
//! - `export`: Export RDF data to various formats
//! - `interactive`: Interactive REPL for SPARQL queries
//! - `serve`: Start the OxiRS SPARQL server
//! - `benchmark`: Run performance benchmarks
//!
//! ### Phase D: Industrial Connectivity
//! - `tsdb`: Time-series database operations with SPARQL temporal extensions
//! - `modbus`: Modbus TCP/RTU monitoring and RDF mapping
//! - `canbus`: CANbus/J1939 monitoring, DBC parsing, SAMM generation
//!
//! ### Storage Tools
//! - `tdbloader`, `tdbquery`, `tdbstats`, `tdbbackup`, `tdbcompact`
//!
//! ### Validation Tools
//! - `shacl`: SHACL shape validation
//! - `shex`: ShEx validation
//! - `infer`: Reasoning and inference
//!
//! ### SAMM/AAS Tools (Java ESMF SDK compatible)
//! - `aspect`: SAMM Aspect Model tools
//! - `aas`: Asset Administration Shell tools
//! - `package`: Package management
//!
//! ### Advanced Tools
//! - `graph-analytics`: RDF graph analytics using scirs2-graph
//! - Various utilities: `arq`, `riot`, `rdfcat`, etc.
//!
//! ## Quick Start
//!
//! ```bash
//! # 1. Initialize a new dataset
//! oxirs init mykg
//!
//! # 2. Import RDF data (automatically persisted to mykg/data.nq)
//! oxirs import mykg data.ttl --format turtle
//!
//! # 3. Query the data (data loaded from disk automatically)
//! oxirs query mykg "SELECT * WHERE { ?s ?p ?o } LIMIT 10"
//!
//! # 4. Query with specific patterns
//! oxirs query mykg "SELECT ?name WHERE { ?person <http://example.org/name> ?name }"
//!
//! # 5. Start SPARQL server
//! oxirs serve mykg/oxirs.toml --port 3030
//! ```
//!
//! ## Dataset Name Rules
//!
//! Dataset names must follow these rules:
//! - Only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens (-)
//! - No dots (.), slashes (/), or other special characters
//! - Maximum length: 255 characters
//! - Cannot be empty
//!
//! Valid examples: `mykg`, `my_dataset`, `test-data-2024`
//! Invalid examples: `dataset.oxirs`, `my/data`, `data.ttl`
//!
//! ## SPARQL Query Examples
//!
//! ```bash
//! # Get all triples
//! oxirs query mykg "SELECT ?s ?p ?o WHERE { ?s ?p ?o }"
//!
//! # Filter by type
//! oxirs query mykg "SELECT ?s WHERE {
//!   ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://example.org/Person>
//! }"
//!
//! # ASK query (returns true/false)
//! oxirs query mykg "ASK { ?s <http://example.org/age> \"30\" }"
//!
//! # CONSTRUCT new triples
//! oxirs query mykg "CONSTRUCT { ?s <http://example.org/hasName> ?name }
//!                   WHERE { ?s <http://example.org/name> ?name }"
//! ```
//!
//! ## Phase D: Industrial Connectivity Examples (0.2.4)
//!
//! ### Time-Series Operations
//! ```bash
//! # Query time-series with aggregation
//! oxirs tsdb query mykg --series 1 --start 2026-01-01T00:00:00Z --end 2026-01-31T23:59:59Z --aggregate avg
//!
//! # Insert data point
//! oxirs tsdb insert mykg --series 1 --value 22.5
//!
//! # Show compression statistics
//! oxirs tsdb stats mykg --detailed
//!
//! # Export to CSV
//! oxirs tsdb export mykg --series 1 --output data.csv --format csv
//! ```
//!
//! ### Modbus Operations
//! ```bash
//! # Monitor Modbus TCP device (real-time)
//! oxirs modbus monitor-tcp --address 192.168.1.100:502 --start 40001 --count 10 --interval 1000
//!
//! # Read registers
//! oxirs modbus read --device 192.168.1.100:502 --address 40001 --count 5 --datatype float32
//!
//! # Generate RDF from Modbus data
//! oxirs modbus to-rdf --device 192.168.1.100:502 --config modbus_map.toml --output data.ttl
//!
//! # Start mock server for testing
//! oxirs modbus mock-server --port 5020
//! ```
//!
//! ### CANbus Operations
//! ```bash
//! # Monitor CAN interface
//! oxirs canbus monitor --interface can0 --dbc vehicle.dbc --j1939
//!
//! # Parse DBC file
//! oxirs canbus parse-dbc --file vehicle.dbc --detailed
//!
//! # Decode CAN frame
//! oxirs canbus decode --id 0x0CF00400 --data DEADBEEF --dbc vehicle.dbc
//!
//! # Generate SAMM Aspect Models from DBC
//! oxirs canbus to-samm --dbc vehicle.dbc --output ./models/
//!
//! # Generate RDF from live CAN data
//! oxirs canbus to-rdf --interface can0 --dbc vehicle.dbc --output can_data.ttl --count 1000
//! ```
//!
//! ## Data Persistence
//!
//! - Data is automatically saved to `<dataset>/data.nq` in N-Quads format
//! - On `oxirs import`, data is appended and persisted
//! - On `oxirs query`, data is loaded from disk automatically
//! - No manual save/load commands needed!

use clap::{Parser, Subcommand};
use std::path::PathBuf;

pub mod cli;
pub mod cli_actions;
pub mod commands;
pub mod config;
pub mod export;
pub mod profiling;
pub mod tools;

// Re-export action enums for convenience
pub use cli_actions::*;

/// OxiRS CLI application
#[derive(Parser)]
#[command(name = "oxirs")]
#[command(about = "OxiRS command-line interface")]
#[command(version)]
#[command(
    long_about = "OxiRS command-line interface for RDF processing, SPARQL operations, and semantic data management.\n\nComplete documentation at https://oxirs.io/docs/cli"
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,

    /// Enable verbose logging
    #[arg(short, long, global = true)]
    pub verbose: bool,

    /// Configuration file
    #[arg(short, long, global = true)]
    pub config: Option<PathBuf>,

    /// Suppress output (quiet mode)
    #[arg(short, long, global = true, conflicts_with = "verbose")]
    pub quiet: bool,

    /// Disable colored output
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Interactive mode (where applicable)
    #[arg(short, long, global = true)]
    pub interactive: bool,

    /// Configuration profile to use
    #[arg(short = 'P', long, global = true)]
    pub profile: Option<String>,

    /// Generate shell completion
    #[arg(long, value_enum, hide = true)]
    pub completion: Option<clap_complete::Shell>,
}

/// Available CLI commands
#[derive(Subcommand)]
pub enum Commands {
    /// Initialize a new knowledge graph dataset
    Init {
        /// Dataset name
        name: String,
        /// Storage format (tdb2, memory)
        #[arg(long, default_value = "tdb2")]
        format: String,
        /// Dataset location
        #[arg(short, long)]
        location: Option<PathBuf>,
    },
    /// Start the OxiRS server
    Serve {
        /// Configuration file or dataset path
        config: PathBuf,
        /// Server port
        #[arg(short, long, default_value = "3030")]
        port: u16,
        /// Server host
        #[arg(long, default_value = "localhost")]
        host: String,
        /// Enable GraphQL endpoint
        #[arg(long)]
        graphql: bool,
    },
    /// Import RDF data
    Import {
        /// Target dataset (alphanumeric, _, - only; no dots or extensions)
        dataset: String,
        /// Input file path
        file: PathBuf,
        /// Input format (turtle, ntriples, rdfxml, jsonld)
        #[arg(short, long)]
        format: Option<String>,
        /// Named graph URI
        #[arg(short, long)]
        graph: Option<String>,
        /// Resume from previous checkpoint if interrupted
        #[arg(long)]
        resume: bool,
    },
    /// Export RDF data
    Export {
        /// Source dataset (alphanumeric, _, - only; no dots or extensions)
        dataset: String,
        /// Output file path
        file: PathBuf,
        /// Output format (turtle, ntriples, rdfxml, jsonld)
        #[arg(short, long, default_value = "turtle")]
        format: String,
        /// Named graph URI
        #[arg(short, long)]
        graph: Option<String>,
        /// Resume from previous checkpoint if interrupted
        #[arg(long)]
        resume: bool,
    },
    /// Execute SPARQL query
    Query {
        /// Target dataset (alphanumeric, _, - only; no dots or extensions)
        dataset: String,
        /// SPARQL query string or file
        query: String,
        /// Query is a file path
        #[arg(short, long)]
        file: bool,
        /// Output format (json, csv, tsv, table, xml, html, markdown, md)
        #[arg(short, long, default_value = "table")]
        output: String,
    },
    /// Execute SPARQL update
    Update {
        /// Target dataset (alphanumeric, _, - only; no dots or extensions)
        dataset: String,
        /// SPARQL update string or file
        update: String,
        /// Update is a file path
        #[arg(short, long)]
        file: bool,
    },
    /// Run performance benchmarks and generate benchmark datasets
    Benchmark {
        #[command(subcommand)]
        action: BenchmarkAction,
    },
    /// Migrate data between formats/databases
    Migrate {
        #[command(subcommand)]
        action: MigrateAction,
    },
    /// Generate synthetic RDF datasets for testing and benchmarking
    Generate {
        /// Output file path
        output: PathBuf,
        /// Dataset size (tiny/small/medium/large/xlarge or number)
        #[arg(short, long, default_value = "small")]
        size: String,
        /// Dataset type (rdf/graph/semantic/bibliographic/geographic/organizational)
        #[arg(short = 't', long, default_value = "rdf")]
        r#type: String,
        /// Output format (turtle, ntriples, rdfxml, jsonld, trig, nquads, n3)
        #[arg(short, long, default_value = "turtle")]
        format: String,
        /// Random seed for reproducibility
        #[arg(long)]
        seed: Option<u64>,
        /// SHACL/RDFS/OWL schema file for constrained generation
        #[arg(long)]
        schema: Option<PathBuf>,
    },
    /// Manage database indexes for query performance
    Index {
        #[command(subcommand)]
        action: IndexAction,
    },
    /// Export RDF graph visualization
    Visualize {
        /// Dataset name or path
        dataset: String,
        /// Output file path
        output: PathBuf,
        /// Visualization format (dot/graphviz, mermaid/mmd, cytoscape/json)
        #[arg(short, long, default_value = "dot")]
        format: String,
        /// Specific graph to export (omit for all graphs)
        #[arg(short, long)]
        graph: Option<String>,
        /// Maximum number of nodes to include
        #[arg(long, default_value = "1000")]
        max_nodes: Option<usize>,
    },
    /// Manage server configuration
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },

    // === Data Processing Tools ===
    /// RDF parsing and serialization (Jena riot equivalent)
    Riot {
        /// Input file(s)
        #[arg(required = true)]
        input: Vec<PathBuf>,
        /// Output format (turtle, ntriples, rdfxml, jsonld, trig, nquads)
        #[arg(long, default_value = "turtle")]
        output: String,
        /// Output file (stdout if not specified)
        #[arg(long)]
        out: Option<PathBuf>,
        /// Input format (auto-detect if not specified)
        #[arg(long)]
        syntax: Option<String>,
        /// Base URI for resolving relative URIs
        #[arg(long)]
        base: Option<String>,
        /// Validate syntax only
        #[arg(long)]
        validate: bool,
        /// Count triples/quads
        #[arg(long)]
        count: bool,
    },

    /// Concatenate and convert RDF files
    RdfCat {
        /// Input files
        #[arg(required = true)]
        files: Vec<PathBuf>,
        /// Output format
        #[arg(short, long, default_value = "turtle")]
        format: String,
        /// Output file
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Copy RDF datasets with format conversion
    RdfCopy {
        /// Source dataset/file
        source: PathBuf,
        /// Target dataset/file
        target: PathBuf,
        /// Source format
        #[arg(long)]
        source_format: Option<String>,
        /// Target format
        #[arg(long)]
        target_format: Option<String>,
    },

    /// Compare RDF datasets
    RdfDiff {
        /// First dataset/file
        first: PathBuf,
        /// Second dataset/file
        second: PathBuf,
        /// Output format for differences
        #[arg(short, long, default_value = "text")]
        format: String,
    },

    /// Validate RDF syntax
    RdfParse {
        /// Input file
        file: PathBuf,
        /// Input format
        #[arg(short, long)]
        format: Option<String>,
        /// Base URI
        #[arg(short, long)]
        base: Option<String>,
    },

    // === Advanced Query Tools ===
    /// Advanced SPARQL query processor (Jena arq equivalent)
    Arq {
        /// SPARQL query string or file
        #[arg(long)]
        query: Option<String>,
        /// Query file
        #[arg(long)]
        query_file: Option<PathBuf>,
        /// Data file(s)
        #[arg(long, action = clap::ArgAction::Append)]
        data: Vec<PathBuf>,
        /// Named graph data
        #[arg(long, action = clap::ArgAction::Append)]
        namedgraph: Vec<String>,
        /// Results format (table, csv, tsv, json, xml)
        #[arg(long, default_value = "table")]
        results: String,
        /// Dataset location
        #[arg(long)]
        dataset: Option<PathBuf>,
        /// Explain query execution
        #[arg(long)]
        explain: bool,
        /// Optimize query
        #[arg(long)]
        optimize: bool,
        /// Time query execution
        #[arg(long)]
        time: bool,
    },

    /// Remote SPARQL query execution
    RSparql {
        /// SPARQL endpoint URL
        #[arg(long)]
        service: String,
        /// SPARQL query
        #[arg(long)]
        query: Option<String>,
        /// Query file
        #[arg(long)]
        query_file: Option<PathBuf>,
        /// Results format
        #[arg(long, default_value = "table")]
        results: String,
        /// HTTP timeout in seconds
        #[arg(long, default_value = "30")]
        timeout: u64,
    },

    /// Remote SPARQL update execution
    RUpdate {
        /// SPARQL endpoint URL
        #[arg(long)]
        service: String,
        /// SPARQL update
        #[arg(long)]
        update: Option<String>,
        /// Update file
        #[arg(long)]
        update_file: Option<PathBuf>,
        /// HTTP timeout in seconds
        #[arg(long, default_value = "30")]
        timeout: u64,
    },

    /// SPARQL query parsing and validation
    QParse {
        /// Query string or file
        query: String,
        /// Query is a file path
        #[arg(short, long)]
        file: bool,
        /// Print AST
        #[arg(long)]
        print_ast: bool,
        /// Print algebra
        #[arg(long)]
        print_algebra: bool,
    },

    /// SPARQL update parsing and validation
    UParse {
        /// Update string or file
        update: String,
        /// Update is a file path
        #[arg(short, long)]
        file: bool,
        /// Print AST
        #[arg(long)]
        print_ast: bool,
    },

    // === Storage Tools ===
    /// Bulk data loading
    TdbLoader {
        /// Target dataset location
        location: PathBuf,
        /// Input files
        files: Vec<PathBuf>,
        /// Graph URI for loading
        #[arg(short, long)]
        graph: Option<String>,
        /// Show progress
        #[arg(long)]
        progress: bool,
        /// Statistics reporting
        #[arg(long)]
        stats: bool,
    },

    /// Dataset export and dumping
    TdbDump {
        /// Source dataset location
        location: PathBuf,
        /// Output file
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Output format
        #[arg(short, long, default_value = "nquads")]
        format: String,
        /// Graph URI to dump
        #[arg(short, long)]
        graph: Option<String>,
    },

    /// Direct TDB querying
    TdbQuery {
        /// Dataset location
        location: PathBuf,
        /// SPARQL query
        query: String,
        /// Query is a file path
        #[arg(short, long)]
        file: bool,
        /// Results format
        #[arg(long, default_value = "table")]
        results: String,
    },

    /// Direct TDB updates
    TdbUpdate {
        /// Dataset location
        location: PathBuf,
        /// SPARQL update
        update: String,
        /// Update is a file path
        #[arg(short, long)]
        file: bool,
    },

    /// Database statistics
    TdbStats {
        /// Dataset location
        location: PathBuf,
        /// Detailed statistics
        #[arg(long)]
        detailed: bool,
        /// Output format (text, json)
        #[arg(long, default_value = "text")]
        format: String,
    },

    /// Database backup utilities with encryption support
    TdbBackup {
        /// Source dataset location
        source: PathBuf,
        /// Backup location
        target: PathBuf,
        /// Compress backup
        #[arg(long)]
        compress: bool,
        /// Incremental backup
        #[arg(long)]
        incremental: bool,
        /// Encrypt backup with AES-256-GCM
        #[arg(long)]
        encrypt: bool,
        /// Password for encryption (prompted if not provided)
        #[arg(long, requires = "encrypt")]
        password: Option<String>,
        /// Keyfile for encryption (alternative to password)
        #[arg(long, requires = "encrypt", conflicts_with = "password")]
        keyfile: Option<PathBuf>,
        /// Generate a new encryption keyfile
        #[arg(long, conflicts_with_all = ["encrypt", "password"])]
        generate_keyfile: Option<PathBuf>,
    },

    /// Database compaction
    TdbCompact {
        /// Dataset location
        location: PathBuf,
        /// Delete logs after compaction
        #[arg(long)]
        delete_old: bool,
    },

    /// Point-in-Time Recovery (PITR) operations
    Pitr {
        #[command(subcommand)]
        action: PitrAction,
    },

    // === Validation Tools ===
    /// SHACL validation
    Shacl {
        /// Data to validate
        #[arg(long)]
        data: Option<PathBuf>,
        /// Dataset location
        #[arg(long)]
        dataset: Option<PathBuf>,
        /// SHACL shapes file
        #[arg(long)]
        shapes: PathBuf,
        /// Output format (text, turtle, json)
        #[arg(long, default_value = "text")]
        format: String,
        /// Output file
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// ShEx validation
    Shex {
        /// Data to validate
        #[arg(long)]
        data: Option<PathBuf>,
        /// Dataset location
        #[arg(long)]
        dataset: Option<PathBuf>,
        /// ShEx schema file
        #[arg(long)]
        schema: PathBuf,
        /// Shape map file
        #[arg(long)]
        shape_map: Option<PathBuf>,
        /// Output format
        #[arg(long, default_value = "text")]
        format: String,
    },

    /// Inference and reasoning
    Infer {
        /// Input data
        data: PathBuf,
        /// Ontology/schema file
        #[arg(long)]
        ontology: Option<PathBuf>,
        /// Reasoning profile (rdfs, owl-rl, custom)
        #[arg(long, default_value = "rdfs")]
        profile: String,
        /// Output file
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Output format
        #[arg(long, default_value = "turtle")]
        format: String,
    },

    /// Schema generation from RDF
    SchemaGen {
        /// Input RDF data
        data: PathBuf,
        /// Schema type (shacl, shex, owl)
        #[arg(long, default_value = "shacl")]
        schema_type: String,
        /// Output file
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Include statistics
        #[arg(long)]
        stats: bool,
    },

    /// SAMM Aspect Model tools (Java ESMF SDK compatible)
    Aspect {
        #[command(subcommand)]
        action: AspectAction,
    },

    /// Asset Administration Shell (AAS) tools (Java ESMF SDK compatible)
    Aas {
        #[command(subcommand)]
        action: AasAction,
    },

    /// Package management tools (Java ESMF SDK compatible)
    Package {
        #[command(subcommand)]
        action: PackageAction,
    },

    // === Utility Tools ===
    /// IRI validation and processing
    Iri {
        /// IRI to validate/process
        iri: String,
        /// Resolve relative IRI
        #[arg(long)]
        resolve: Option<String>,
        /// Check if IRI is valid
        #[arg(long)]
        validate: bool,
        /// Normalize IRI
        #[arg(long)]
        normalize: bool,
    },

    /// Language tag validation
    LangTag {
        /// Language tag to validate
        tag: String,
        /// Check if tag is well-formed
        #[arg(long)]
        validate: bool,
        /// Normalize tag
        #[arg(long)]
        normalize: bool,
    },

    /// UUID generation for blank nodes
    JUuid {
        /// Number of UUIDs to generate
        #[arg(short = 'n', long, default_value = "1")]
        count: usize,
        /// Output format (uuid, urn, bnode)
        #[arg(short, long, default_value = "uuid")]
        format: String,
    },

    /// UTF-8 encoding utilities
    Utf8 {
        /// Input file or string
        input: String,
        /// Input is a file path
        #[arg(short, long)]
        file: bool,
        /// Check UTF-8 validity
        #[arg(long)]
        validate: bool,
        /// Fix UTF-8 encoding issues
        #[arg(long)]
        fix: bool,
    },

    /// URL encoding
    WwwEnc {
        /// String to encode
        input: String,
        /// Encoding type (url, form)
        #[arg(long, default_value = "url")]
        encoding: String,
    },

    /// URL decoding
    WwwDec {
        /// String to decode
        input: String,
        /// Decoding type (url, form)
        #[arg(long, default_value = "url")]
        decoding: String,
    },

    /// Result set processing
    RSet {
        /// Input results file
        input: PathBuf,
        /// Input format (csv, tsv, json, xml)
        #[arg(long)]
        input_format: Option<String>,
        /// Output format (csv, tsv, json, xml, table)
        #[arg(long, default_value = "table")]
        output_format: String,
        /// Output file
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Start interactive REPL mode
    Interactive {
        /// Initial dataset to connect to
        #[arg(short, long)]
        dataset: Option<String>,
        /// History file location
        #[arg(long)]
        history: Option<PathBuf>,
    },

    /// Performance monitoring and profiling
    Performance {
        #[command(subcommand)]
        action: commands::performance::PerformanceCommand,
    },

    /// Query explanation and analysis
    Explain {
        /// Target dataset
        dataset: String,
        /// SPARQL query string or file
        query: String,
        /// Query is a file path
        #[arg(short, long)]
        file: bool,
        /// Analysis mode (explain, analyze, full)
        #[arg(short, long, default_value = "explain")]
        mode: String,
        /// Generate graphical query plan (Graphviz DOT format)
        #[arg(short, long)]
        graphviz: Option<PathBuf>,
    },

    /// Query optimization analyzer
    Optimize {
        /// SPARQL query string or file
        query: String,
        /// Query is a file path
        #[arg(short, long)]
        file: bool,
    },

    /// SPARQL query template management
    Template {
        #[command(subcommand)]
        action: TemplateAction,
    },

    /// Query history management
    History {
        #[command(subcommand)]
        action: HistoryAction,
    },

    /// CI/CD integration tools
    Cicd {
        #[command(subcommand)]
        action: CicdAction,
    },

    /// Command alias management
    Alias {
        #[command(subcommand)]
        action: AliasAction,
    },

    /// Query cache management
    Cache {
        #[command(subcommand)]
        action: CacheAction,
    },

    /// ReBAC relationship management
    Rebac(commands::rebac::RebacArgs),

    /// Generate CLI documentation
    Docs {
        /// Output format (markdown, html, man, text)
        #[arg(short, long, default_value = "markdown")]
        format: String,
        /// Output file path (stdout if not specified)
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Generate documentation for specific command
        #[arg(long)]
        command: Option<String>,
    },

    /// Interactive tutorial mode for learning OxiRS
    Tutorial {
        /// Start at specific lesson
        #[arg(short, long)]
        lesson: Option<String>,
    },

    /// Advanced RDF graph analytics using scirs2-graph
    GraphAnalytics {
        /// Dataset name or path
        dataset: String,
        /// Analytics operation (pagerank, community, betweenness, closeness, degree, paths, stats)
        #[arg(short, long, default_value = "pagerank")]
        operation: String,
        /// Damping factor for PageRank
        #[arg(long, default_value = "0.85")]
        damping: f64,
        /// Maximum iterations for iterative algorithms
        #[arg(long, default_value = "100")]
        max_iter: usize,
        /// Convergence tolerance
        #[arg(long, default_value = "0.000001")]
        tolerance: f64,
        /// Source node URI for shortest paths
        #[arg(long)]
        source: Option<String>,
        /// Target node URI for shortest paths
        #[arg(long)]
        target: Option<String>,
        /// Top K results to display
        #[arg(short = 'k', long, default_value = "20")]
        top: usize,
    },

    // === Phase D: Industrial Connectivity ===
    /// Time-series database operations
    Tsdb {
        #[command(subcommand)]
        action: TsdbAction,
    },

    /// Modbus protocol monitoring and configuration
    Modbus {
        #[command(subcommand)]
        action: ModbusAction,
    },

    /// CANbus/J1939 monitoring and DBC parsing
    Canbus {
        #[command(subcommand)]
        action: CanbusAction,
    },

    /// SPARQL query profiler
    Profile {
        #[command(subcommand)]
        action: ProfilerAction,
    },

    /// LRU result cache management
    ResultCache {
        #[command(subcommand)]
        action: ResultCacheAction,
    },

    /// Streaming SPARQL query results
    Stream {
        #[command(subcommand)]
        action: StreamAction,
    },
}

/// Run the CLI application
pub async fn run(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
    use cli::{completion, CliContext};

    // Handle shell completion generation
    if let Some(shell) = cli.completion {
        use clap::CommandFactory;
        let mut app = Cli::command();
        completion::print_completions(shell, &mut app);
        return Ok(());
    }

    // Create CLI context
    let ctx = CliContext::from_cli(cli.verbose, cli.quiet, cli.no_color);

    // Initialize structured logging
    let log_format = if std::env::var("OXIRS_LOG_FORMAT").as_deref() == Ok("json") {
        cli::LogFormat::Json
    } else if ctx.verbose {
        cli::LogFormat::Pretty
    } else {
        cli::LogFormat::Text
    };

    let log_config = cli::LogConfig {
        level: if ctx.verbose {
            "debug".to_string()
        } else if ctx.quiet {
            "error".to_string()
        } else {
            std::env::var("OXIRS_LOG_LEVEL").unwrap_or_else(|_| "info".to_string())
        },
        format: log_format,
        timestamps: !ctx.quiet,
        source_location: ctx.verbose,
        thread_ids: false,
        perf_threshold_ms: std::env::var("OXIRS_PERF_THRESHOLD")
            .ok()
            .and_then(|s| s.parse().ok()),
        file: std::env::var("OXIRS_LOG_FILE").ok(),
    };

    cli::init_logging(&log_config).expect("Failed to initialize logging");

    // Show startup message if not quiet
    if ctx.should_show_output() {
        ctx.info(&format!("Oxirs CLI v{}", env!("CARGO_PKG_VERSION")));
    }

    match cli.command {
        Commands::Init {
            name,
            format,
            location,
        } => commands::init::run(name, format, location)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Serve {
            config,
            port,
            host,
            graphql,
        } => commands::serve::run(config, port, host, graphql)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Import {
            dataset,
            file,
            format,
            graph,
            resume,
        } => commands::import::run(dataset, file, format, graph, resume)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Export {
            dataset,
            file,
            format,
            graph,
            resume,
        } => commands::export::run(dataset, file, format, graph, resume)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Query {
            dataset,
            query,
            file,
            output,
        } => commands::query::run(dataset, query, file, output)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Update {
            dataset,
            update,
            file,
        } => commands::update::run(dataset, update, file)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Benchmark { action } => match action {
            BenchmarkAction::Run {
                dataset,
                suite,
                iterations,
                output,
                detailed,
                warmup,
            } => commands::benchmark::run(dataset, suite, iterations, output, detailed, warmup)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            BenchmarkAction::Generate {
                output,
                size,
                dataset_type,
                seed,
                triples,
                schema,
            } => commands::benchmark::generate(output, size, dataset_type, seed, triples, schema)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            BenchmarkAction::Analyze {
                input,
                output,
                format,
                suggestions,
                patterns,
            } => commands::benchmark::analyze(input, output, format, suggestions, patterns)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            BenchmarkAction::Compare {
                baseline,
                current,
                output,
                threshold,
                format,
            } => commands::benchmark::compare(baseline, current, output, threshold, format)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        },
        Commands::Migrate { action } => match action {
            MigrateAction::Format {
                source,
                target,
                from,
                to,
            } => commands::migrate::format(source, target, from, to)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            MigrateAction::FromTdb1 {
                tdb_dir,
                dataset,
                skip_validation,
            } => commands::migrate::from_tdb1(tdb_dir, dataset, skip_validation)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            MigrateAction::FromTdb2 {
                tdb_dir,
                dataset,
                skip_validation,
            } => commands::migrate::from_tdb2(tdb_dir, dataset, skip_validation)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            MigrateAction::FromVirtuoso {
                connection,
                dataset,
                graphs,
            } => commands::migrate::from_virtuoso(connection, dataset, graphs)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            MigrateAction::FromRdf4j { repo_dir, dataset } => {
                commands::migrate::from_rdf4j(repo_dir, dataset)
                    .await
                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
            }
            MigrateAction::FromBlazegraph {
                endpoint,
                dataset,
                namespace,
            } => commands::migrate::from_blazegraph(endpoint, dataset, namespace)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            MigrateAction::FromGraphdb {
                endpoint,
                dataset,
                repository,
            } => commands::migrate::from_graphdb(endpoint, dataset, repository)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        },
        Commands::Generate {
            output,
            size,
            r#type,
            format,
            seed,
            schema,
        } => commands::generate::run(output, size, r#type, format, seed, schema)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Index { action } => match action {
            IndexAction::List { dataset } => commands::index::list(dataset)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            IndexAction::Rebuild { dataset, index } => commands::index::rebuild(dataset, index)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            IndexAction::Stats { dataset, format } => commands::index::stats(dataset, format)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
            IndexAction::Optimize { dataset } => commands::index::optimize(dataset)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        },
        Commands::Visualize {
            dataset,
            output,
            format,
            graph,
            max_nodes,
        } => commands::visualize::export(dataset, output, format, graph, max_nodes)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Config { action } => commands::config::run(action)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),

        // Data Processing Tools
        Commands::Riot {
            input,
            output,
            out,
            syntax,
            base,
            validate,
            count,
        } => tools::riot::run(input, output, out, syntax, base, validate, count).await,
        Commands::RdfCat {
            files,
            format,
            output,
        } => tools::rdfcat::run(files, format, output).await,
        Commands::RdfCopy {
            source,
            target,
            source_format,
            target_format,
        } => tools::rdfcopy::run(source, target, source_format, target_format).await,
        Commands::RdfDiff {
            first,
            second,
            format,
        } => tools::rdfdiff::run(first, second, format).await,
        Commands::RdfParse { file, format, base } => tools::rdfparse::run(file, format, base).await,

        // Advanced Query Tools
        Commands::Arq {
            query,
            query_file,
            data,
            namedgraph,
            results,
            dataset,
            explain,
            optimize,
            time,
        } => {
            tools::arq::run(tools::arq::ArqConfig {
                query,
                query_file,
                data,
                namedgraph,
                results_format: results,
                dataset,
                explain,
                optimize,
                time,
            })
            .await
        }
        Commands::RSparql {
            service,
            query,
            query_file,
            results,
            timeout,
        } => tools::rsparql::run(service, query, query_file, results, timeout).await,
        Commands::RUpdate {
            service,
            update,
            update_file,
            timeout,
        } => tools::rupdate::run(service, update, update_file, timeout).await,
        Commands::QParse {
            query,
            file,
            print_ast,
            print_algebra,
        } => tools::qparse::run(query, file, print_ast, print_algebra).await,
        Commands::UParse {
            update,
            file,
            print_ast,
        } => tools::uparse::run(update, file, print_ast).await,

        // Storage Tools
        Commands::TdbLoader {
            location,
            files,
            graph,
            progress,
            stats,
        } => tools::tdbloader::run(location, files, graph, progress, stats).await,
        Commands::TdbDump {
            location,
            output,
            format,
            graph,
        } => tools::tdbdump::run(location, output, format, graph).await,
        Commands::TdbQuery {
            location,
            query,
            file,
            results,
        } => tools::tdbquery::run(location, query, file, results).await,
        Commands::TdbUpdate {
            location,
            update,
            file,
        } => tools::tdbupdate::run(location, update, file).await,
        Commands::TdbStats {
            location,
            detailed,
            format,
        } => tools::tdbstats::run(location, detailed, format).await,
        Commands::TdbBackup {
            source,
            target,
            compress,
            incremental,
            encrypt,
            password,
            keyfile,
            generate_keyfile,
        } => {
            use tools::backup_encryption;

            // Handle keyfile generation
            if let Some(keyfile_path) = generate_keyfile {
                println!("Generating encryption keyfile...");
                backup_encryption::generate_keyfile(&keyfile_path)?;
                println!(
                    "Keyfile generated successfully at: {}",
                    keyfile_path.display()
                );
                println!(
                    "⚠️  Keep this keyfile secure! Loss of the keyfile means loss of data access."
                );
                return Ok(());
            }

            // Clone target for encryption if needed
            let target_for_encryption = target.clone();

            // Run backup
            tools::tdbbackup::run(source, target, compress, incremental).await?;

            // Encrypt backup if requested
            if encrypt {
                use dialoguer::Password;

                println!("\nEncrypting backup...");
                let backup_file = &target_for_encryption;
                let encrypted_file = backup_file.with_extension("oxirs.enc");

                let encryption_config = if let Some(ref pwd) = password {
                    backup_encryption::EncryptionConfig {
                        password: Some(pwd.clone()),
                        keyfile: None,
                        verify: true,
                    }
                } else if let Some(ref kf) = keyfile {
                    backup_encryption::EncryptionConfig {
                        password: None,
                        keyfile: Some(kf.clone()),
                        verify: true,
                    }
                } else {
                    // Prompt for password
                    let pwd = Password::new()
                        .with_prompt("Enter encryption password")
                        .with_confirmation("Confirm password", "Passwords don't match")
                        .interact()?;

                    backup_encryption::EncryptionConfig {
                        password: Some(pwd),
                        keyfile: None,
                        verify: true,
                    }
                };

                backup_encryption::encrypt_backup(
                    backup_file,
                    &encrypted_file,
                    &encryption_config,
                )?;
                println!(
                    "✓ Backup encrypted successfully: {}",
                    encrypted_file.display()
                );
            }
            Ok(())
        }
        Commands::TdbCompact {
            location,
            delete_old,
        } => tools::tdbcompact::run(location, delete_old).await,

        Commands::Pitr { action } => {
            use chrono::{DateTime, Utc};
            use tools::pitr::{PitrConfig, TransactionLog};

            match action {
                PitrAction::Init {
                    dataset,
                    max_log_size,
                    auto_archive,
                } => {
                    println!("Initializing PITR for dataset: {}", dataset.display());
                    let config = PitrConfig {
                        log_dir: dataset.join("pitr/logs"),
                        archive_dir: dataset.join("pitr/archive"),
                        max_log_size: max_log_size * 1_048_576, // Convert MB to bytes
                        auto_archive,
                    };
                    let _log = TransactionLog::new(config)?;
                    println!("✓ PITR initialized successfully");
                }
                PitrAction::Checkpoint { dataset, name } => {
                    let config = PitrConfig {
                        log_dir: dataset.join("pitr/logs"),
                        archive_dir: dataset.join("pitr/archive"),
                        max_log_size: 100_000_000,
                        auto_archive: false,
                    };
                    let log = TransactionLog::new(config)?;
                    let checkpoint_path = log.create_checkpoint(&name)?;
                    println!("✓ Checkpoint created: {}", checkpoint_path.display());
                }
                PitrAction::List { dataset, format } => {
                    let config = PitrConfig {
                        log_dir: dataset.join("pitr/logs"),
                        archive_dir: dataset.join("pitr/archive"),
                        max_log_size: 100_000_000,
                        auto_archive: false,
                    };
                    let log = TransactionLog::new(config)?;
                    let checkpoints = log.list_checkpoints()?;

                    if format == "json" {
                        println!("{}", serde_json::to_string_pretty(&checkpoints)?);
                    } else {
                        println!("Available Checkpoints:");
                        println!("{:-<80}", "");
                        for cp in checkpoints {
                            println!("Name: {}", cp.name);
                            println!("  Timestamp: {}", cp.timestamp.to_rfc3339());
                            println!("  Last Transaction ID: {}", cp.last_transaction_id);
                            println!("  Log Files: {}", cp.log_files.len());
                            println!();
                        }
                    }
                }
                PitrAction::RecoverTimestamp {
                    dataset,
                    timestamp,
                    output,
                } => {
                    let target_time: DateTime<Utc> = timestamp.parse()?;
                    let config = PitrConfig {
                        log_dir: dataset.join("pitr/logs"),
                        archive_dir: dataset.join("pitr/archive"),
                        max_log_size: 100_000_000,
                        auto_archive: false,
                    };
                    let log = TransactionLog::new(config)?;
                    let count = log.recover_to_timestamp(target_time, &output)?;
                    println!("✓ Recovered {} transactions to {}", count, output.display());
                }
                PitrAction::RecoverTransaction {
                    dataset,
                    transaction_id,
                    output,
                } => {
                    let config = PitrConfig {
                        log_dir: dataset.join("pitr/logs"),
                        archive_dir: dataset.join("pitr/archive"),
                        max_log_size: 100_000_000,
                        auto_archive: false,
                    };
                    let log = TransactionLog::new(config)?;
                    let count = log.recover_to_transaction(transaction_id, &output)?;
                    println!("✓ Recovered {} transactions to {}", count, output.display());
                }
                PitrAction::Archive { dataset } => {
                    let config = PitrConfig {
                        log_dir: dataset.join("pitr/logs"),
                        archive_dir: dataset.join("pitr/archive"),
                        max_log_size: 100_000_000,
                        auto_archive: false,
                    };
                    let mut log = TransactionLog::new(config)?;
                    let archived = log.archive_logs()?;
                    println!("✓ Archived {} log files", archived);
                }
            }
            Ok(())
        }

        // Validation Tools
        Commands::Shacl {
            data,
            dataset,
            shapes,
            format,
            output,
        } => tools::shacl::run(data, dataset, shapes, format, output).await,
        Commands::Shex {
            data,
            dataset,
            schema,
            shape_map,
            format,
        } => tools::shex::run(data, dataset, schema, shape_map, format).await,
        Commands::Infer {
            data,
            ontology,
            profile,
            output,
            format,
        } => tools::infer::run(data, ontology, profile, output, format).await,
        Commands::SchemaGen {
            data,
            schema_type,
            output,
            stats,
        } => tools::schemagen::run(data, schema_type, output, stats).await,
        Commands::Aspect { action } => commands::aspect::run(action)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Aas { action } => commands::aas::run(action)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),
        Commands::Package { action } => commands::package::run(action)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>),

        // Utility Tools
        Commands::Iri {
            iri,
            resolve,
            validate,
            normalize,
        } => tools::iri::run(iri, resolve, validate, normalize).await,
        Commands::LangTag {
            tag,
            validate,
            normalize,
        } => tools::langtag::run(tag, validate, normalize).await,
        Commands::JUuid { count, format } => tools::juuid::run(count, format).await,
        Commands::Utf8 {
            input,
            file,
            validate,
            fix,
        } => tools::utf8::run(input, file, validate, fix).await,
        Commands::WwwEnc { input, encoding } => tools::wwwenc::run(input, encoding).await,
        Commands::WwwDec { input, decoding } => tools::wwwdec::run(input, decoding).await,
        Commands::RSet {
            input,
            input_format,
            output_format,
            output,
        } => tools::rset::run(input, input_format, output_format, output).await,
        Commands::Interactive {
            dataset,
            history: _,
        } => {
            ctx.info("Starting interactive SPARQL shell...");
            commands::interactive::execute(dataset, cli.config)
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
        }
        Commands::Performance { action } => {
            let config = config::Config::default();
            action
                .execute(&config)
                .await
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
        }
        Commands::Explain {
            dataset,
            query,
            file,
            mode,
            graphviz,
        } => {
            let analysis_mode = match mode.to_lowercase().as_str() {
                "explain" => commands::explain::AnalysisMode::Explain,
                "analyze" => commands::explain::AnalysisMode::Analyze,
                "full" => commands::explain::AnalysisMode::Full,
                _ => {
                    eprintln!(
                        "Invalid mode '{}'. Valid modes: explain, analyze, full",
                        mode
                    );
                    return Err("Invalid analysis mode".into());
                }
            };
            commands::explain::explain_query_with_options(
                dataset,
                query,
                file,
                analysis_mode,
                graphviz,
            )
            .await
            .map_err(|e| e.into())
        }
        Commands::Optimize { query, file } => {
            commands::query_optimizer::optimize_command(query, file)
                .await
                .map_err(|e| e.into())
        }
        Commands::Template { action } => {
            use std::collections::HashMap;
            match action {
                TemplateAction::List { category } => commands::templates::list_command(category)
                    .await
                    .map_err(|e| e.into()),
                TemplateAction::Show { name } => commands::templates::show_command(name)
                    .await
                    .map_err(|e| e.into()),
                TemplateAction::Render { name, param } => {
                    let mut params = HashMap::new();
                    for p in param {
                        let parts: Vec<&str> = p.splitn(2, '=').collect();
                        if parts.len() != 2 {
                            eprintln!("Invalid parameter format: '{}'. Expected key=value", p);
                            return Err("Invalid parameter format".into());
                        }
                        params.insert(parts[0].to_string(), parts[1].to_string());
                    }
                    commands::templates::render_command(name, params)
                        .await
                        .map_err(|e| e.into())
                }
            }
        }
        Commands::History { action } => match action {
            HistoryAction::List { limit, dataset } => {
                commands::history::commands::list_command(limit, dataset)
                    .await
                    .map_err(|e| e.into())
            }
            HistoryAction::Show { id } => commands::history::commands::show_command(id)
                .await
                .map_err(|e| e.into()),
            HistoryAction::Replay { id, output } => {
                commands::history::commands::replay_command(id, output)
                    .await
                    .map_err(|e| e.into())
            }
            HistoryAction::Search { query } => commands::history::commands::search_command(query)
                .await
                .map_err(|e| e.into()),
            HistoryAction::Clear => commands::history::commands::clear_command()
                .await
                .map_err(|e| e.into()),
            HistoryAction::Stats => commands::history::commands::stats_command()
                .await
                .map_err(|e| e.into()),
            HistoryAction::Analytics { dataset } => {
                commands::history::commands::analytics_command(dataset)
                    .await
                    .map_err(|e| e.into())
            }
        },
        Commands::Cicd { action } => match action {
            CicdAction::Report {
                input,
                output,
                format,
            } => commands::cicd::generate_test_report(input, output, format)
                .await
                .map_err(|e| e.into()),
            CicdAction::Docker { output } => commands::cicd::generate_docker_files(output)
                .await
                .map_err(|e| e.into()),
            CicdAction::Github { output } => commands::cicd::generate_github_workflow(output)
                .await
                .map_err(|e| e.into()),
            CicdAction::Gitlab { output } => commands::cicd::generate_gitlab_ci(output)
                .await
                .map_err(|e| e.into()),
        },
        Commands::Alias { action } => match action {
            AliasAction::List => commands::alias::list().await.map_err(|e| e.into()),
            AliasAction::Show { name } => commands::alias::show(name.clone())
                .await
                .map_err(|e| e.into()),
            AliasAction::Add { name, command } => {
                commands::alias::add(name.clone(), command.clone())
                    .await
                    .map_err(|e| e.into())
            }
            AliasAction::Remove { name } => commands::alias::remove(name.clone())
                .await
                .map_err(|e| e.into()),
            AliasAction::Reset => commands::alias::reset().await.map_err(|e| e.into()),
        },

        Commands::Cache { action } => match action {
            CacheAction::Stats => commands::cache::commands::stats_command()
                .await
                .map_err(|e| e.into()),
            CacheAction::Clear => commands::cache::commands::clear_command()
                .await
                .map_err(|e| e.into()),
            CacheAction::Config { ttl, max_size } => {
                commands::cache::commands::config_command(ttl, max_size)
                    .await
                    .map_err(|e| e.into())
            }
        },

        Commands::Rebac(args) => commands::rebac::execute(args).await.map_err(|e| e.into()),

        Commands::Docs {
            format,
            output,
            command,
        } => {
            use cli::doc_generator::{DocFormat, DocGenerator};
            use std::io::Write;

            let doc_format: DocFormat = format
                .parse()
                .map_err(|e: String| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;

            let generator = DocGenerator::new();

            if let Some(cmd_name) = command {
                ctx.info(&format!(
                    "Generating documentation for command: {}",
                    cmd_name
                ));
                // Generate single command docs (future enhancement)
                ctx.warn(
                    "Single command documentation not yet implemented. Generating all commands.",
                );
            }

            let content = generator
                .generate(doc_format)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;

            if let Some(output_path) = output {
                let mut file = std::fs::File::create(&output_path)?;
                file.write_all(content.as_bytes())?;
                ctx.success(&format!(
                    "Documentation written to: {}",
                    output_path.display()
                ));
            } else {
                println!("{}", content);
            }

            Ok(())
        }

        Commands::Tutorial { lesson } => {
            use cli::tutorial::TutorialManager;

            let mut manager = TutorialManager::new();

            if let Some(lesson_name) = lesson {
                ctx.info(&format!("Starting tutorial with lesson: {}", lesson_name));
                ctx.warn(
                    "Specific lesson selection not yet implemented. Starting interactive tutorial.",
                );
            }

            manager.start().map_err(|e| {
                std::io::Error::new(std::io::ErrorKind::Other, format!("Tutorial error: {}", e))
            })?;

            Ok(())
        }

        Commands::GraphAnalytics {
            dataset,
            operation,
            damping,
            max_iter,
            tolerance,
            source,
            target,
            top,
        } => {
            use commands::graph_analytics::{
                execute_graph_analytics, AnalyticsConfig, AnalyticsOperation,
            };
            use std::path::Path;

            // Parse operation
            let op: AnalyticsOperation = operation
                .parse()
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;

            // Build configuration
            let config = AnalyticsConfig {
                operation: op,
                damping_factor: damping,
                max_iterations: max_iter,
                tolerance,
                source_node: source.clone(),
                target_node: target.clone(),
                top_k: top,
                katz_alpha: 0.1,            // Default Katz centrality alpha parameter
                katz_beta: 1.0,             // Default Katz centrality beta parameter
                k_core_value: None,         // Auto-detect all cores
                enable_simd: true,          // Auto-enable SIMD optimizations
                enable_parallel: true,      // Auto-enable parallel processing
                enable_gpu: false,          // GPU is opt-in (requires hardware)
                enable_cache: true,         // Enable caching for better performance
                export_path: None,          // No export by default
                enable_benchmarking: false, // Disable benchmarking by default
            };

            // Execute analytics
            let dataset_path = Path::new(dataset.as_str());
            execute_graph_analytics(dataset_path, &config)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;

            Ok(())
        }

        // === Phase D: Industrial Connectivity CLI Handlers (0.2.4) ===
        Commands::Tsdb { action } => commands::tsdb::execute(action, &ctx)
            .await
            .map_err(|e| e.into()),

        Commands::Modbus { action } => commands::modbus::execute(action, &ctx)
            .await
            .map_err(|e| e.into()),

        Commands::Canbus { action } => commands::canbus::execute(action, &ctx)
            .await
            .map_err(|e| e.into()),

        Commands::Profile { action } => match action {
            ProfilerAction::Run {
                dataset,
                query,
                file,
                iterations,
                suggestions,
            } => commands::query_profiler::run_profile_command(
                dataset,
                query,
                file,
                iterations,
                suggestions,
            )
            .await
            .map_err(|e| e.into()),
            ProfilerAction::Suggest { query, file } => {
                let q = if file {
                    std::fs::read_to_string(&query)
                        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?
                } else {
                    query
                };
                let features = commands::query_profiler::QueryProfileFeatures::extract(&q);
                let suggestions = commands::query_profiler::generate_suggestions(&features, &q);
                for s in suggestions {
                    println!("[{}] {}: {}", s.severity.label(), s.title, s.description);
                }
                Ok(())
            }
        },

        Commands::ResultCache { action } => match action {
            ResultCacheAction::Stats => commands::result_cache::commands::stats_command()
                .await
                .map_err(|e| e.into()),
            ResultCacheAction::Clear => commands::result_cache::commands::clear_command()
                .await
                .map_err(|e| e.into()),
            ResultCacheAction::Invalidate { dataset } => {
                commands::result_cache::commands::invalidate_dataset_command(&dataset)
                    .await
                    .map_err(|e| e.into())
            }
            ResultCacheAction::Evict => commands::result_cache::commands::evict_expired_command()
                .await
                .map_err(|e| e.into()),
            ResultCacheAction::List { dataset } => {
                commands::result_cache::commands::list_command(dataset.as_deref())
                    .await
                    .map_err(|e| e.into())
            }
            ResultCacheAction::Config { max_size, ttl } => {
                let cache = commands::result_cache::global_lru_cache();
                if let Some(sz) = max_size {
                    println!("Max entries updated to {}", sz);
                    let _ = sz; // config applied at init time
                }
                if let Some(t) = ttl {
                    println!("Default TTL updated to {}s", t);
                    let _ = t;
                }
                let _ = cache;
                Ok(())
            }
        },

        Commands::Stream { action } => match action {
            StreamAction::Query {
                dataset,
                query,
                file,
                chunk_size,
                format,
                max_rows,
                no_progress,
                output,
            } => commands::stream::run_stream_command(
                dataset,
                query,
                file,
                chunk_size,
                format,
                max_rows,
                no_progress,
                output,
            )
            .await
            .map_err(|e| e.into()),
        },
    }
}