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
//! Interactive REPL mode for OxiRS (Alpha Implementation)
//!
//! Provides an interactive shell for SPARQL queries with real execution

use crate::cli::formatters::{
    create_formatter, Binding, QueryResults as FormatterQueryResults, RdfTerm,
};
use crate::cli::sparql_autocomplete::SparqlAutocompleteProvider;
use crate::cli::syntax_highlighting::{highlight_sparql, HighlightConfig};
use crate::cli::CliResult;
use oxirs_core::model::{Predicate, Subject, Term};
use oxirs_core::rdf_store::{OxirsQueryResults, QueryResults as CoreQueryResults, RdfStore};
use rustyline::error::ReadlineError;
use rustyline::history::DefaultHistory;
use rustyline::Editor;
use rustyline_derive::{Helper, Highlighter, Validator};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::time::Instant;
use strsim; // Fuzzy string matching

/// SPARQL query helper for readline with enhanced context-aware completion
#[derive(Helper, Highlighter, Validator)]
struct SparqlHelper {
    autocomplete_provider: SparqlAutocompleteProvider,
}

impl SparqlHelper {
    fn new() -> Self {
        Self {
            autocomplete_provider: SparqlAutocompleteProvider::new(),
        }
    }
}

impl rustyline::completion::Completer for SparqlHelper {
    type Candidate = String;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &rustyline::Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
        use crate::cli::completion::{CompletionContext, CompletionProvider};

        // Create completion context from the current line
        let context = CompletionContext::from_line(line, pos);

        // Get completions from the SPARQL autocomplete provider
        let completions = self.autocomplete_provider.get_completions(&context);

        // Find start position for completion (start of current word)
        let line_before = &line[..pos];
        let start = line_before
            .rfind(char::is_whitespace)
            .map(|i| i + 1)
            .unwrap_or(0);

        // Convert CompletionItem to rustyline's String candidates
        let candidates: Vec<String> = completions
            .into_iter()
            .map(|item| item.replacement)
            .collect();

        Ok((start, candidates))
    }
}

impl rustyline::hint::Hinter for SparqlHelper {
    type Hint = String;

    fn hint(&self, line: &str, pos: usize, _ctx: &rustyline::Context<'_>) -> Option<Self::Hint> {
        if pos < line.len() {
            return None;
        }

        let line_upper = line.to_uppercase();

        // Provide hints based on current context
        if line_upper.starts_with("SELECT") && !line_upper.contains("WHERE") {
            Some(" WHERE { ?s ?p ?o }".to_string())
        } else if line_upper.starts_with("PREFIX")
            && line.matches(':').count() == 1
            && !line.contains('<')
        {
            Some(" <http://example.org/>".to_string())
        } else if line_upper.ends_with("WHERE") {
            Some(" { ?s ?p ?o }".to_string())
        } else {
            None
        }
    }
}

/// Query session data
#[derive(Debug, Clone, Serialize, Deserialize)]
struct QuerySession {
    /// Session name
    name: String,
    /// Dataset connected to
    dataset: String,
    /// Queries executed in this session
    queries: Vec<String>,
    /// Timestamp of session creation
    created_at: String,
    /// Last modified timestamp
    modified_at: String,
}

impl QuerySession {
    /// Create a new session
    fn new(name: String, dataset: String) -> Self {
        let now = chrono::Local::now().to_rfc3339();
        Self {
            name,
            dataset,
            queries: Vec::new(),
            created_at: now.clone(),
            modified_at: now,
        }
    }

    /// Add a query to the session
    fn add_query(&mut self, query: String) {
        self.queries.push(query);
        self.modified_at = chrono::Local::now().to_rfc3339();
    }

    /// Save session to file
    fn save_to_file(&self, path: &PathBuf) -> Result<(), String> {
        let json = serde_json::to_string_pretty(self)
            .map_err(|e| format!("Failed to serialize session: {}", e))?;
        fs::write(path, json).map_err(|e| format!("Failed to write session file: {}", e))?;
        Ok(())
    }

    /// Load session from file
    fn load_from_file(path: &PathBuf) -> Result<Self, String> {
        let json =
            fs::read_to_string(path).map_err(|e| format!("Failed to read session file: {}", e))?;
        let session: QuerySession = serde_json::from_str(&json)
            .map_err(|e| format!("Failed to parse session file: {}", e))?;
        Ok(session)
    }

    /// Clear all queries from the session
    fn clear(&mut self) {
        self.queries.clear();
        self.modified_at = chrono::Local::now().to_rfc3339();
    }
}

/// Format SPARQL query for better readability with syntax highlighting
fn format_sparql_query(query: &str) -> String {
    let mut formatted = String::new();
    let mut indent_level: usize = 0;
    let indent = "  ";

    for line in query.lines() {
        let trimmed = line.trim();

        // Decrease indent before closing braces
        if trimmed.starts_with('}') {
            indent_level = indent_level.saturating_sub(1);
        }

        // Add indentation
        if !trimmed.is_empty() {
            formatted.push_str(&indent.repeat(indent_level));
            formatted.push_str(trimmed);
            formatted.push('\n');
        }

        // Increase indent after opening braces
        if trimmed.ends_with('{') {
            indent_level += 1;
        }
    }

    let formatted_text = formatted.trim_end().to_string();

    // Apply syntax highlighting
    let highlight_config = HighlightConfig::default();
    highlight_sparql(&formatted_text, &highlight_config)
}

/// Get query template by name
fn get_query_template(name: &str) -> Option<String> {
    match name.to_lowercase().as_str() {
        "select" => Some(
            "PREFIX ex: <http://example.org/>\n\
             SELECT ?subject ?predicate ?object\n\
             WHERE {\n\
               ?subject ?predicate ?object .\n\
             }\n\
             LIMIT 10"
                .to_string(),
        ),
        "construct" => Some(
            "PREFIX ex: <http://example.org/>\n\
             CONSTRUCT {\n\
               ?s ex:related ?o .\n\
             }\n\
             WHERE {\n\
               ?s ?p ?o .\n\
             }"
            .to_string(),
        ),
        "ask" => Some(
            "PREFIX ex: <http://example.org/>\n\
             ASK {\n\
               ?s ex:property ?o .\n\
             }"
            .to_string(),
        ),
        "describe" => Some(
            "PREFIX ex: <http://example.org/>\n\
             DESCRIBE ?resource\n\
             WHERE {\n\
               ?resource ex:property ?value .\n\
             }"
            .to_string(),
        ),
        "filter" => Some(
            "PREFIX ex: <http://example.org/>\n\
             SELECT ?item ?value\n\
             WHERE {\n\
               ?item ex:property ?value .\n\
               FILTER (?value > 100)\n\
             }"
            .to_string(),
        ),
        "optional" => Some(
            "PREFIX ex: <http://example.org/>\n\
             SELECT ?person ?name ?email\n\
             WHERE {\n\
               ?person ex:name ?name .\n\
               OPTIONAL { ?person ex:email ?email }\n\
             }"
            .to_string(),
        ),
        _ => None,
    }
}

/// Validate basic SPARQL syntax and return hints
fn validate_sparql_syntax(query: &str) -> Vec<String> {
    let mut hints = Vec::new();
    let query_upper = query.to_uppercase();

    // Check for common SPARQL keywords
    let has_select = query_upper.contains("SELECT");
    let has_construct = query_upper.contains("CONSTRUCT");
    let has_ask = query_upper.contains("ASK");
    let has_describe = query_upper.contains("DESCRIBE");
    let has_where = query_upper.contains("WHERE");

    if !has_select && !has_construct && !has_ask && !has_describe {
        hints.push("Query should start with SELECT, CONSTRUCT, ASK, or DESCRIBE".to_string());
    }

    if (has_select || has_construct || has_describe) && !has_where {
        hints.push("Query should include a WHERE clause".to_string());
    }

    // Check for unbalanced braces in WHERE clause
    let brace_count = query.matches('{').count() as i32 - query.matches('}').count() as i32;
    if brace_count != 0 {
        hints.push(format!(
            "Unbalanced braces (difference: {})",
            brace_count.abs()
        ));
    }

    // Check for common prefixes without PREFIX declarations
    let common_prefixes = [
        ("rdf:", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
        ("rdfs:", "http://www.w3.org/2000/01/rdf-schema#"),
        ("owl:", "http://www.w3.org/2002/07/owl#"),
        ("xsd:", "http://www.w3.org/2001/XMLSchema#"),
        ("foaf:", "http://xmlns.com/foaf/0.1/"),
        ("dc:", "http://purl.org/dc/elements/1.1/"),
        ("skos:", "http://www.w3.org/2004/02/skos/core#"),
    ];

    for (prefix, uri) in &common_prefixes {
        if query.contains(prefix)
            && !query_upper.contains(&format!(
                "PREFIX {}",
                prefix.to_uppercase().trim_end_matches(':')
            ))
        {
            hints.push(format!(
                "Consider adding: PREFIX {}: <{}>",
                prefix.trim_end_matches(':'),
                uri
            ));
        }
    }

    // Check for FILTER without parentheses
    if query_upper.contains("FILTER") && !query.contains("FILTER (") && !query.contains("FILTER(") {
        hints.push("FILTER should be followed by parentheses: FILTER (expression)".to_string());
    }

    // Check for missing dots between triples
    if has_where {
        let lines: Vec<&str> = query.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            let trimmed = line.trim();
            if !trimmed.is_empty()
                && !trimmed.starts_with('#')
                && !trimmed.ends_with('.')
                && !trimmed.ends_with('{')
                && !trimmed.ends_with('}')
                && !trimmed.ends_with(';')
                && !trimmed.starts_with("PREFIX")
                && !trimmed.starts_with("SELECT")
                && !trimmed.starts_with("WHERE")
                && !trimmed.starts_with("FILTER")
                && trimmed.contains("?")
                && i + 1 < lines.len()
            {
                hints.push(format!(
                    "Line {} might be missing a dot (.) at the end",
                    i + 1
                ));
                break; // Only show one hint about this
            }
        }
    }

    hints
}

/// Check if a SPARQL query is complete
/// A query is complete if:
/// - All braces are balanced
/// - All quotes are balanced
/// - It doesn't end with a continuation indicator (backslash)
fn is_query_complete(query: &str) -> bool {
    let trimmed = query.trim();

    // Empty queries are not complete
    if trimmed.is_empty() {
        return false;
    }

    // Check for explicit continuation (backslash at end)
    if trimmed.ends_with('\\') {
        return false;
    }

    // Count braces, brackets, and parentheses
    let mut brace_count = 0;
    let mut bracket_count = 0;
    let mut paren_count = 0;
    let mut in_single_quote = false;
    let mut in_double_quote = false;
    let mut in_triple_single_quote = false;
    let mut in_triple_double_quote = false;
    let mut escape_next = false;

    let chars: Vec<char> = query.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let ch = chars[i];

        if escape_next {
            escape_next = false;
            i += 1;
            continue;
        }

        // Check if we're in any quote mode
        let in_any_quote =
            in_single_quote || in_double_quote || in_triple_single_quote || in_triple_double_quote;

        match ch {
            '\\' if in_any_quote => {
                escape_next = true;
            }
            '\'' if !in_double_quote && !in_triple_double_quote => {
                // Check for triple single quotes
                if i + 2 < chars.len() && chars[i + 1] == '\'' && chars[i + 2] == '\'' {
                    if !in_single_quote {
                        in_triple_single_quote = !in_triple_single_quote;
                        i += 2;
                    }
                } else if !in_triple_single_quote {
                    in_single_quote = !in_single_quote;
                }
            }
            '"' if !in_single_quote && !in_triple_single_quote => {
                // Check for triple double quotes
                if i + 2 < chars.len() && chars[i + 1] == '"' && chars[i + 2] == '"' {
                    if !in_double_quote {
                        in_triple_double_quote = !in_triple_double_quote;
                        i += 2;
                    }
                } else if !in_triple_double_quote {
                    in_double_quote = !in_double_quote;
                }
            }
            '{' if !in_any_quote => {
                brace_count += 1;
            }
            '}' if !in_any_quote => {
                brace_count -= 1;
            }
            '[' if !in_any_quote => {
                bracket_count += 1;
            }
            ']' if !in_any_quote => {
                bracket_count -= 1;
            }
            '(' if !in_any_quote => {
                paren_count += 1;
            }
            ')' if !in_any_quote => {
                paren_count -= 1;
            }
            _ => {}
        }

        i += 1;
    }

    // Query is complete if all delimiters are balanced and not in a quote
    brace_count == 0
        && bracket_count == 0
        && paren_count == 0
        && !in_single_quote
        && !in_double_quote
        && !in_triple_single_quote
        && !in_triple_double_quote
}

/// Convert Term to RdfTerm for formatting
fn term_to_rdf_term(term: &Term) -> RdfTerm {
    match term {
        Term::NamedNode(node) => RdfTerm::Uri {
            value: node.as_str().to_string(),
        },
        Term::BlankNode(bnode) => RdfTerm::Bnode {
            value: bnode.as_str().to_string(),
        },
        Term::Literal(lit) => RdfTerm::Literal {
            value: lit.value().to_string(),
            lang: lit.language().map(|l| l.to_string()),
            datatype: Some(lit.datatype().as_str().to_string()),
        },
        Term::Variable(var) => RdfTerm::Literal {
            value: format!("?{}", var.name()),
            lang: None,
            datatype: None,
        },
        Term::QuotedTriple(triple) => RdfTerm::Literal {
            value: format!(
                "<<{} {} {}>>",
                triple.subject(),
                triple.predicate(),
                triple.object()
            ),
            lang: None,
            datatype: Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement".to_string()),
        },
    }
}

/// Convert Subject to RdfTerm for formatting
fn subject_to_rdf_term(subject: &Subject) -> RdfTerm {
    match subject {
        Subject::NamedNode(node) => RdfTerm::Uri {
            value: node.as_str().to_string(),
        },
        Subject::BlankNode(bnode) => RdfTerm::Bnode {
            value: bnode.as_str().to_string(),
        },
        Subject::Variable(var) => RdfTerm::Literal {
            value: format!("?{}", var.name()),
            lang: None,
            datatype: None,
        },
        Subject::QuotedTriple(triple) => RdfTerm::Literal {
            value: format!(
                "<<{} {} {}>>",
                triple.subject(),
                triple.predicate(),
                triple.object()
            ),
            lang: None,
            datatype: Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement".to_string()),
        },
    }
}

/// Convert Predicate to RdfTerm for formatting
fn predicate_to_rdf_term(predicate: &Predicate) -> RdfTerm {
    match predicate {
        Predicate::NamedNode(node) => RdfTerm::Uri {
            value: node.as_str().to_string(),
        },
        Predicate::Variable(var) => RdfTerm::Literal {
            value: format!("?{}", var.name()),
            lang: None,
            datatype: None,
        },
    }
}

/// Convert Object to RdfTerm for formatting
fn object_to_rdf_term(object: &oxirs_core::model::Object) -> RdfTerm {
    use oxirs_core::model::Object;

    match object {
        Object::NamedNode(node) => RdfTerm::Uri {
            value: node.as_str().to_string(),
        },
        Object::BlankNode(bnode) => RdfTerm::Bnode {
            value: bnode.as_str().to_string(),
        },
        Object::Literal(lit) => RdfTerm::Literal {
            value: lit.value().to_string(),
            lang: lit.language().map(|l| l.to_string()),
            datatype: Some(lit.datatype().as_str().to_string()),
        },
        Object::Variable(var) => RdfTerm::Literal {
            value: format!("?{}", var.name()),
            lang: None,
            datatype: None,
        },
        Object::QuotedTriple(triple) => RdfTerm::Literal {
            value: format!(
                "<<{} {} {}>>",
                triple.subject(),
                triple.predicate(),
                triple.object()
            ),
            lang: None,
            datatype: Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement".to_string()),
        },
    }
}

/// Format and display query results
fn format_and_display_results(
    results: &OxirsQueryResults,
    output_format: &str,
) -> Result<(), String> {
    use std::io;

    // Convert real OxirsQueryResults to formatter QueryResults
    let formatter_results = match results.results() {
        CoreQueryResults::Bindings(bindings) => {
            let variables = results.variables();

            FormatterQueryResults {
                variables: variables.to_vec(),
                bindings: bindings
                    .iter()
                    .map(|var_binding| {
                        // Get values in the order of variables
                        let values: Vec<Option<RdfTerm>> = variables
                            .iter()
                            .map(|var| var_binding.get(var).map(term_to_rdf_term))
                            .collect();

                        Binding { values }
                    })
                    .collect(),
            }
        }
        CoreQueryResults::Boolean(value) => {
            // For ASK queries, return a single binding with the boolean result
            FormatterQueryResults {
                variables: vec!["result".to_string()],
                bindings: vec![Binding {
                    values: vec![Some(RdfTerm::Literal {
                        value: value.to_string(),
                        lang: None,
                        datatype: Some("http://www.w3.org/2001/XMLSchema#boolean".to_string()),
                    })],
                }],
            }
        }
        CoreQueryResults::Graph(quads) => {
            // For CONSTRUCT/DESCRIBE queries, convert quads to bindings
            FormatterQueryResults {
                variables: vec![
                    "subject".to_string(),
                    "predicate".to_string(),
                    "object".to_string(),
                ],
                bindings: quads
                    .iter()
                    .map(|quad| Binding {
                        values: vec![
                            Some(subject_to_rdf_term(quad.subject())),
                            Some(predicate_to_rdf_term(quad.predicate())),
                            Some(object_to_rdf_term(quad.object())),
                        ],
                    })
                    .collect(),
            }
        }
    };

    // Use the comprehensive formatter
    if let Some(formatter) = create_formatter(output_format) {
        let mut stdout = io::stdout();
        formatter
            .format(&formatter_results, &mut stdout)
            .map_err(|e| format!("Failed to format results: {e}"))?;
    } else {
        return Err(format!("Unsupported output format: {output_format}"));
    }

    Ok(())
}

/// Execute interactive mode
pub fn execute(dataset: Option<String>, _config_path: Option<PathBuf>) -> CliResult<()> {
    let dataset_name = dataset.clone().unwrap_or_else(|| "default".to_string());

    // Load dataset
    let dataset_dir = PathBuf::from(&dataset_name);
    let dataset_path = if dataset_dir.join("oxirs.toml").exists() {
        // Dataset with configuration file - extract dataset name from directory name
        let name = dataset_dir
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&dataset_name);
        let (storage_path, _config) = crate::config::load_named_dataset(&dataset_dir, name)
            .map_err(|e| crate::cli::CliError::from(format!("Failed to load dataset: {e}")))?;
        storage_path
    } else {
        // Assume dataset is a directory path
        dataset_dir
    };

    // Open the RDF store
    let store = if dataset_path.is_dir() {
        RdfStore::open(&dataset_path)
            .map_err(|e| crate::cli::CliError::from(format!("Failed to open dataset: {e}")))?
    } else {
        return Err(crate::cli::CliError::from(format!(
            "Dataset not found: {dataset_name}"
        )));
    };

    let mut rl = Editor::<SparqlHelper, DefaultHistory>::new()
        .map_err(|e| crate::cli::CliError::from(format!("Failed to create editor: {}", e)))?;
    rl.set_helper(Some(SparqlHelper::new()));

    // Load history
    let history_dir = dirs::data_local_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("oxirs");
    let _ = std::fs::create_dir_all(&history_dir);
    let history_file = history_dir.join("history.txt");
    let _ = rl.load_history(&history_file);

    // Initialize session
    let sessions_dir = history_dir.join("sessions");
    let _ = std::fs::create_dir_all(&sessions_dir);
    let mut current_session = QuerySession::new("default".to_string(), dataset_name.clone());

    // Print welcome message
    println!("╔═══════════════════════════════════════════════════════════╗");
    println!("║              OxiRS Interactive SPARQL Shell             ║");
    println!("║                    Version 0.1.0                   ║");
    println!("╚═══════════════════════════════════════════════════════════╝");
    println!();
    println!("Connected to dataset: {}", dataset_name);
    println!(
        "Session: {} (created: {})",
        current_session.name, current_session.created_at
    );
    println!();
    println!("Commands:");
    println!("  .help             Show help");
    println!("  .quit, .exit      Exit");
    println!("  .stats            Show statistics");
    println!();
    println!("Session Commands:");
    println!("  .session          Show session info");
    println!("  .save <file>      Save session");
    println!("  .load <file>      Load session");
    println!("  .list             List saved sessions");
    println!("  .clear            Clear session");
    println!();
    println!("Query Commands:");
    println!("  .history          Show query history");
    println!("  .show <n>         Show query #n");
    println!("  .replay <n>       Replay query #n");
    println!("  .search <word>    Search queries (fuzzy matching)");
    println!("  .format <n>       Format query #n");
    println!();
    println!("File Operations:");
    println!("  .export <file>    Export queries to file");
    println!("  .import <file>    Import queries from file");
    println!("  .batch <file>     Execute queries from file");
    println!();
    println!("Templates:");
    println!("  .template [name]  Show query templates");
    println!();
    println!("Type your SPARQL query and press Enter");
    println!("Multi-line queries supported - query continues until all braces are balanced");
    println!("Queries are executed immediately and results displayed in table format");
    println!("─────────────────────────────────────────────────────────────");
    println!();

    // Main REPL loop with multi-line support
    let mut accumulated_query = String::new();
    let mut in_multiline = false;

    loop {
        let prompt = if in_multiline {
            "oxirs...> "
        } else {
            "oxirs> "
        };

        let readline = rl.readline(prompt);

        match readline {
            Ok(line) => {
                // Handle Ctrl+C during multi-line input
                if in_multiline && line.trim().is_empty() {
                    // Empty line in multi-line mode - check if user wants to cancel
                    // We'll just add it and continue
                }

                // Accumulate the line
                if in_multiline {
                    accumulated_query.push('\n');
                }
                accumulated_query.push_str(&line);

                // Check if this is a meta-command (only at start of input)
                if !in_multiline && line.trim().starts_with('.') {
                    let trimmed = line.trim();
                    let parts: Vec<&str> = trimmed.splitn(2, ' ').collect();
                    let command = parts[0];

                    match command {
                        ".help" | ".h" => {
                            print_help();
                        }
                        ".quit" | ".q" | ".exit" => {
                            println!("Goodbye!");
                            break;
                        }
                        ".stats" => {
                            println!(
                                "╔═══════════════════════════════════════════════════════════╗"
                            );
                            println!(
                                "║                   Session Statistics                     ║"
                            );
                            println!(
                                "╚═══════════════════════════════════════════════════════════╝"
                            );
                            println!("Dataset:         {}", dataset_name);
                            println!("Status:          Connected");
                            println!("Queries:         {}", current_session.queries.len());
                            println!("Session:         {}", current_session.name);
                            println!("Created:         {}", current_session.created_at);
                            println!("Last Modified:   {}", current_session.modified_at);

                            // Calculate query statistics
                            let total_lines: usize = current_session
                                .queries
                                .iter()
                                .map(|q| q.lines().count())
                                .sum();
                            let avg_lines = if current_session.queries.is_empty() {
                                0.0
                            } else {
                                total_lines as f64 / current_session.queries.len() as f64
                            };

                            let total_chars: usize =
                                current_session.queries.iter().map(|q| q.len()).sum();

                            println!("Total Lines:     {}", total_lines);
                            println!("Avg Lines/Query: {:.1}", avg_lines);
                            println!("Total Chars:     {}", total_chars);
                            println!();
                        }
                        ".session" => {
                            println!(
                                "╔═══════════════════════════════════════════════════════════╗"
                            );
                            println!(
                                "║                   Session Information                    ║"
                            );
                            println!(
                                "╚═══════════════════════════════════════════════════════════╝"
                            );
                            println!("Name:     {}", current_session.name);
                            println!("Dataset:  {}", current_session.dataset);
                            println!("Created:  {}", current_session.created_at);
                            println!("Modified: {}", current_session.modified_at);
                            println!("Queries:  {}", current_session.queries.len());
                            println!();
                        }
                        ".save" => {
                            if parts.len() < 2 {
                                eprintln!("Usage: .save <filename>");
                            } else {
                                let filename = parts[1].trim();
                                let session_path = sessions_dir.join(format!("{}.json", filename));
                                match current_session.save_to_file(&session_path) {
                                    Ok(_) => {
                                        println!("Session saved to: {}", session_path.display())
                                    }
                                    Err(e) => eprintln!("Error saving session: {}", e),
                                }
                            }
                        }
                        ".load" => {
                            if parts.len() < 2 {
                                eprintln!("Usage: .load <filename>");
                            } else {
                                let filename = parts[1].trim();
                                let session_path = sessions_dir.join(format!("{}.json", filename));
                                match QuerySession::load_from_file(&session_path) {
                                    Ok(session) => {
                                        current_session = session;
                                        println!("Session loaded: {}", current_session.name);
                                        println!("Queries: {}", current_session.queries.len());
                                    }
                                    Err(e) => eprintln!("Error loading session: {}", e),
                                }
                            }
                        }
                        ".clear" => {
                            current_session.clear();
                            println!(
                                "Session cleared (queries: {})",
                                current_session.queries.len()
                            );
                        }
                        ".history" => {
                            if current_session.queries.is_empty() {
                                println!("No queries in session history");
                            } else {
                                println!(
                                    "╔═══════════════════════════════════════════════════════════╗"
                                );
                                println!(
                                    "║                   Query History                          ║"
                                );
                                println!(
                                    "╚═══════════════════════════════════════════════════════════╝"
                                );
                                for (i, query) in current_session.queries.iter().enumerate() {
                                    println!("\n[Query #{}]", i + 1);
                                    // Apply syntax highlighting
                                    let highlight_config = HighlightConfig::default();
                                    let highlighted_query =
                                        highlight_sparql(query, &highlight_config);
                                    // Show first 2 lines or full query if short
                                    let lines: Vec<&str> = highlighted_query.lines().collect();
                                    if lines.len() <= 2 {
                                        println!("{}", highlighted_query);
                                    } else {
                                        println!("{}", lines[0]);
                                        println!("{}", lines[1]);
                                        println!("... ({} more lines)", lines.len() - 2);
                                    }
                                }
                                println!();
                            }
                        }
                        ".show" => {
                            if parts.len() < 2 {
                                eprintln!("Usage: .show <query_number>");
                            } else if let Ok(n) = parts[1].trim().parse::<usize>() {
                                if n == 0 || n > current_session.queries.len() {
                                    eprintln!(
                                        "Query #{} not found (valid: 1-{})",
                                        n,
                                        current_session.queries.len()
                                    );
                                } else {
                                    println!("\n─── Query #{} ───", n);
                                    println!("{}", current_session.queries[n - 1]);
                                    println!("─────────────────");
                                }
                            } else {
                                eprintln!("Invalid query number: {}", parts[1]);
                            }
                        }
                        ".replay" => {
                            if parts.len() < 2 {
                                eprintln!("Usage: .replay <query_number>");
                            } else if let Ok(n) = parts[1].trim().parse::<usize>() {
                                if n == 0 || n > current_session.queries.len() {
                                    eprintln!(
                                        "Query #{} not found (valid: 1-{})",
                                        n,
                                        current_session.queries.len()
                                    );
                                } else {
                                    let query = current_session.queries[n - 1].clone();
                                    println!("\n╔═══════════════════════════════════════════════════════════╗");
                                    println!(
                                        "║ Replaying Query #{:<37}                              ║",
                                        n
                                    );
                                    println!("╚═══════════════════════════════════════════════════════════╝");

                                    // Show query
                                    let lines: Vec<&str> = query.lines().collect();
                                    for (i, line) in lines.iter().enumerate().take(5) {
                                        println!(" {:3}{}", i + 1, line);
                                    }
                                    if lines.len() > 5 {
                                        println!(" ... │ ({} more lines)", lines.len() - 5);
                                    }
                                    println!();

                                    // Execute the query
                                    let start_time = Instant::now();
                                    match store.query(&query) {
                                        Ok(results) => {
                                            let elapsed = start_time.elapsed();
                                            println!(
                                                "✓  Query completed in {:.2}ms",
                                                elapsed.as_secs_f64() * 1000.0
                                            );
                                            println!("   Results: {} solutions", results.len());
                                            println!();

                                            if let Err(e) =
                                                format_and_display_results(&results, "table")
                                            {
                                                eprintln!("⚠  Error formatting results: {}", e);
                                            } else {
                                                println!();
                                            }
                                        }
                                        Err(e) => {
                                            let elapsed = start_time.elapsed();
                                            println!(
                                                "✗  Query failed in {:.2}ms",
                                                elapsed.as_secs_f64() * 1000.0
                                            );
                                            eprintln!("   Error: {}", e);
                                            println!();
                                        }
                                    }
                                }
                            } else {
                                eprintln!("Invalid query number: {}", parts[1]);
                            }
                        }
                        ".export" => {
                            if parts.len() < 2 {
                                eprintln!("Usage: .export <filename.sparql>");
                            } else {
                                let filename = parts[1].trim();
                                let export_path = if filename.contains('/') {
                                    PathBuf::from(filename)
                                } else {
                                    sessions_dir.join(filename)
                                };

                                let queries_text =
                                    current_session.queries.join("\n\n# ───────────\n\n");
                                match fs::write(&export_path, queries_text) {
                                    Ok(_) => {
                                        println!("✓ Queries exported to: {}", export_path.display())
                                    }
                                    Err(e) => eprintln!("✗ Error exporting queries: {}", e),
                                }
                            }
                        }
                        ".import" => {
                            if parts.len() < 2 {
                                eprintln!("Usage: .import <filename.sparql>");
                            } else {
                                let filename = parts[1].trim();
                                let import_path = if filename.contains('/') {
                                    PathBuf::from(filename)
                                } else {
                                    sessions_dir.join(filename)
                                };

                                match fs::read_to_string(&import_path) {
                                    Ok(content) => {
                                        // Split by separator or double newlines
                                        let queries: Vec<String> = if content
                                            .contains("# ───────────")
                                        {
                                            content
                                                .split("# ───────────")
                                                .map(|s| s.trim().to_string())
                                                .filter(|s| !s.is_empty())
                                                .collect()
                                        } else {
                                            // Split by PREFIX blocks or SELECT/ASK/CONSTRUCT/DESCRIBE
                                            content
                                                .split("\n\n")
                                                .map(|s| s.trim().to_string())
                                                .filter(|s| !s.is_empty() && !s.starts_with('#'))
                                                .collect()
                                        };

                                        let count = queries.len();
                                        for query in queries {
                                            current_session.add_query(query);
                                        }

                                        println!(
                                            "✓ Imported {} queries from: {}",
                                            count,
                                            import_path.display()
                                        );
                                        println!(
                                            "  Total queries in session: {}",
                                            current_session.queries.len()
                                        );
                                    }
                                    Err(e) => eprintln!("✗ Error importing file: {}", e),
                                }
                            }
                        }
                        ".batch" => {
                            if parts.len() < 2 {
                                eprintln!("Usage: .batch <filename.sparql>");
                            } else {
                                let filename = parts[1].trim();
                                let batch_path = if filename.contains('/') {
                                    PathBuf::from(filename)
                                } else {
                                    sessions_dir.join(filename)
                                };

                                match fs::read_to_string(&batch_path) {
                                    Ok(content) => {
                                        println!("╔═══════════════════════════════════════════════════════════╗");
                                        println!("║                   Batch Execution                        ║");
                                        println!("╚═══════════════════════════════════════════════════════════╝");
                                        println!("File: {}", batch_path.display());
                                        println!();

                                        let queries: Vec<String> = if content
                                            .contains("# ───────────")
                                        {
                                            content
                                                .split("# ───────────")
                                                .map(|s| s.trim().to_string())
                                                .filter(|s| !s.is_empty())
                                                .collect()
                                        } else {
                                            content
                                                .split("\n\n")
                                                .map(|s| s.trim().to_string())
                                                .filter(|s| !s.is_empty() && !s.starts_with('#'))
                                                .collect()
                                        };

                                        let total_start = Instant::now();
                                        let mut successful = 0;
                                        let mut failed = 0;

                                        for (i, query) in queries.iter().enumerate() {
                                            println!("─── Query {}/{} ───", i + 1, queries.len());

                                            // Show first line
                                            if let Some(first_line) = query.lines().next() {
                                                println!("{}", first_line);
                                                if query.lines().count() > 1 {
                                                    println!(
                                                        "... ({} more lines)",
                                                        query.lines().count() - 1
                                                    );
                                                }
                                            }
                                            println!();

                                            // Execute the query
                                            let start = Instant::now();
                                            match store.query(query) {
                                                Ok(results) => {
                                                    let elapsed = start.elapsed();
                                                    println!(
                                                        "✓ Query completed in {:.2}ms",
                                                        elapsed.as_secs_f64() * 1000.0
                                                    );
                                                    println!(
                                                        "  Results: {} solutions",
                                                        results.len()
                                                    );
                                                    successful += 1;
                                                }
                                                Err(e) => {
                                                    let elapsed = start.elapsed();
                                                    println!(
                                                        "✗ Query failed in {:.2}ms",
                                                        elapsed.as_secs_f64() * 1000.0
                                                    );
                                                    eprintln!("  Error: {}", e);
                                                    failed += 1;
                                                }
                                            }
                                            println!();

                                            current_session.add_query(query.clone());
                                        }

                                        let total_elapsed = total_start.elapsed();
                                        println!("═══════════════════════════════════════════════════════════");
                                        println!(
                                            "Batch complete: {} queries in {:.2}ms",
                                            queries.len(),
                                            total_elapsed.as_secs_f64() * 1000.0
                                        );
                                        println!("  Successful: {}", successful);
                                        println!("  Failed:     {}", failed);
                                        println!(
                                            "  Average:    {:.2}ms per query",
                                            total_elapsed.as_secs_f64() * 1000.0
                                                / queries.len() as f64
                                        );
                                        println!();
                                    }
                                    Err(e) => eprintln!("✗ Error reading batch file: {}", e),
                                }
                            }
                        }
                        ".search" => {
                            if parts.len() < 2 {
                                eprintln!("Usage: .search <keyword>");
                                eprintln!("  Supports fuzzy matching - finds similar queries even with typos");
                                eprintln!("  Results are ranked by relevance");
                            } else {
                                let keyword = parts[1].trim();

                                // Collect matches with relevance scores
                                let mut scored_matches: Vec<(usize, &String, f64)> =
                                    current_session
                                        .queries
                                        .iter()
                                        .enumerate()
                                        .filter_map(|(idx, q)| {
                                            let query_lower = q.to_lowercase();
                                            let keyword_lower = keyword.to_lowercase();

                                            // Exact substring match gets highest score
                                            if query_lower.contains(&keyword_lower) {
                                                return Some((idx, q, 1.0));
                                            }

                                            // Fuzzy match using Jaro-Winkler distance
                                            let max_similarity = q
                                                .split_whitespace()
                                                .map(|word| {
                                                    strsim::jaro_winkler(
                                                        &word.to_lowercase(),
                                                        &keyword_lower,
                                                    )
                                                })
                                                .max_by(|a, b| {
                                                    a.partial_cmp(b)
                                                        .unwrap_or(std::cmp::Ordering::Equal)
                                                })
                                                .unwrap_or(0.0);

                                            // Only include matches above 0.7 similarity threshold
                                            if max_similarity >= 0.7 {
                                                Some((idx, q, max_similarity))
                                            } else {
                                                None
                                            }
                                        })
                                        .collect();

                                // Sort by score (highest first)
                                scored_matches.sort_by(|a, b| {
                                    b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal)
                                });

                                if scored_matches.is_empty() {
                                    println!("No queries found matching: {}", keyword);
                                    println!("Try a different search term or use fewer characters");
                                } else {
                                    println!("╔═══════════════════════════════════════════════════════════╗");
                                    println!(
                                        "║         Fuzzy Search Results for: {:<27}                ║",
                                        keyword
                                    );
                                    println!("╚═══════════════════════════════════════════════════════════╝");
                                    println!(
                                        "Found {} matches (sorted by relevance):\n",
                                        scored_matches.len()
                                    );

                                    for (idx, query, score) in scored_matches {
                                        // Show relevance indicator
                                        let relevance = if score >= 0.95 {
                                            "Excellent match"
                                        } else if score >= 0.85 {
                                            "Good match"
                                        } else {
                                            "Possible match"
                                        };

                                        println!(
                                            "[Query #{}] - {} ({:.0}% relevant)",
                                            idx + 1,
                                            relevance,
                                            score * 100.0
                                        );

                                        // Apply syntax highlighting
                                        let highlight_config = HighlightConfig::default();
                                        let highlighted_query =
                                            highlight_sparql(query, &highlight_config);
                                        let lines: Vec<&str> = highlighted_query.lines().collect();
                                        if lines.len() <= 2 {
                                            println!("{}", highlighted_query);
                                        } else {
                                            println!("{}", lines[0]);
                                            println!("... ({} more lines)", lines.len() - 1);
                                        }
                                        println!();
                                    }
                                }
                            }
                        }
                        ".format" => {
                            if parts.len() < 2 {
                                eprintln!("Usage: .format <query_number>");
                            } else if let Ok(n) = parts[1].trim().parse::<usize>() {
                                if n == 0 || n > current_session.queries.len() {
                                    eprintln!(
                                        "Query #{} not found (valid: 1-{})",
                                        n,
                                        current_session.queries.len()
                                    );
                                } else {
                                    let query = &current_session.queries[n - 1];
                                    println!("\n─── Formatted Query #{} ───", n);
                                    println!("{}", format_sparql_query(query));
                                    println!("──────────────────────────");
                                }
                            } else {
                                eprintln!("Invalid query number: {}", parts[1]);
                            }
                        }
                        ".template" => {
                            if parts.len() < 2 {
                                println!("Available templates:");
                                println!("  select    - Basic SELECT query");
                                println!("  construct - CONSTRUCT query");
                                println!("  ask       - ASK query");
                                println!("  describe  - DESCRIBE query");
                                println!("  filter    - SELECT with FILTER");
                                println!("  optional  - SELECT with OPTIONAL");
                                println!("\nUsage: .template <name>");
                            } else {
                                let template_name = parts[1].trim();
                                if let Some(template) = get_query_template(template_name) {
                                    println!("\n─── Template: {} ───", template_name);
                                    // Apply syntax highlighting to template
                                    let highlight_config = HighlightConfig::default();
                                    let highlighted_template =
                                        highlight_sparql(&template, &highlight_config);
                                    println!("{}", highlighted_template);
                                    println!("────────────────────────");
                                    println!("\nType or paste to use this template");
                                } else {
                                    eprintln!("Unknown template: {}", template_name);
                                    eprintln!("Use .template to see available templates");
                                }
                            }
                        }
                        ".list" => {
                            println!(
                                "╔═══════════════════════════════════════════════════════════╗"
                            );
                            println!(
                                "║                   Available Sessions                     ║"
                            );
                            println!(
                                "╚═══════════════════════════════════════════════════════════╝"
                            );
                            match fs::read_dir(&sessions_dir) {
                                Ok(entries) => {
                                    let mut found_any = false;
                                    for entry in entries.flatten() {
                                        if let Some(name) = entry.file_name().to_str() {
                                            if name.ends_with(".json") {
                                                found_any = true;
                                                let session_name = name.trim_end_matches(".json");
                                                println!("  {}", session_name);
                                            }
                                        }
                                    }
                                    if !found_any {
                                        println!("  No saved sessions found");
                                    }
                                }
                                Err(e) => eprintln!("Error reading sessions directory: {}", e),
                            }
                            println!();
                        }
                        _ => {
                            eprintln!("Unknown command: {}", trimmed);
                            println!("Type .help for available commands");
                        }
                    }
                    accumulated_query.clear();
                    continue;
                }

                // Check if the query is complete
                if is_query_complete(&accumulated_query) {
                    let query = accumulated_query.trim().to_string();

                    // Skip empty queries
                    if !query.is_empty() {
                        let start_time = Instant::now();

                        // Validate syntax and show hints
                        let hints = validate_sparql_syntax(&query);

                        // Add complete query to history
                        let _ = rl.add_history_entry(&query);

                        // Add query to session
                        current_session.add_query(query.clone());

                        // Display query header
                        println!("\n╔═══════════════════════════════════════════════════════════╗");
                        println!(
                            "║ Query #{:<49}                                       ║",
                            current_session.queries.len()
                        );
                        println!("╚═══════════════════════════════════════════════════════════╝");

                        // Show query with line numbers (first 5 lines)
                        let lines: Vec<&str> = query.lines().collect();
                        for (i, line) in lines.iter().enumerate().take(5) {
                            println!(" {:3}{}", i + 1, line);
                        }
                        if lines.len() > 5 {
                            println!(" ... │ ({} more lines)", lines.len() - 5);
                        }
                        println!();

                        // Show syntax hints if any
                        if !hints.is_empty() {
                            println!("⚠  Syntax Hints:");
                            for hint in &hints {
                                println!("{}", hint);
                            }
                            println!();
                        }

                        // Execute the query
                        match store.query(&query) {
                            Ok(results) => {
                                let elapsed = start_time.elapsed();

                                // Display result count
                                println!(
                                    "✓  Query completed in {:.2}ms",
                                    elapsed.as_secs_f64() * 1000.0
                                );
                                println!("   Results: {} solutions", results.len());
                                println!();

                                // Format and display results
                                if let Err(e) = format_and_display_results(&results, "table") {
                                    eprintln!("⚠  Error formatting results: {}", e);
                                } else {
                                    println!();
                                }
                            }
                            Err(e) => {
                                let elapsed = start_time.elapsed();
                                println!(
                                    "✗  Query failed in {:.2}ms",
                                    elapsed.as_secs_f64() * 1000.0
                                );
                                eprintln!("   Error: {}", e);
                                println!();
                            }
                        }
                    }

                    // Reset for next query
                    accumulated_query.clear();
                    in_multiline = false;
                } else {
                    // Query is incomplete, continue in multi-line mode
                    in_multiline = true;
                }
            }
            Err(ReadlineError::Interrupted) => {
                if in_multiline {
                    println!("^C (multi-line input cancelled)");
                    accumulated_query.clear();
                    in_multiline = false;
                } else {
                    println!("^C");
                }
                continue;
            }
            Err(ReadlineError::Eof) => {
                println!("Bye!");
                break;
            }
            Err(err) => {
                eprintln!("Error: {:?}", err);
                break;
            }
        }
    }

    // Save history
    let _ = rl.save_history(&history_file);

    // Auto-save session on exit if it has queries
    if !current_session.queries.is_empty() {
        let autosave_path = sessions_dir.join("_autosave.json");
        if let Ok(()) = current_session.save_to_file(&autosave_path) {
            println!("\n✓ Session auto-saved to: {}", autosave_path.display());
        }
    }

    Ok(())
}

fn print_help() {
    println!("╔═══════════════════════════════════════════════════════════╗");
    println!("║                 OxiRS Interactive Help                   ║");
    println!("╚═══════════════════════════════════════════════════════════╝");
    println!();
    println!("Meta Commands:");
    println!("  .help             Show this help message");
    println!("  .quit, .exit      Exit the shell");
    println!("  .stats            Show dataset and session statistics");
    println!();
    println!("Session Management:");
    println!("  .session          Show current session information");
    println!("  .save <filename>  Save session to file");
    println!("  .load <filename>  Load session from file");
    println!("  .list             List all saved sessions");
    println!("  .clear            Clear current session queries");
    println!();
    println!("Query Management:");
    println!("  .history          Show all queries in session");
    println!("  .show <n>         Display query number n");
    println!("  .replay <n>       Re-execute query number n");
    println!("  .search <keyword> Search queries with fuzzy matching and ranking");
    println!("  .format <n>       Format and pretty-print query number n");
    println!();
    println!("File Operations:");
    println!("  .export <file>    Export all queries to SPARQL file");
    println!("  .import <file>    Import queries from SPARQL file");
    println!("  .batch <file>     Execute all queries from file with timing");
    println!();
    println!("Templates:");
    println!("  .template         List available query templates");
    println!("  .template <name>  Show specific template (select, construct, etc.)");
    println!();
    println!("  Sessions are stored in: ~/.local/share/oxirs/sessions/");
    println!("  Each session contains query history and metadata.");
    println!();
    println!("Query Examples:");
    println!("  SELECT * WHERE {{ ?s ?p ?o }} LIMIT 10");
    println!("  ASK {{ ?s a <http://example.org/Person> }}");
    println!();
    println!("Multi-line Queries:");
    println!("  Queries automatically continue over multiple lines until");
    println!("  all braces, brackets, and quotes are balanced.");
    println!("  The prompt changes to 'oxirs...>' for continuation lines.");
    println!();
    println!("  Example:");
    println!("    oxirs> SELECT ?name ?email WHERE {{");
    println!("    oxirs...>   ?person foaf:name ?name .");
    println!("    oxirs...>   ?person foaf:mbox ?email");
    println!("    oxirs...> }} LIMIT 10");
    println!();
    println!("Keyboard Shortcuts:");
    println!("  Ctrl+C            Cancel multi-line input or interrupt");
    println!("  Ctrl+D            Exit the shell");
    println!("  Up/Down           Navigate history");
    println!("  Backslash (\\)     Force continuation to next line");
    println!();
}

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

    #[test]
    fn test_query_complete_simple() {
        assert!(is_query_complete("SELECT * WHERE { ?s ?p ?o }"));
        assert!(is_query_complete(
            "ASK { ?s a <http://example.org/Person> }"
        ));
        assert!(is_query_complete(
            "PREFIX ex: <http://example.org/> SELECT * WHERE { ?s ?p ?o }"
        ));
    }

    #[test]
    fn test_query_incomplete_braces() {
        assert!(!is_query_complete("SELECT * WHERE {"));
        assert!(!is_query_complete("SELECT * WHERE { ?s ?p ?o"));
        assert!(!is_query_complete("SELECT * WHERE { ?s { ?p ?o }"));
    }

    #[test]
    fn test_query_complete_nested_braces() {
        assert!(is_query_complete(
            "SELECT * WHERE { { ?s ?p ?o } UNION { ?a ?b ?c } }"
        ));
        assert!(is_query_complete(
            "SELECT * WHERE { GRAPH <g> { ?s ?p ?o } }"
        ));
    }

    #[test]
    fn test_query_incomplete_quotes() {
        assert!(!is_query_complete("SELECT * WHERE { ?s ?p \"unclosed"));
        assert!(!is_query_complete("SELECT * WHERE { ?s ?p 'unclosed"));
    }

    #[test]
    fn test_query_complete_quotes() {
        assert!(is_query_complete("SELECT * WHERE { ?s ?p \"value\" }"));
        assert!(is_query_complete("SELECT * WHERE { ?s ?p 'value' }"));
        assert!(is_query_complete(
            r#"SELECT * WHERE { ?s ?p "value with \"escaped\" quotes" }"#
        ));
    }

    #[test]
    fn test_query_complete_triple_quotes() {
        assert!(is_query_complete(
            r#"SELECT * WHERE { ?s ?p """triple quoted value""" }"#
        ));
        assert!(is_query_complete(
            r#"SELECT * WHERE { ?s ?p '''triple quoted value''' }"#
        ));
    }

    #[test]
    fn test_query_incomplete_triple_quotes() {
        assert!(!is_query_complete(r#"SELECT * WHERE { ?s ?p """unclosed"#));
        assert!(!is_query_complete(r#"SELECT * WHERE { ?s ?p '''unclosed"#));
    }

    #[test]
    fn test_query_complete_brackets() {
        assert!(is_query_complete("SELECT * WHERE { ?s [ ?p ?o ] }"));
        assert!(is_query_complete("SELECT * WHERE { [ ?p ?o ] ?p2 ?o2 }"));
    }

    #[test]
    fn test_query_incomplete_brackets() {
        assert!(!is_query_complete("SELECT * WHERE { ?s [ ?p ?o }"));
        assert!(!is_query_complete("SELECT * WHERE { [ ?p ?o ?p2 ?o2 }"));
    }

    #[test]
    fn test_query_complete_parentheses() {
        assert!(is_query_complete("SELECT * WHERE { FILTER (1 + 2) }"));
        assert!(is_query_complete(
            "SELECT * WHERE { BIND ((1 + 2) AS ?sum) }"
        ));
    }

    #[test]
    fn test_query_incomplete_parentheses() {
        assert!(!is_query_complete("SELECT * WHERE { FILTER (1 + 2 }"));
        assert!(!is_query_complete(
            "SELECT * WHERE { BIND ((1 + 2 AS ?sum) }"
        ));
    }

    #[test]
    fn test_query_continuation_backslash() {
        assert!(!is_query_complete("SELECT * WHERE { ?s ?p ?o } \\"));
        assert!(!is_query_complete("PREFIX ex: <http://example.org/> \\"));
    }

    #[test]
    fn test_query_empty() {
        assert!(!is_query_complete(""));
        assert!(!is_query_complete("   "));
        assert!(!is_query_complete("\n\n"));
    }

    #[test]
    fn test_query_complex_multiline() {
        let query = r#"SELECT ?name ?email WHERE {
            ?person foaf:name ?name .
            ?person foaf:mbox ?email
        }"#;
        assert!(is_query_complete(query));
    }

    #[test]
    fn test_query_with_comments() {
        let query = "SELECT * WHERE { # This is a comment\n ?s ?p ?o }";
        assert!(is_query_complete(query));
    }

    #[test]
    fn test_query_braces_in_strings() {
        assert!(is_query_complete(
            r#"SELECT * WHERE { ?s ?p "value with { braces }" }"#
        ));
        assert!(is_query_complete(
            r#"SELECT * WHERE { ?s ?p "value with ( parens )" }"#
        ));
        assert!(is_query_complete(
            r#"SELECT * WHERE { ?s ?p "value with [ brackets ]" }"#
        ));
    }

    #[test]
    fn test_syntax_validation_valid_query() {
        let query = "SELECT * WHERE { ?s ?p ?o }";
        let hints = validate_sparql_syntax(query);
        assert!(hints.is_empty());
    }

    #[test]
    fn test_syntax_validation_missing_where() {
        let query = "SELECT * { ?s ?p ?o }";
        let hints = validate_sparql_syntax(query);
        assert!(!hints.is_empty());
        assert!(hints.iter().any(|h| h.contains("WHERE")));
    }

    #[test]
    fn test_syntax_validation_missing_prefix() {
        let query = "SELECT * WHERE { ?s rdf:type ?o }";
        let hints = validate_sparql_syntax(query);
        assert!(hints.iter().any(|h| h.contains("PREFIX rdf:")));
    }

    #[test]
    fn test_syntax_validation_with_prefix() {
        let query = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nSELECT * WHERE { ?s rdf:type ?o }";
        let hints = validate_sparql_syntax(query);
        assert!(hints.iter().all(|h| !h.contains("PREFIX rdf:")));
    }

    #[test]
    fn test_syntax_validation_multiple_prefixes() {
        let query = "SELECT * WHERE { ?s rdf:type ?o . ?s foaf:name ?name }";
        let hints = validate_sparql_syntax(query);
        assert!(hints.len() >= 2); // Should suggest both rdf and foaf prefixes
    }

    #[test]
    fn test_syntax_validation_ask_query() {
        let query = "ASK { ?s ?p ?o }";
        let hints = validate_sparql_syntax(query);
        assert!(hints.is_empty());
    }

    #[test]
    fn test_syntax_validation_filter_syntax() {
        let query = "SELECT * WHERE { ?s ?p ?o FILTER ?o > 10 }";
        let hints = validate_sparql_syntax(query);
        assert!(hints.iter().any(|h| h.contains("FILTER")));
    }
}