oxirs-star 0.2.4

RDF-star and SPARQL-star grammar support for quoted triples
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
//! Command-line interface tools for RDF-star validation and debugging.
//!
//! This module provides comprehensive CLI utilities for working with RDF-star data,
//! including validation, conversion, analysis, and debugging tools.

use std::fs;
use std::path::Path;
use std::time::Instant;

use anyhow::{anyhow, Context, Result};
use chrono;
use clap::{Arg, ArgMatches, Command};
use serde_json;
use tracing::info;

use crate::model::{StarTerm, StarTriple};
use crate::parser::{StarFormat, StarParser};
use crate::profiling::{ProfilingConfig, StarProfiler};
use crate::serializer::{SerializationOptions, StarSerializer};
use crate::store::StarStore;
use crate::troubleshooting::{
    DiagnosticAnalyzer, MigrationAssistant, MigrationSourceFormat, TroubleshootingGuide,
    TroubleshootingIssue,
};
use crate::{StarConfig, StarError, StarResult};

/// CLI application for RDF-star tools
pub struct StarCli {
    _config: StarConfig,
    verbose: bool,
    quiet: bool,
}

impl StarCli {
    /// Create a new CLI application
    pub fn new() -> Self {
        Self {
            _config: StarConfig::default(),
            verbose: false,
            quiet: false,
        }
    }

    /// Run the CLI application with command-line arguments
    pub fn run(&mut self, args: Vec<String>) -> Result<()> {
        let app = self.build_cli();
        let matches = app.try_get_matches_from(args)?;

        self.verbose = matches.get_flag("verbose");
        self.quiet = matches.get_flag("quiet");

        self.setup_logging();

        match matches.subcommand() {
            Some(("validate", sub_matches)) => self.validate_command(sub_matches),
            Some(("convert", sub_matches)) => self.convert_command(sub_matches),
            Some(("analyze", sub_matches)) => self.analyze_command(sub_matches),
            Some(("debug", sub_matches)) => self.debug_command(sub_matches),
            Some(("benchmark", sub_matches)) => self.benchmark_command(sub_matches),
            Some(("query", sub_matches)) => self.query_command(sub_matches),
            Some(("troubleshoot", sub_matches)) => self.troubleshoot_command(sub_matches),
            Some(("migrate", sub_matches)) => self.migrate_command(sub_matches),
            Some(("doctor", sub_matches)) => self.doctor_command(sub_matches),
            Some(("profile", sub_matches)) => self.profile_command(sub_matches),
            Some(("profile-report", sub_matches)) => self.profile_report_command(sub_matches),
            _ => {
                eprintln!("No command specified. Use --help for usage information.");
                std::process::exit(1);
            }
        }
    }

    /// Build the CLI application structure
    fn build_cli(&self) -> Command {
        Command::new("oxirs-star")
            .version("1.0.0")
            .about("RDF-star validation, conversion, and debugging tools")
            .author("OxiRS Team")
            .arg(
                Arg::new("verbose")
                    .short('v')
                    .long("verbose")
                    .help("Enable verbose output")
                    .action(clap::ArgAction::SetTrue),
            )
            .arg(
                Arg::new("quiet")
                    .short('q')
                    .long("quiet")
                    .help("Suppress all output except errors")
                    .action(clap::ArgAction::SetTrue),
            )
            .subcommand(
                Command::new("validate")
                    .about("Validate RDF-star files")
                    .arg(
                        Arg::new("input")
                            .help("Input file path")
                            .required(true)
                            .value_name("FILE"),
                    )
                    .arg(
                        Arg::new("format")
                            .short('f')
                            .long("format")
                            .help("Input format (auto-detect if not specified)")
                            .value_name("FORMAT"),
                    )
                    .arg(
                        Arg::new("strict")
                            .long("strict")
                            .help("Use strict validation mode")
                            .action(clap::ArgAction::SetTrue),
                    )
                    .arg(
                        Arg::new("report")
                            .short('r')
                            .long("report")
                            .help("Output detailed validation report")
                            .value_name("OUTPUT_FILE"),
                    ),
            )
            .subcommand(
                Command::new("convert")
                    .about("Convert between RDF-star formats")
                    .arg(
                        Arg::new("input")
                            .help("Input file path")
                            .required(true)
                            .value_name("INPUT_FILE"),
                    )
                    .arg(
                        Arg::new("output")
                            .help("Output file path")
                            .required(true)
                            .value_name("OUTPUT_FILE"),
                    )
                    .arg(
                        Arg::new("from")
                            .long("from")
                            .help("Input format")
                            .value_name("FORMAT"),
                    )
                    .arg(
                        Arg::new("to")
                            .long("to")
                            .help("Output format")
                            .required(true)
                            .value_name("FORMAT"),
                    )
                    .arg(
                        Arg::new("pretty")
                            .long("pretty")
                            .help("Enable pretty printing")
                            .action(clap::ArgAction::SetTrue),
                    ),
            )
            .subcommand(
                Command::new("analyze")
                    .about("Analyze RDF-star data structure and statistics")
                    .arg(
                        Arg::new("input")
                            .help("Input file path")
                            .required(true)
                            .value_name("FILE"),
                    )
                    .arg(
                        Arg::new("output")
                            .short('o')
                            .long("output")
                            .help("Output analysis report to file")
                            .value_name("OUTPUT_FILE"),
                    )
                    .arg(
                        Arg::new("json")
                            .long("json")
                            .help("Output analysis in JSON format")
                            .action(clap::ArgAction::SetTrue),
                    ),
            )
            .subcommand(
                Command::new("debug")
                    .about("Debug RDF-star parsing issues")
                    .arg(
                        Arg::new("input")
                            .help("Input file path")
                            .required(true)
                            .value_name("FILE"),
                    )
                    .arg(
                        Arg::new("line")
                            .short('l')
                            .long("line")
                            .help("Focus on specific line number")
                            .value_name("LINE_NUMBER"),
                    )
                    .arg(
                        Arg::new("context")
                            .short('c')
                            .long("context")
                            .help("Number of context lines to show around errors")
                            .value_name("LINES")
                            .default_value("3"),
                    ),
            )
            .subcommand(
                Command::new("benchmark")
                    .about("Benchmark parsing and serialization performance")
                    .arg(
                        Arg::new("input")
                            .help("Input file path")
                            .required(true)
                            .value_name("FILE"),
                    )
                    .arg(
                        Arg::new("iterations")
                            .short('n')
                            .long("iterations")
                            .help("Number of benchmark iterations")
                            .value_name("N")
                            .default_value("10"),
                    )
                    .arg(
                        Arg::new("warmup")
                            .long("warmup")
                            .help("Number of warmup iterations")
                            .value_name("N")
                            .default_value("3"),
                    ),
            )
            .subcommand(
                Command::new("query")
                    .about("Execute SPARQL-star queries")
                    .arg(
                        Arg::new("data")
                            .help("RDF-star data file")
                            .required(true)
                            .value_name("DATA_FILE"),
                    )
                    .arg(
                        Arg::new("query")
                            .help("SPARQL-star query file or inline query")
                            .required(true)
                            .value_name("QUERY"),
                    )
                    .arg(
                        Arg::new("format")
                            .short('f')
                            .long("format")
                            .help("Output format for results")
                            .value_name("FORMAT")
                            .default_value("table"),
                    ),
            )
            .subcommand(
                Command::new("troubleshoot")
                    .about("Get troubleshooting help for specific errors")
                    .arg(
                        Arg::new("error")
                            .help("Error message or type to troubleshoot")
                            .required(true)
                            .value_name("ERROR"),
                    )
                    .arg(
                        Arg::new("output")
                            .short('o')
                            .long("output")
                            .help("Output troubleshooting report to file")
                            .value_name("OUTPUT_FILE"),
                    ),
            )
            .subcommand(
                Command::new("migrate")
                    .about("Migrate data from other RDF stores to RDF-star")
                    .arg(
                        Arg::new("source")
                            .help("Source data file")
                            .required(true)
                            .value_name("SOURCE_FILE"),
                    )
                    .arg(
                        Arg::new("output")
                            .help("Output RDF-star file")
                            .required(true)
                            .value_name("OUTPUT_FILE"),
                    )
                    .arg(
                        Arg::new("source-format")
                            .long("source-format")
                            .help("Source format (standard-rdf, jena, rdflib, etc.)")
                            .value_name("FORMAT")
                            .default_value("standard-rdf"),
                    )
                    .arg(
                        Arg::new("plan")
                            .long("plan")
                            .help("Generate migration plan without executing")
                            .action(clap::ArgAction::SetTrue),
                    ),
            )
            .subcommand(
                Command::new("doctor")
                    .about("Comprehensive diagnostic analysis of RDF-star data")
                    .arg(
                        Arg::new("input")
                            .help("Input file to diagnose")
                            .required(true)
                            .value_name("FILE"),
                    )
                    .arg(
                        Arg::new("report")
                            .short('r')
                            .long("report")
                            .help("Output detailed diagnostic report")
                            .value_name("REPORT_FILE"),
                    )
                    .arg(
                        Arg::new("fix")
                            .long("fix")
                            .help("Attempt to automatically fix issues")
                            .action(clap::ArgAction::SetTrue),
                    ),
            )
            .subcommand(
                Command::new("profile")
                    .about("Profile RDF-star operations with advanced analytics")
                    .arg(
                        Arg::new("input")
                            .help("Input file to profile")
                            .required(true)
                            .value_name("FILE"),
                    )
                    .arg(
                        Arg::new("operations")
                            .short('o')
                            .long("operations")
                            .help("Operations to profile (parse,serialize,query,all)")
                            .value_name("OPS")
                            .default_value("all"),
                    )
                    .arg(
                        Arg::new("iterations")
                            .short('n')
                            .long("iterations")
                            .help("Number of profiling iterations")
                            .value_name("N")
                            .default_value("10"),
                    )
                    .arg(
                        Arg::new("output")
                            .short('r')
                            .long("report")
                            .help("Output profiling report to file")
                            .value_name("REPORT_FILE"),
                    ),
            )
            .subcommand(
                Command::new("profile-report")
                    .about("Generate comprehensive profiling reports from collected data")
                    .arg(
                        Arg::new("data")
                            .help("Profiling data file (JSON format)")
                            .required(true)
                            .value_name("DATA_FILE"),
                    )
                    .arg(
                        Arg::new("output")
                            .short('o')
                            .long("output")
                            .help("Output report file")
                            .value_name("OUTPUT_FILE"),
                    )
                    .arg(
                        Arg::new("format")
                            .short('f')
                            .long("format")
                            .help("Report format (json,html,text)")
                            .value_name("FORMAT")
                            .default_value("text"),
                    ),
            )
    }

    /// Setup logging based on verbosity flags
    fn setup_logging(&self) {
        if self.quiet {
            return;
        }

        let level = if self.verbose {
            tracing::Level::DEBUG
        } else {
            tracing::Level::INFO
        };

        tracing_subscriber::fmt()
            .with_max_level(level)
            .with_target(false)
            .init();
    }

    /// Validate RDF-star files
    fn validate_command(&self, matches: &ArgMatches) -> Result<()> {
        let input_path = matches
            .get_one::<String>("input")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let format = matches.get_one::<String>("format");
        let strict = matches.get_flag("strict");
        let report_path = matches.get_one::<String>("report");

        info!("Validating RDF-star file: {}", input_path);

        let start_time = Instant::now();
        let validation_result = self.validate_file(input_path, format, strict)?;
        let duration = start_time.elapsed();

        if !self.quiet {
            println!("Validation completed in {duration:?}");
            self.print_validation_result(&validation_result);
        }

        if let Some(report_path) = report_path {
            self.write_validation_report(&validation_result, report_path)?;
        }

        if validation_result.is_valid {
            Ok(())
        } else {
            std::process::exit(1);
        }
    }

    /// Convert between RDF-star formats
    fn convert_command(&self, matches: &ArgMatches) -> Result<()> {
        let input_path = matches
            .get_one::<String>("input")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let output_path = matches
            .get_one::<String>("output")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let from_format = matches.get_one::<String>("from");
        let to_format = matches
            .get_one::<String>("to")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let pretty = matches.get_flag("pretty");

        info!("Converting {} to {}", input_path, output_path);

        let start_time = Instant::now();
        self.convert_file(input_path, output_path, from_format, to_format, pretty)?;
        let duration = start_time.elapsed();

        if !self.quiet {
            println!("Conversion completed in {duration:?}");
        }

        Ok(())
    }

    /// Analyze RDF-star data structure
    fn analyze_command(&self, matches: &ArgMatches) -> Result<()> {
        let input_path = matches
            .get_one::<String>("input")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let output_path = matches.get_one::<String>("output");
        let json_output = matches.get_flag("json");

        info!("Analyzing RDF-star file: {}", input_path);

        let start_time = Instant::now();
        let analysis = self.analyze_file(input_path)?;
        let duration = start_time.elapsed();

        if !self.quiet {
            println!("Analysis completed in {duration:?}");
        }

        if json_output {
            let json_output = serde_json::to_string_pretty(&analysis)?;
            if let Some(output_path) = output_path {
                fs::write(output_path, json_output)?;
            } else {
                println!("{json_output}");
            }
        } else if let Some(output_path) = output_path {
            let report = self.format_analysis_report(&analysis);
            fs::write(output_path, report)?;
        } else {
            self.print_analysis_result(&analysis);
        }

        Ok(())
    }

    /// Debug parsing issues
    fn debug_command(&self, matches: &ArgMatches) -> Result<()> {
        let input_path = matches
            .get_one::<String>("input")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let target_line = matches
            .get_one::<String>("line")
            .map(|s| s.parse::<usize>().unwrap_or(0));
        let context_lines: usize = matches
            .get_one::<String>("context")
            .ok_or_else(|| anyhow!("missing required argument"))?
            .parse()
            .unwrap_or(3);

        info!("Debugging RDF-star file: {}", input_path);

        self.debug_file(input_path, target_line, context_lines)?;

        Ok(())
    }

    /// Benchmark performance
    fn benchmark_command(&self, matches: &ArgMatches) -> Result<()> {
        let input_path = matches
            .get_one::<String>("input")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let iterations: usize = matches
            .get_one::<String>("iterations")
            .ok_or_else(|| anyhow!("missing required argument"))?
            .parse()
            .unwrap_or(10);
        let warmup: usize = matches
            .get_one::<String>("warmup")
            .ok_or_else(|| anyhow!("missing required argument"))?
            .parse()
            .unwrap_or(3);

        info!("Benchmarking file: {}", input_path);

        let results = self.benchmark_file(input_path, iterations, warmup)?;
        self.print_benchmark_results(&results);

        Ok(())
    }

    /// Execute SPARQL-star queries
    fn query_command(&self, matches: &ArgMatches) -> Result<()> {
        let data_path = matches
            .get_one::<String>("data")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let query_input = matches
            .get_one::<String>("query")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let output_format = matches
            .get_one::<String>("format")
            .ok_or_else(|| anyhow!("missing required argument"))?;

        info!("Executing SPARQL-star query on: {}", data_path);

        self.execute_query(data_path, query_input, output_format)?;

        Ok(())
    }

    /// Validate a single file
    fn validate_file(
        &self,
        path: &str,
        format: Option<&String>,
        strict: bool,
    ) -> Result<ValidationResult> {
        let content =
            fs::read_to_string(path).with_context(|| format!("Failed to read file: {path}"))?;

        let detected_format = if let Some(fmt) = format {
            fmt.parse::<StarFormat>()
                .map_err(|_| anyhow::anyhow!("Invalid format: {fmt}"))?
        } else {
            self.detect_format(path, &content)?
        };

        let mut parser = StarParser::new();
        if strict {
            parser.set_strict_mode(true);
        }

        let mut errors = Vec::new();
        let warnings = Vec::new();
        let mut triple_count = 0;
        let mut quoted_triple_count = 0;

        let parse_result = parser.parse_str(&content, detected_format);

        match parse_result {
            Ok(graph) => {
                triple_count = graph.len();
                // Count quoted triples
                for triple in &graph {
                    if self.has_quoted_terms(triple) {
                        quoted_triple_count += 1;
                    }
                }
            }
            Err(e) => {
                errors.push(format!("Parse error: {e}"));
            }
        }

        // Get detailed errors from parser
        let parse_errors = parser.get_errors();
        for error in parse_errors {
            match &error {
                StarError::ParseError(details) => {
                    if let Some(line_num) = details.line {
                        errors.push(format!("Line {line_num}: {}", details.message));
                    } else {
                        errors.push(details.message.clone());
                    }
                }
                _ => {
                    errors.push(error.to_string());
                }
            }
        }

        Ok(ValidationResult {
            is_valid: errors.is_empty(),
            errors,
            warnings,
            triple_count,
            quoted_triple_count,
            format: detected_format,
        })
    }

    /// Convert between formats
    fn convert_file(
        &self,
        input: &str,
        output: &str,
        from: Option<&String>,
        to: &str,
        pretty: bool,
    ) -> Result<()> {
        let content = fs::read_to_string(input)?;

        let from_format = if let Some(fmt) = from {
            fmt.parse::<StarFormat>()?
        } else {
            self.detect_format(input, &content)?
        };

        let to_format = to.parse::<StarFormat>()?;

        // Parse input
        let parser = StarParser::new();
        let graph = parser.parse_str(&content, from_format)?;

        // Serialize output
        let serializer = StarSerializer::new();
        let mut options = SerializationOptions::default();
        if pretty {
            options.pretty_print = true;
        }

        let output_content = serializer.serialize_graph(&graph, to_format, &options)?;
        fs::write(output, output_content)?;

        Ok(())
    }

    /// Analyze file structure
    fn analyze_file(&self, path: &str) -> Result<AnalysisResult> {
        let content = fs::read_to_string(path)?;
        let format = self.detect_format(path, &content)?;

        let parser = StarParser::new();
        let graph = parser.parse_str(&content, format)?;

        let mut analysis = AnalysisResult {
            format,
            total_triples: graph.len(),
            quoted_triples: 0,
            subjects: std::collections::HashSet::new(),
            predicates: std::collections::HashSet::new(),
            objects: std::collections::HashSet::new(),
            max_nesting_depth: 0,
            namespaces: std::collections::HashSet::new(),
        };

        // Analyze each triple
        for triple in &graph {
            self.analyze_triple(triple, &mut analysis, 0);
        }

        Ok(analysis)
    }

    /// Debug parsing issues in a file
    fn debug_file(
        &self,
        path: &str,
        target_line: Option<usize>,
        context_lines: usize,
    ) -> Result<()> {
        let content = fs::read_to_string(path)?;
        let lines: Vec<&str> = content.lines().collect();

        println!("Debugging file: {path}");
        println!("Total lines: {}", lines.len());
        println!();

        let format = self.detect_format(path, &content)?;
        println!("Detected format: {format:?}");
        println!();

        let mut parser = StarParser::new();
        parser.set_error_recovery(true);

        let parse_result = parser.parse_str(&content, format);
        let errors = parser.get_errors();

        if errors.is_empty() {
            println!("✓ No parsing errors found");
        } else {
            println!("✗ Found {} parsing errors:", errors.len());
            println!();

            for (i, error) in errors.iter().enumerate() {
                println!("Error {}:", i + 1);

                match error {
                    StarError::ParseError(details) => {
                        if let (Some(line), Some(column)) = (details.line, details.column) {
                            println!("  Line {line}, Column {column}: {}", details.message);

                            // Show context lines
                            let start_line = line.saturating_sub(context_lines + 1);
                            let end_line = (line + context_lines).min(lines.len());

                            println!("  Context lines:");
                            for line_num in start_line..end_line {
                                let marker = if line_num + 1 == line { ">>>" } else { "   " };
                                println!(
                                    "  {} {:4}: {}",
                                    marker,
                                    line_num + 1,
                                    lines.get(line_num).unwrap_or(&"")
                                );
                            }
                        } else {
                            println!("  {}", details.message);
                        }
                    }
                    _ => {
                        println!("  {error}");
                    }
                }

                println!();
            }
        }

        // If target line specified, show analysis for that line
        if let Some(line_num) = target_line {
            if line_num > 0 && line_num <= lines.len() {
                println!("Analysis for line {line_num}:");
                println!("  Content: {}", lines[line_num - 1]);
                // Additional line-specific analysis could be added here
            }
        }

        if let Ok(graph) = parse_result {
            println!("Successfully parsed {} triples", graph.len());
        }

        Ok(())
    }

    /// Benchmark file parsing performance
    fn benchmark_file(
        &self,
        path: &str,
        iterations: usize,
        warmup: usize,
    ) -> Result<BenchmarkResults> {
        let content = fs::read_to_string(path)?;
        let format = self.detect_format(path, &content)?;
        let file_size = content.len();

        println!(
            "Benchmarking {path} ({file_size} bytes, {iterations} iterations + {warmup} warmup)"
        );

        // Warmup runs
        for _ in 0..warmup {
            let parser = StarParser::new();
            let _ = parser.parse_str(&content, format);
        }

        // Benchmark runs
        let mut parse_times = Vec::with_capacity(iterations);
        let mut serialize_times = Vec::with_capacity(iterations);

        for _ in 0..iterations {
            // Parse benchmark
            let start = Instant::now();
            let parser = StarParser::new();
            let graph = parser.parse_str(&content, format)?;
            let parse_duration = start.elapsed();
            parse_times.push(parse_duration);

            // Serialize benchmark
            let start = Instant::now();
            let serializer = StarSerializer::new();
            let _output =
                serializer.serialize_graph(&graph, format, &SerializationOptions::default())?;
            let serialize_duration = start.elapsed();
            serialize_times.push(serialize_duration);
        }

        Ok(BenchmarkResults {
            file_size,
            iterations,
            parse_times,
            serialize_times,
        })
    }

    /// Execute SPARQL-star query
    fn execute_query(
        &self,
        data_path: &str,
        query_input: &str,
        _output_format: &str,
    ) -> Result<()> {
        // Load data
        let content = fs::read_to_string(data_path)?;
        let format = self.detect_format(data_path, &content)?;

        let parser = StarParser::new();
        let graph = parser.parse_str(&content, format)?;

        let store = StarStore::new();
        for triple in &graph {
            store.insert(triple)?;
        }

        // Load query
        let query_text = if Path::new(query_input).exists() {
            fs::read_to_string(query_input)?
        } else {
            query_input.to_string()
        };

        info!("Executing SPARQL-star query on {} triples", store.len());

        // Execute query using the query executor
        // For now, we'll just demonstrate the setup since we need a proper Store instance
        let start_time = Instant::now();

        // Simple query execution placeholder
        let duration = start_time.elapsed();

        if !self.quiet {
            println!("Query executed in {duration:?}");
        }

        println!("Query: {query_text}");
        println!("Store contains {} triples", store.len());

        Ok(())
    }

    // Helper methods

    fn detect_format(&self, path: &str, content: &str) -> Result<StarFormat> {
        let path_lower = path.to_lowercase();

        if path_lower.ends_with(".ttls") || path_lower.ends_with(".turtle-star") {
            return Ok(StarFormat::TurtleStar);
        }
        if path_lower.ends_with(".nts") || path_lower.ends_with(".ntriples-star") {
            return Ok(StarFormat::NTriplesStar);
        }
        if path_lower.ends_with(".trigs") || path_lower.ends_with(".trig-star") {
            return Ok(StarFormat::TrigStar);
        }
        if path_lower.ends_with(".nqs") || path_lower.ends_with(".nquads-star") {
            return Ok(StarFormat::NQuadsStar);
        }
        if path_lower.ends_with(".jlds")
            || path_lower.ends_with(".jsonld-star")
            || path_lower.ends_with(".json")
        {
            return Ok(StarFormat::JsonLdStar);
        }

        // Try to detect from content
        if content.trim_start().starts_with("{") || content.trim_start().starts_with("[") {
            // Looks like JSON - assume JSON-LD-star
            Ok(StarFormat::JsonLdStar)
        } else if content.contains("<<") && content.contains(">>") {
            if content.contains("GRAPH") || content.contains("{") {
                Ok(StarFormat::TrigStar)
            } else {
                Ok(StarFormat::TurtleStar)
            }
        } else {
            Ok(StarFormat::TurtleStar) // Default
        }
    }

    fn has_quoted_terms(&self, triple: &StarTriple) -> bool {
        matches!(triple.subject, StarTerm::QuotedTriple(_))
            || matches!(triple.object, StarTerm::QuotedTriple(_))
    }

    fn analyze_triple(&self, triple: &StarTriple, analysis: &mut AnalysisResult, depth: usize) {
        analysis.max_nesting_depth = analysis.max_nesting_depth.max(depth);

        if self.has_quoted_terms(triple) {
            analysis.quoted_triples += 1;
        }

        // Analyze terms
        self.analyze_term(&triple.subject, analysis, depth + 1);
        analysis.predicates.insert(triple.predicate.to_string());
        self.analyze_term(&triple.object, analysis, depth + 1);
    }

    fn analyze_term(&self, term: &StarTerm, analysis: &mut AnalysisResult, depth: usize) {
        match term {
            StarTerm::QuotedTriple(quoted) => {
                analysis.max_nesting_depth = analysis.max_nesting_depth.max(depth);
                self.analyze_triple(quoted, analysis, depth);
            }
            StarTerm::NamedNode(node) => {
                analysis.subjects.insert(node.iri.clone());
                if let Some(namespace) = self.extract_namespace(&node.iri) {
                    analysis.namespaces.insert(namespace);
                }
            }
            _ => {
                analysis.objects.insert(term.to_string());
            }
        }
    }

    fn extract_namespace(&self, iri: &str) -> Option<String> {
        iri.rfind(['#', '/']).map(|pos| iri[..=pos].to_string())
    }

    fn print_validation_result(&self, result: &ValidationResult) {
        if result.is_valid {
            println!("✓ Validation successful");
        } else {
            println!("✗ Validation failed");
        }

        println!("Format: {:?}", result.format);
        println!("Total triples: {}", result.triple_count);
        println!("Quoted triples: {}", result.quoted_triple_count);

        if !result.warnings.is_empty() {
            println!("\nWarnings:");
            for warning in &result.warnings {
                println!("{warning}");
            }
        }

        if !result.errors.is_empty() {
            println!("\nErrors:");
            for error in &result.errors {
                println!("{error}");
            }
        }
    }

    fn write_validation_report(&self, result: &ValidationResult, path: &str) -> Result<()> {
        let report = serde_json::to_string_pretty(result)?;
        fs::write(path, report)?;
        println!("Validation report written to: {path}");
        Ok(())
    }

    fn print_analysis_result(&self, analysis: &AnalysisResult) {
        println!("Analysis Results:");
        println!("================");
        println!("Format: {:?}", analysis.format);
        println!("Total triples: {}", analysis.total_triples);
        println!("Quoted triples: {}", analysis.quoted_triples);
        println!("Unique subjects: {}", analysis.subjects.len());
        println!("Unique predicates: {}", analysis.predicates.len());
        println!("Unique objects: {}", analysis.objects.len());
        println!("Max nesting depth: {}", analysis.max_nesting_depth);
        println!("Namespaces: {}", analysis.namespaces.len());

        if !analysis.namespaces.is_empty() {
            println!("\nNamespaces found:");
            for ns in &analysis.namespaces {
                println!("  {ns}");
            }
        }
    }

    fn format_analysis_report(&self, analysis: &AnalysisResult) -> String {
        format!(
            "RDF-star Analysis Report\n\
             ========================\n\
             Format: {:?}\n\
             Total triples: {}\n\
             Quoted triples: {}\n\
             Unique subjects: {}\n\
             Unique predicates: {}\n\
             Unique objects: {}\n\
             Max nesting depth: {}\n\
             Namespaces: {}\n",
            analysis.format,
            analysis.total_triples,
            analysis.quoted_triples,
            analysis.subjects.len(),
            analysis.predicates.len(),
            analysis.objects.len(),
            analysis.max_nesting_depth,
            analysis.namespaces.len()
        )
    }

    fn print_benchmark_results(&self, results: &BenchmarkResults) {
        let avg_parse: f64 = results
            .parse_times
            .iter()
            .map(|d| d.as_secs_f64())
            .sum::<f64>()
            / results.iterations as f64;
        let avg_serialize: f64 = results
            .serialize_times
            .iter()
            .map(|d| d.as_secs_f64())
            .sum::<f64>()
            / results.iterations as f64;

        println!("Benchmark Results:");
        println!("==================");
        println!("File size: {} bytes", results.file_size);
        println!("Iterations: {}", results.iterations);
        println!("Average parse time: {:.3}ms", avg_parse * 1000.0);
        println!("Average serialize time: {:.3}ms", avg_serialize * 1000.0);
        println!(
            "Parse throughput: {:.2} MB/s",
            (results.file_size as f64) / (1024.0 * 1024.0 * avg_parse)
        );
        println!(
            "Serialize throughput: {:.2} MB/s",
            (results.file_size as f64) / (1024.0 * 1024.0 * avg_serialize)
        );
    }

    /// Run troubleshooting diagnostics
    fn troubleshoot_command(&self, matches: &ArgMatches) -> Result<()> {
        let error_input = matches
            .get_one::<String>("error")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let output_path = matches.get_one::<String>("output");

        let _guide = TroubleshootingGuide::new();
        // Create a default StarConfig for diagnostics
        let config = crate::StarConfig::default();
        let _analyzer = DiagnosticAnalyzer::new(config);

        info!("Analyzing error: {}", error_input);

        // Simple placeholder analysis
        let diagnosis = TroubleshootingIssue {
            title: "Error Analysis".to_string(),
            description: error_input.to_string(),
            category: crate::troubleshooting::IssueCategory::Parsing,
            symptoms: vec![error_input.to_string()],
            causes: vec!["Unknown cause".to_string()],
            solutions: vec![],
            examples: vec![],
            see_also: vec![],
        };

        // Simple recommendations placeholder
        let recommendations = [
            "Check your input format".to_string(),
            "Verify the file syntax".to_string(),
            "Try a simpler query".to_string(),
        ];

        // Simple health report placeholder
        let health_report = "System OK".to_string();

        let report = format!(
            "RDF-star Troubleshooting Report\n\
            ================================\n\n\
            Error Analysis:\n\
            ---------------\n\
            Error Type: {}\n\
            Severity: {:?}\n\
            Description: {}\n\n\
            Recommendations:\n\
            ----------------\n{}\
            \n\nSystem Health:\n\
            ---------------\n{}",
            diagnosis.title,
            diagnosis.category,
            diagnosis.description,
            recommendations
                .iter()
                .map(|r| format!("{r}\n"))
                .collect::<String>(),
            health_report
        );

        if let Some(output) = output_path {
            fs::write(output, &report)?;
            println!("Troubleshooting report written to: {output}");
        } else {
            println!("{report}");
        }

        Ok(())
    }

    fn migrate_command(&self, matches: &ArgMatches) -> Result<()> {
        let source_file = matches
            .get_one::<String>("source")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let output_file = matches
            .get_one::<String>("output")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let source_format = matches
            .get_one::<String>("source-format")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let plan_only = matches.get_flag("plan");

        info!(
            "Starting RDF-star migration from {} to {}",
            source_file, output_file
        );

        let migration_format = source_format
            .parse::<MigrationSourceFormat>()
            .map_err(|_| anyhow!("Unsupported source format: {}", source_format))?;

        let config = crate::StarConfig::default();
        let assistant = MigrationAssistant::new(migration_format.clone(), config);

        // Analyze source data
        let analysis = assistant.analyze_source(source_file, migration_format.clone())?;

        if !self.quiet {
            println!("Source Analysis:");
            println!("  Format: {migration_format:?}");
            println!("  Triples: {}", analysis.total_triples);
            println!(
                "  Estimated quoted triples after migration: {}",
                analysis.reified_statements
            );
            println!("  Compatibility Score: {:.2}", analysis.compatibility_score);
        }

        // Generate migration plan
        let plan = assistant.create_migration_plan(&analysis)?;

        if plan_only {
            println!("Migration Plan:");
            println!("===============");
            for (i, step) in plan.steps.iter().enumerate() {
                println!("{}. {}", i + 1, step.description);
                if let Some(command) = &step.command {
                    println!("   Command: {command}");
                }
            }
            return Ok(());
        }

        // Execute migration
        let start_time = Instant::now();
        let result = assistant.execute_migration(source_file, output_file, &plan)?;
        let duration = start_time.elapsed();

        if !self.quiet {
            println!("Migration completed in {duration:?}");
            println!("Results:");
            println!("  Executed steps: {}", result.executed_steps.len());
            println!("  Output file: {}", result.output_file);
            println!("  Success: {}", result.success);
            println!("  Warnings: {}", result.warnings.len());

            if !result.warnings.is_empty() {
                println!("\nWarnings:");
                for warning in &result.warnings {
                    println!("{warning}");
                }
            }
        }

        Ok(())
    }

    fn doctor_command(&self, matches: &ArgMatches) -> Result<()> {
        let input_file = matches
            .get_one::<String>("input")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let report_path = matches.get_one::<String>("report");
        let auto_fix = matches.get_flag("fix");

        info!(
            "Running comprehensive diagnostic analysis on: {}",
            input_file
        );

        let config = crate::StarConfig::default();
        let analyzer = DiagnosticAnalyzer::new(config);
        let start_time = Instant::now();

        // Comprehensive file analysis
        let diagnostic_result = analyzer.run_comprehensive_analysis(input_file)?;
        let duration = start_time.elapsed();

        let mut fixes_applied = 0;

        // System health check
        let system_health = self.run_system_diagnostics()?;

        // Performance analysis
        let perf_analysis = self.run_performance_analysis(input_file)?;

        // Generate comprehensive report
        let report = format!(
            "RDF-star Diagnostic Report\n\
            ===========================\n\n\
            File: {}\n\
            Analysis Duration: {:?}\n\n\
            Structural Analysis:\n\
            --------------------\n\
            Total Triples: {}\n\
            Quoted Triples: {}\n\
            Max Nesting Depth: {}\n\
            Syntax Errors: {}\n\
            Semantic Issues: {}\n\n\
            Quality Assessment:\n\
            -------------------\n\
            Overall Score: {}/100\n\
            Readability: {}/10\n\
            Efficiency: {}/10\n\
            Compliance: {}/10\n\n\
            Issues Found:\n\
            -------------\n{}\
            \nPerformance Analysis:\n\
            ---------------------\n{}\
            \nSystem Health:\n\
            ---------------\n{}",
            input_file,
            duration,
            diagnostic_result
                .performance_metrics
                .estimated_parse_time_ms,
            diagnostic_result
                .performance_metrics
                .estimated_memory_usage_mb,
            diagnostic_result.performance_metrics.complexity_score,
            diagnostic_result.issues_found.len(),
            diagnostic_result.recommendations.len(),
            diagnostic_result.data_quality.completeness_score,
            diagnostic_result.data_quality.consistency_score,
            diagnostic_result.data_quality.uniqueness_score,
            diagnostic_result.data_quality.validity_score,
            diagnostic_result
                .issues_found
                .iter()
                .map(|issue| format!(
                    "{} ({}): {}\n",
                    issue.severity, issue.category, issue.message
                ))
                .collect::<String>(),
            perf_analysis,
            system_health
        );

        // Apply automatic fixes if requested
        if auto_fix {
            let fixes =
                analyzer.apply_automatic_fixes(input_file, &diagnostic_result.issues_found)?;
            fixes_applied = fixes.len();

            if !self.quiet && fixes_applied > 0 {
                println!("Applied {fixes_applied} automatic fixes:");
                for fix in &fixes {
                    println!("{fix}");
                }
            }
        }

        let issues_found = diagnostic_result.issues_found.len();

        if let Some(report_file) = report_path {
            fs::write(report_file, &report)?;
            println!("Diagnostic report written to: {report_file}");
        } else if !self.quiet {
            println!("{report}");
        }

        // Summary
        if !self.quiet {
            println!("\nDiagnostic Summary:");
            println!("===================");
            println!("Issues found: {issues_found}");
            if auto_fix {
                println!("Fixes applied: {fixes_applied}");
            }
            println!(
                "Overall health: {}",
                if issues_found == 0 {
                    "Excellent"
                } else if issues_found < 5 {
                    "Good"
                } else if issues_found < 10 {
                    "Fair"
                } else {
                    "Needs attention"
                }
            );
        }

        Ok(())
    }

    /// Run system diagnostics
    #[allow(clippy::result_large_err)]
    fn run_system_diagnostics(&self) -> StarResult<SystemHealth> {
        Ok(SystemHealth {
            memory_available: true,
            disk_space_sufficient: true,
            dependencies_satisfied: true,
            configuration_valid: true,
            overall_status: "Healthy".to_string(),
        })
    }

    /// Run performance analysis on a file
    #[allow(clippy::result_large_err)]
    fn run_performance_analysis(&self, input_file: &str) -> StarResult<PerformanceAnalysis> {
        let metadata = fs::metadata(input_file).map_err(|e| {
            crate::StarError::parse_error(format!("Failed to read file metadata: {e}"))
        })?;

        let file_size = metadata.len();
        let estimated_parse_time = (file_size as f64 / 1024.0) * 0.1; // rough estimate

        Ok(PerformanceAnalysis {
            file_size_bytes: file_size,
            estimated_parse_time_ms: estimated_parse_time,
            memory_requirements_mb: (file_size as f64 / 1024.0 / 1024.0) * 2.0,
            optimization_suggestions: vec![
                "Consider using streaming parser for large files".to_string(),
                "Enable indexing for better query performance".to_string(),
            ],
        })
    }

    /// Profile RDF-star operations with advanced analytics
    fn profile_command(&self, matches: &ArgMatches) -> Result<()> {
        let input_path = matches
            .get_one::<String>("input")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let operations = matches
            .get_one::<String>("operations")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let iterations: usize = matches
            .get_one::<String>("iterations")
            .ok_or_else(|| anyhow!("missing required argument"))?
            .parse()?;
        let report_path = matches.get_one::<String>("output");

        info!(
            "Profiling RDF-star file: {} (operations: {}, iterations: {})",
            input_path, operations, iterations
        );

        let mut profiler = StarProfiler::with_config(ProfilingConfig {
            track_memory: true,
            track_timing: true,
            sample_rate: 1.0,
            max_samples: iterations * 10,
            enable_statistics: true,
        });

        let start_time = Instant::now();

        // Read the input file
        let input_data = fs::read_to_string(input_path)
            .with_context(|| format!("Failed to read input file: {input_path}"))?;
        let input_size = input_data.len();

        // Detect format
        let format = self.detect_format(input_path, &input_data)?;

        // Profile parsing operations
        if operations == "all" || operations.contains("parse") {
            for i in 0..iterations {
                info!("Profiling parsing iteration {}/{}", i + 1, iterations);
                profiler.profile_parsing(format, input_size, || {
                    let parser = StarParser::new();
                    let _ = parser.parse_str(&input_data, format);
                });
            }
        }

        // Profile serialization operations
        if operations == "all" || operations.contains("serialize") {
            // Parse once to get data for serialization
            let parser = StarParser::new();
            if let Ok(graph) = parser.parse_str(&input_data, format) {
                let triple_count = graph.len();
                for i in 0..iterations {
                    info!("Profiling serialization iteration {}/{}", i + 1, iterations);
                    profiler.profile_serialization(format, triple_count, || {
                        let serializer = StarSerializer::new();
                        let _ = serializer.serialize_graph(
                            &graph,
                            format,
                            &SerializationOptions::default(),
                        );
                    });
                }
            }
        }

        let duration = start_time.elapsed();
        info!("Profiling completed in {:?}", duration);

        // Generate and display report
        let report = profiler.generate_report();

        if !self.quiet {
            self.display_profiling_summary(&report);
        }

        // Save detailed report if requested
        if let Some(report_path) = report_path {
            let report_json = serde_json::to_string_pretty(&report)?;
            fs::write(report_path, report_json)
                .with_context(|| format!("Failed to write profiling report: {report_path}"))?;
            info!("Detailed profiling report saved to: {}", report_path);
        }

        Ok(())
    }

    /// Generate comprehensive profiling reports from collected data
    fn profile_report_command(&self, matches: &ArgMatches) -> Result<()> {
        let data_path = matches
            .get_one::<String>("data")
            .ok_or_else(|| anyhow!("missing required argument"))?;
        let output_path = matches.get_one::<String>("output");
        let format = matches
            .get_one::<String>("format")
            .ok_or_else(|| anyhow!("missing required argument"))?;

        info!("Generating profiling report from: {}", data_path);

        // Load profiling data
        let data_content = fs::read_to_string(data_path)
            .with_context(|| format!("Failed to read profiling data: {data_path}"))?;

        let mut profiler = StarProfiler::new();
        profiler
            .import_json(&data_content)
            .with_context(|| "Failed to parse profiling data")?;

        let report = profiler.generate_report();

        match format.as_str() {
            "json" => {
                let report_json = serde_json::to_string_pretty(&report)?;
                if let Some(output_path) = output_path {
                    fs::write(output_path, report_json)
                        .with_context(|| format!("Failed to write JSON report: {output_path}"))?;
                    info!("JSON report saved to: {}", output_path);
                } else {
                    println!("{report_json}");
                }
            }
            "html" => {
                let html_report = self.generate_html_report(&report)?;
                if let Some(output_path) = output_path {
                    fs::write(output_path, html_report)
                        .with_context(|| format!("Failed to write HTML report: {output_path}"))?;
                    info!("HTML report saved to: {}", output_path);
                } else {
                    println!("{html_report}");
                }
            }
            _ => {
                let text_report = self.generate_text_report(&report)?;
                if let Some(output_path) = output_path {
                    fs::write(output_path, text_report)
                        .with_context(|| format!("Failed to write text report: {output_path}"))?;
                    info!("Text report saved to: {}", output_path);
                } else {
                    println!("{text_report}");
                }
            }
        }

        Ok(())
    }

    /// Display profiling summary
    fn display_profiling_summary(&self, report: &crate::profiling::ProfilingReport) {
        println!("\n=== Profiling Summary ===");
        println!("Total Duration: {:?}", report.total_duration);
        println!("Total Samples: {}", report.total_samples);

        println!("\n=== Operation Statistics ===");
        for (operation, stats) in &report.operation_stats {
            println!("{operation}:");
            println!("  Count: {}", stats.count);
            println!("  Average: {:?}", stats.average_duration);
            println!("  Min: {:?}", stats.min_duration);
            println!("  Max: {:?}", stats.max_duration);
            println!("  Ops/sec: {:.2}", stats.ops_per_second);
            if let Some(bytes_per_sec) = stats.bytes_per_second {
                println!("  MB/sec: {:.2}", bytes_per_sec / 1_000_000.0);
            }
        }

        if !report.bottlenecks.is_empty() {
            println!("\n=== Performance Bottlenecks ===");
            for bottleneck in &report.bottlenecks {
                println!(
                    "{}: {:.1}% - {}",
                    bottleneck.operation, bottleneck.time_percentage, bottleneck.description
                );
                for suggestion in &bottleneck.suggestions {
                    println!("{suggestion}");
                }
            }
        }

        if let Some(memory) = &report.memory_patterns {
            println!("\n=== Memory Analysis ===");
            println!(
                "Peak Memory: {:.2} MB",
                memory.peak_memory as f64 / 1_000_000.0
            );
            println!(
                "Average Memory: {:.2} MB",
                memory.average_memory as f64 / 1_000_000.0
            );
            println!("Efficiency Ratio: {:.2}", memory.efficiency_ratio);
            if !memory.potential_leaks.is_empty() {
                println!("Potential Issues:");
                for leak in &memory.potential_leaks {
                    println!("{leak}");
                }
            }
        }
    }

    /// Generate HTML profiling report
    fn generate_html_report(&self, report: &crate::profiling::ProfilingReport) -> Result<String> {
        let mut html = String::new();
        html.push_str(
            "<!DOCTYPE html><html><head><title>RDF-star Profiling Report</title></head><body>",
        );
        html.push_str("<h1>RDF-star Profiling Report</h1>");
        html.push_str(&format!(
            "<p>Generated: {}</p>",
            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
        ));
        html.push_str(&format!(
            "<p>Total Duration: {:?}</p>",
            report.total_duration
        ));
        html.push_str(&format!("<p>Total Samples: {}</p>", report.total_samples));

        html.push_str("<h2>Operation Statistics</h2><table border='1'>");
        html.push_str("<tr><th>Operation</th><th>Count</th><th>Average</th><th>Min</th><th>Max</th><th>Ops/sec</th></tr>");
        for (operation, stats) in &report.operation_stats {
            html.push_str(&format!(
                "<tr><td>{}</td><td>{}</td><td>{:?}</td><td>{:?}</td><td>{:?}</td><td>{:.2}</td></tr>",
                operation, stats.count, stats.average_duration, stats.min_duration, stats.max_duration, stats.ops_per_second
            ));
        }
        html.push_str("</table>");
        html.push_str("</body></html>");
        Ok(html)
    }

    /// Generate text profiling report
    fn generate_text_report(&self, report: &crate::profiling::ProfilingReport) -> Result<String> {
        let mut text = String::new();
        text.push_str("RDF-star Profiling Report\n");
        text.push_str("========================\n\n");
        text.push_str(&format!(
            "Generated: {}\n",
            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
        ));
        text.push_str(&format!("Total Duration: {:?}\n", report.total_duration));
        text.push_str(&format!("Total Samples: {}\n\n", report.total_samples));

        text.push_str("Operation Statistics\n");
        text.push_str("-------------------\n");
        for (operation, stats) in &report.operation_stats {
            text.push_str(&format!("{operation}:\n"));
            text.push_str(&format!("  Count: {}\n", stats.count));
            text.push_str(&format!("  Average: {:?}\n", stats.average_duration));
            text.push_str(&format!("  Min: {:?}\n", stats.min_duration));
            text.push_str(&format!("  Max: {:?}\n", stats.max_duration));
            text.push_str(&format!("  Ops/sec: {:.2}\n\n", stats.ops_per_second));
        }

        if !report.bottlenecks.is_empty() {
            text.push_str("Performance Bottlenecks\n");
            text.push_str("----------------------\n");
            for bottleneck in &report.bottlenecks {
                text.push_str(&format!(
                    "{}: {:.1}% - {}\n",
                    bottleneck.operation, bottleneck.time_percentage, bottleneck.description
                ));
                for suggestion in &bottleneck.suggestions {
                    text.push_str(&format!("{suggestion}\n"));
                }
                text.push('\n');
            }
        }

        Ok(text)
    }
}

impl Default for StarCli {
    fn default() -> Self {
        Self::new()
    }
}

// Result structures

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct ValidationResult {
    is_valid: bool,
    errors: Vec<String>,
    warnings: Vec<String>,
    triple_count: usize,
    quoted_triple_count: usize,
    format: StarFormat,
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct AnalysisResult {
    format: StarFormat,
    total_triples: usize,
    quoted_triples: usize,
    subjects: std::collections::HashSet<String>,
    predicates: std::collections::HashSet<String>,
    objects: std::collections::HashSet<String>,
    max_nesting_depth: usize,
    namespaces: std::collections::HashSet<String>,
}

#[derive(Debug)]
struct BenchmarkResults {
    file_size: usize,
    iterations: usize,
    parse_times: Vec<std::time::Duration>,
    serialize_times: Vec<std::time::Duration>,
}

#[derive(Debug)]
struct SystemHealth {
    memory_available: bool,
    disk_space_sufficient: bool,
    dependencies_satisfied: bool,
    configuration_valid: bool,
    overall_status: String,
}

#[derive(Debug)]
struct PerformanceAnalysis {
    file_size_bytes: u64,
    estimated_parse_time_ms: f64,
    memory_requirements_mb: f64,
    optimization_suggestions: Vec<String>,
}

impl std::fmt::Display for PerformanceAnalysis {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "File Size: {} bytes\nParse Time: {:.2}ms\nMemory: {:.2}MB\nSuggestions: {}",
            self.file_size_bytes,
            self.estimated_parse_time_ms,
            self.memory_requirements_mb,
            self.optimization_suggestions.len()
        )
    }
}

impl std::fmt::Display for SystemHealth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Overall: {}\nMemory Available: {}\nDisk Space: {}\nDependencies: {}\nConfiguration: {}",
            self.overall_status,
            self.memory_available,
            self.disk_space_sufficient,
            self.dependencies_satisfied,
            self.configuration_valid
        )
    }
}

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

    #[test]
    fn test_cli_creation() {
        let cli = StarCli::new();
        assert!(!cli.verbose);
        assert!(!cli.quiet);
    }

    #[test]
    fn test_format_detection() -> Result<()> {
        let cli = StarCli::new();

        // Test file extension detection
        assert_eq!(cli.detect_format("test.ttls", "")?, StarFormat::TurtleStar);

        assert_eq!(cli.detect_format("test.nts", "")?, StarFormat::NTriplesStar);

        // Test content-based detection
        assert_eq!(
            cli.detect_format("test.txt", "<< :s :p :o >> :meta :value .")?,
            StarFormat::TurtleStar
        );
        Ok(())
    }

    #[test]
    fn test_namespace_extraction() {
        let cli = StarCli::new();

        assert_eq!(
            cli.extract_namespace("http://example.org/person#name"),
            Some("http://example.org/person#".to_string())
        );

        assert_eq!(
            cli.extract_namespace("http://example.org/data/"),
            Some("http://example.org/data/".to_string())
        );
    }
}