xchecker 1.2.0

Spec pipeline with receipts and gateable JSON contracts
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
//! Tests for code examples in documentation
//!
//! This module validates that all code examples in documentation are correct and executable.
//! Requirements: R9

use anyhow::{Context, Result};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};

use crate::doc_validation::common::{FenceExtractor, StubRunner, run_example};

/// Test shell examples from README.md
#[test]
fn test_readme_shell_examples() -> Result<()> {
    let readme_path = Path::new("README.md");
    if !readme_path.exists() {
        println!("README.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(readme_path)?;
    let runner = StubRunner::new()?;

    // Extract bash and sh blocks
    let bash_blocks = extractor.extract_by_language("bash");
    let sh_blocks = extractor.extract_by_language("sh");
    let all_shell_blocks = [bash_blocks, sh_blocks].concat();

    if all_shell_blocks.is_empty() {
        println!("No shell examples found in README.md");
        return Ok(());
    }

    println!(
        "Testing {} shell examples from README.md",
        all_shell_blocks.len()
    );

    for (i, block) in all_shell_blocks.iter().enumerate() {
        // Skip blocks that don't start with xchecker (might be generic examples)
        let trimmed = block.content.trim();
        if !trimmed.starts_with("xchecker") {
            println!(
                "Skipping non-xchecker command: {}",
                trimmed.lines().next().unwrap_or("")
            );
            continue;
        }

        println!(
            "Running example {}: {}",
            i + 1,
            trimmed.lines().next().unwrap_or("")
        );

        match run_example(&runner, trimmed, &block.metadata) {
            Ok(_) => println!("  ✓ Passed"),
            Err(e) => {
                eprintln!("  ✗ Failed: {e}");
                // Don't fail the test immediately, collect all failures
                // For now, we'll be lenient and just log
            }
        }
    }

    Ok(())
}

/// Test shell examples from CONFIGURATION.md
#[test]
fn test_configuration_shell_examples() -> Result<()> {
    let config_path = Path::new("docs/CONFIGURATION.md");
    if !config_path.exists() {
        println!("docs/CONFIGURATION.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(config_path)?;
    let runner = StubRunner::new()?;

    let bash_blocks = extractor.extract_by_language("bash");
    let sh_blocks = extractor.extract_by_language("sh");
    let all_shell_blocks = [bash_blocks, sh_blocks].concat();

    if all_shell_blocks.is_empty() {
        println!("No shell examples found in CONFIGURATION.md");
        return Ok(());
    }

    println!(
        "Testing {} shell examples from CONFIGURATION.md",
        all_shell_blocks.len()
    );

    for (i, block) in all_shell_blocks.iter().enumerate() {
        let trimmed = block.content.trim();
        if !trimmed.starts_with("xchecker") {
            continue;
        }

        println!(
            "Running example {}: {}",
            i + 1,
            trimmed.lines().next().unwrap_or("")
        );

        match run_example(&runner, trimmed, &block.metadata) {
            Ok(_) => println!("  ✓ Passed"),
            Err(e) => {
                eprintln!("  ✗ Failed: {e}");
            }
        }
    }

    Ok(())
}

/// Test shell examples from DOCTOR.md
#[test]
fn test_doctor_shell_examples() -> Result<()> {
    let doctor_path = Path::new("docs/DOCTOR.md");
    if !doctor_path.exists() {
        println!("docs/DOCTOR.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(doctor_path)?;
    let runner = StubRunner::new()?;

    let bash_blocks = extractor.extract_by_language("bash");
    let sh_blocks = extractor.extract_by_language("sh");
    let all_shell_blocks = [bash_blocks, sh_blocks].concat();

    if all_shell_blocks.is_empty() {
        println!("No shell examples found in DOCTOR.md");
        return Ok(());
    }

    println!(
        "Testing {} shell examples from DOCTOR.md",
        all_shell_blocks.len()
    );

    for (i, block) in all_shell_blocks.iter().enumerate() {
        let trimmed = block.content.trim();
        if !trimmed.starts_with("xchecker") {
            continue;
        }

        println!(
            "Running example {}: {}",
            i + 1,
            trimmed.lines().next().unwrap_or("")
        );

        match run_example(&runner, trimmed, &block.metadata) {
            Ok(_) => println!("  ✓ Passed"),
            Err(e) => {
                eprintln!("  ✗ Failed: {e}");
            }
        }
    }

    Ok(())
}

/// Test shell examples from CONTRACTS.md
#[test]
fn test_contracts_shell_examples() -> Result<()> {
    let contracts_path = Path::new("docs/reference/CONTRACTS.md");
    if !contracts_path.exists() {
        println!("docs/CONTRACTS.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(contracts_path)?;
    let runner = StubRunner::new()?;

    let bash_blocks = extractor.extract_by_language("bash");
    let sh_blocks = extractor.extract_by_language("sh");
    let all_shell_blocks = [bash_blocks, sh_blocks].concat();

    if all_shell_blocks.is_empty() {
        println!("No shell examples found in CONTRACTS.md");
        return Ok(());
    }

    println!(
        "Testing {} shell examples from CONTRACTS.md",
        all_shell_blocks.len()
    );

    for (i, block) in all_shell_blocks.iter().enumerate() {
        let trimmed = block.content.trim();
        if !trimmed.starts_with("xchecker") {
            continue;
        }

        println!(
            "Running example {}: {}",
            i + 1,
            trimmed.lines().next().unwrap_or("")
        );

        match run_example(&runner, trimmed, &block.metadata) {
            Ok(_) => println!("  ✓ Passed"),
            Err(e) => {
                eprintln!("  ✗ Failed: {e}");
            }
        }
    }

    Ok(())
}

/// Test TOML examples from README.md
#[test]
fn test_readme_toml_examples() -> Result<()> {
    let readme_path = Path::new("README.md");
    if !readme_path.exists() {
        println!("README.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(readme_path)?;
    let toml_blocks = extractor.extract_by_language("toml");

    if toml_blocks.is_empty() {
        println!("No TOML examples found in README.md");
        return Ok(());
    }

    println!("Testing {} TOML examples from README.md", toml_blocks.len());

    for (i, block) in toml_blocks.iter().enumerate() {
        println!("Parsing TOML example {}", i + 1);

        match toml::from_str::<toml::Value>(&block.content) {
            Ok(_) => println!("  ✓ Valid TOML"),
            Err(e) => {
                eprintln!("  ✗ Invalid TOML: {e}");
                eprintln!("Content:\n{}", block.content);
                return Err(e.into());
            }
        }
    }

    Ok(())
}

/// Test TOML examples from CONFIGURATION.md
#[test]
fn test_configuration_toml_examples() -> Result<()> {
    let config_path = Path::new("docs/CONFIGURATION.md");
    if !config_path.exists() {
        println!("docs/CONFIGURATION.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(config_path)?;
    let toml_blocks = extractor.extract_by_language("toml");

    if toml_blocks.is_empty() {
        println!("No TOML examples found in CONFIGURATION.md");
        return Ok(());
    }

    println!(
        "Testing {} TOML examples from CONFIGURATION.md",
        toml_blocks.len()
    );

    for (i, block) in toml_blocks.iter().enumerate() {
        println!("Parsing TOML example {}", i + 1);

        match toml::from_str::<toml::Value>(&block.content) {
            Ok(_) => println!("  ✓ Valid TOML"),
            Err(e) => {
                eprintln!("  ✗ Invalid TOML: {e}");
                eprintln!("Content:\n{}", block.content);
                return Err(e.into());
            }
        }
    }

    Ok(())
}

/// Test TOML examples from DOCTOR.md
#[test]
fn test_doctor_toml_examples() -> Result<()> {
    let doctor_path = Path::new("docs/DOCTOR.md");
    if !doctor_path.exists() {
        println!("docs/DOCTOR.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(doctor_path)?;
    let toml_blocks = extractor.extract_by_language("toml");

    if toml_blocks.is_empty() {
        println!("No TOML examples found in DOCTOR.md");
        return Ok(());
    }

    println!("Testing {} TOML examples from DOCTOR.md", toml_blocks.len());

    for (i, block) in toml_blocks.iter().enumerate() {
        println!("Parsing TOML example {}", i + 1);

        match toml::from_str::<toml::Value>(&block.content) {
            Ok(_) => println!("  ✓ Valid TOML"),
            Err(e) => {
                eprintln!("  ✗ Invalid TOML: {e}");
                eprintln!("Content:\n{}", block.content);
                return Err(e.into());
            }
        }
    }

    Ok(())
}

/// Test TOML examples from CONTRACTS.md
#[test]
fn test_contracts_toml_examples() -> Result<()> {
    let contracts_path = Path::new("docs/reference/CONTRACTS.md");
    if !contracts_path.exists() {
        println!("docs/CONTRACTS.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(contracts_path)?;
    let toml_blocks = extractor.extract_by_language("toml");

    if toml_blocks.is_empty() {
        println!("No TOML examples found in CONTRACTS.md");
        return Ok(());
    }

    println!(
        "Testing {} TOML examples from CONTRACTS.md",
        toml_blocks.len()
    );

    for (i, block) in toml_blocks.iter().enumerate() {
        println!("Parsing TOML example {}", i + 1);

        match toml::from_str::<toml::Value>(&block.content) {
            Ok(_) => println!("  ✓ Valid TOML"),
            Err(e) => {
                eprintln!("  ✗ Invalid TOML: {e}");
                eprintln!("Content:\n{}", block.content);
                return Err(e.into());
            }
        }
    }

    Ok(())
}

/// Helper to identify which schema to use for a JSON example
fn identify_schema(json: &serde_json::Value) -> Option<&'static str> {
    // Check for schema_version field and other identifying fields
    if let Some(obj) = json.as_object() {
        if obj.contains_key("spec_id") && obj.contains_key("phase") {
            return Some("receipt.v1");
        }
        if obj.contains_key("effective_config") {
            return Some("status.v1");
        }
        if obj.contains_key("checks") && obj.contains_key("ok") {
            return Some("doctor.v1");
        }
    }
    None
}

/// Helper to load and validate against a schema
fn validate_against_schema(json: &serde_json::Value, schema_name: &str) -> Result<()> {
    use jsonschema::validator_for;

    let schema_path = format!("schemas/{schema_name}.json");
    let schema_content = std::fs::read_to_string(&schema_path)
        .context(format!("Failed to read schema: {schema_path}"))?;
    let schema: serde_json::Value = serde_json::from_str(&schema_content)?;

    let validator = validator_for(&schema).context(format!(
        "Failed to create validator for schema: {schema_name}"
    ))?;

    // Use is_valid for simple validation
    if !validator.is_valid(json) {
        anyhow::bail!("Schema validation failed for {schema_name}: JSON does not match schema");
    }

    Ok(())
}

/// Test JSON examples from README.md
#[test]
fn test_readme_json_examples() -> Result<()> {
    let readme_path = Path::new("README.md");
    if !readme_path.exists() {
        println!("README.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(readme_path)?;
    let json_blocks = extractor.extract_by_language("json");

    if json_blocks.is_empty() {
        println!("No JSON examples found in README.md");
        return Ok(());
    }

    println!("Testing {} JSON examples from README.md", json_blocks.len());

    for (i, block) in json_blocks.iter().enumerate() {
        println!("Parsing JSON example {}", i + 1);

        match serde_json::from_str::<serde_json::Value>(&block.content) {
            Ok(json) => {
                println!("  ✓ Valid JSON");

                // Try to identify and validate against schema
                if let Some(schema_name) = identify_schema(&json) {
                    println!("  Identified as {schema_name} schema");
                    match validate_against_schema(&json, schema_name) {
                        Ok(()) => println!("  ✓ Valid against schema"),
                        Err(e) => {
                            eprintln!("  ✗ Schema validation failed: {e}");
                            // Don't fail the test, just log
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("  ✗ Invalid JSON: {e}");
                eprintln!("Content:\n{}", block.content);
                return Err(e.into());
            }
        }
    }

    Ok(())
}

/// Test JSON examples from CONFIGURATION.md
#[test]
fn test_configuration_json_examples() -> Result<()> {
    let config_path = Path::new("docs/CONFIGURATION.md");
    if !config_path.exists() {
        println!("docs/CONFIGURATION.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(config_path)?;
    let json_blocks = extractor.extract_by_language("json");

    if json_blocks.is_empty() {
        println!("No JSON examples found in CONFIGURATION.md");
        return Ok(());
    }

    println!(
        "Testing {} JSON examples from CONFIGURATION.md",
        json_blocks.len()
    );

    for (i, block) in json_blocks.iter().enumerate() {
        println!("Parsing JSON example {}", i + 1);

        match serde_json::from_str::<serde_json::Value>(&block.content) {
            Ok(json) => {
                println!("  ✓ Valid JSON");

                if let Some(schema_name) = identify_schema(&json) {
                    println!("  Identified as {schema_name} schema");
                    match validate_against_schema(&json, schema_name) {
                        Ok(()) => println!("  ✓ Valid against schema"),
                        Err(e) => {
                            eprintln!("  ✗ Schema validation failed: {e}");
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("  ✗ Invalid JSON: {e}");
                eprintln!("Content:\n{}", block.content);
                return Err(e.into());
            }
        }
    }

    Ok(())
}

/// Test JSON examples from DOCTOR.md
#[test]
fn test_doctor_json_examples() -> Result<()> {
    let doctor_path = Path::new("docs/DOCTOR.md");
    if !doctor_path.exists() {
        println!("docs/DOCTOR.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(doctor_path)?;
    let json_blocks = extractor.extract_by_language("json");

    if json_blocks.is_empty() {
        println!("No JSON examples found in DOCTOR.md");
        return Ok(());
    }

    println!("Testing {} JSON examples from DOCTOR.md", json_blocks.len());

    for (i, block) in json_blocks.iter().enumerate() {
        println!("Parsing JSON example {}", i + 1);

        match serde_json::from_str::<serde_json::Value>(&block.content) {
            Ok(json) => {
                println!("  ✓ Valid JSON");

                if let Some(schema_name) = identify_schema(&json) {
                    println!("  Identified as {schema_name} schema");
                    match validate_against_schema(&json, schema_name) {
                        Ok(()) => println!("  ✓ Valid against schema"),
                        Err(e) => {
                            eprintln!("  ✗ Schema validation failed: {e}");
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("  ✗ Invalid JSON: {e}");
                eprintln!("Content:\n{}", block.content);
                return Err(e.into());
            }
        }
    }

    Ok(())
}

/// Helper to strip JavaScript-style comments from JSON examples
/// This allows documentation to include explanatory comments in JSON blocks
/// Also replaces [...] placeholders with [] for valid JSON
fn strip_json_comments(json_str: &str) -> String {
    json_str
        .lines()
        .map(|line| {
            // Remove // comments
            let line = if let Some(pos) = line.find("//") {
                &line[..pos]
            } else {
                line
            };
            // Replace [...] placeholders with []
            line.replace("[...]", "[]")
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Test JSON examples from CONTRACTS.md
#[test]
fn test_contracts_json_examples() -> Result<()> {
    let contracts_path = Path::new("docs/reference/CONTRACTS.md");
    if !contracts_path.exists() {
        println!("docs/CONTRACTS.md not found, skipping test");
        return Ok(());
    }

    let extractor = FenceExtractor::new(contracts_path)?;
    let json_blocks = extractor.extract_by_language("json");

    if json_blocks.is_empty() {
        println!("No JSON examples found in CONTRACTS.md");
        return Ok(());
    }

    println!(
        "Testing {} JSON examples from CONTRACTS.md",
        json_blocks.len()
    );

    for (i, block) in json_blocks.iter().enumerate() {
        println!("Parsing JSON example {}", i + 1);

        // Strip comments for documentation examples
        let cleaned_content = strip_json_comments(&block.content);

        // Skip blocks that are only comments (become empty after stripping)
        if cleaned_content.trim().is_empty() {
            println!("  ⊘ Skipped (comment-only block)");
            continue;
        }

        match serde_json::from_str::<serde_json::Value>(&cleaned_content) {
            Ok(json) => {
                println!("  ✓ Valid JSON");

                if let Some(schema_name) = identify_schema(&json) {
                    println!("  Identified as {schema_name} schema");
                    match validate_against_schema(&json, schema_name) {
                        Ok(()) => println!("  ✓ Valid against schema"),
                        Err(e) => {
                            eprintln!("  ✗ Schema validation failed: {e}");
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("  ✗ Invalid JSON: {e}");
                eprintln!("Content:\n{cleaned_content}");
                return Err(e.into());
            }
        }
    }

    Ok(())
}

use crate::doc_validation::common::JsonQuery;

/// Test jq equivalent functionality with generated examples
///
/// Note: jq examples in docs are for users; tests use Rust JSON Pointer equivalent
/// This test demonstrates `JsonQuery` capabilities that can be used to verify
/// jq-like queries when they are added to documentation.
#[test]
fn test_json_query_on_generated_examples() -> Result<()> {
    // Test with a sample receipt-like structure
    let sample_receipt = serde_json::json!({
        "schema_version": "1",
        "spec_id": "example-spec",
        "phase": "requirements",
        "outputs": [
            {"path": "artifacts/00-requirements.md", "blake3_first8": "abc12345"},
            {"path": "artifacts/10-design.md", "blake3_first8": "fedcba98"}
        ],
        "exit_code": 0
    });

    // Test basic queries
    assert_eq!(
        JsonQuery::get_string(&sample_receipt, "/spec_id")?,
        "example-spec"
    );

    assert_eq!(JsonQuery::get_number(&sample_receipt, "/exit_code")?, 0);

    // Test array operations
    assert_eq!(JsonQuery::array_length(&sample_receipt, "/outputs")?, 2);

    // Test field existence
    assert!(JsonQuery::has_field(&sample_receipt, "/phase"));
    assert!(!JsonQuery::has_field(&sample_receipt, "/nonexistent"));

    // Test array sorting verification
    assert!(JsonQuery::verify_sorted(&sample_receipt, "/outputs", "path").is_ok());

    println!("✓ JsonQuery functionality verified");

    Ok(())
}

#[derive(Debug, Default, Clone, Copy)]
struct JqFlags {
    exit_on_false: bool,
    #[allow(dead_code)] // Retained for parity with jq flags
    raw_output: bool,
}

fn strip_shell_prompt(line: &str) -> &str {
    let trimmed = line.trim_start();
    if let Some(rest) = trimmed.strip_prefix("$ ") {
        return rest;
    }
    if let Some(rest) = trimmed.strip_prefix("> ") {
        return rest;
    }
    trimmed
}

fn extract_command_substitution(line: &str) -> &str {
    if let (Some(start), Some(end)) = (line.find("$("), line.rfind(')'))
        && start + 2 < end
    {
        return &line[start + 2..end];
    }
    line
}

#[derive(Default)]
struct ScanState {
    in_single: bool,
    in_double: bool,
    escape: bool,
    paren_depth: usize,
}

impl ScanState {
    fn step(&mut self, ch: char) {
        if self.escape {
            self.escape = false;
            return;
        }

        if self.in_single {
            if ch == '\\' {
                self.escape = true;
            } else if ch == '\'' {
                self.in_single = false;
            }
            return;
        }

        if self.in_double {
            if ch == '\\' {
                self.escape = true;
            } else if ch == '"' {
                self.in_double = false;
            }
            return;
        }

        match ch {
            '\'' => self.in_single = true,
            '"' => self.in_double = true,
            '(' => self.paren_depth += 1,
            ')' => {
                if self.paren_depth > 0 {
                    self.paren_depth -= 1;
                }
            }
            _ => {}
        }
    }
}

fn split_pipeline(expr: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut buf = String::new();
    let mut state = ScanState::default();

    for ch in expr.chars() {
        if !state.in_single && !state.in_double && state.paren_depth == 0 && ch == '|' {
            let trimmed = buf.trim();
            if !trimmed.is_empty() {
                parts.push(trimmed.to_string());
            }
            buf.clear();
            continue;
        }
        buf.push(ch);
        state.step(ch);
    }

    let trimmed = buf.trim();
    if !trimmed.is_empty() {
        parts.push(trimmed.to_string());
    }

    parts
}

fn split_top_level(expr: &str, token: &str) -> Option<(String, String)> {
    let bytes = expr.as_bytes();
    let token_bytes = token.as_bytes();
    let mut state = ScanState::default();
    let mut i = 0;

    while i + token_bytes.len() <= bytes.len() {
        if !state.in_single
            && !state.in_double
            && state.paren_depth == 0
            && bytes[i..].starts_with(token_bytes)
        {
            let left = expr[..i].trim().to_string();
            let right = expr[i + token_bytes.len()..].trim().to_string();
            return Some((left, right));
        }

        state.step(bytes[i] as char);
        i += 1;
    }

    None
}

fn is_truthy(value: &Value) -> bool {
    !matches!(value, Value::Null | Value::Bool(false))
}

fn parse_literal(expr: &str) -> Result<Value> {
    let expr = expr.trim();
    if expr.starts_with('\'') && expr.ends_with('\'') && expr.len() >= 2 {
        return Ok(Value::String(expr[1..expr.len() - 1].to_string()));
    }
    if let Ok(value) = serde_json::from_str(expr) {
        return Ok(value);
    }
    anyhow::bail!("Unsupported literal in jq expression: {expr}");
}

fn eval_path(values: Vec<Value>, path: &str) -> Result<Vec<Value>> {
    let path = path.trim();
    if path == "." {
        return Ok(values);
    }

    let mut current = values;
    let segments = path.trim_start_matches('.').split('.');

    for segment in segments {
        if segment.is_empty() {
            continue;
        }
        let (name, expand) = if let Some(stripped) = segment.strip_suffix("[]") {
            (stripped, true)
        } else {
            (segment, false)
        };

        let mut next = Vec::new();
        for value in &current {
            let target = if name.is_empty() {
                value.clone()
            } else {
                match value {
                    Value::Object(map) => map
                        .get(name)
                        .cloned()
                        .ok_or_else(|| anyhow::anyhow!("Missing field '{name}' in jq path"))?,
                    _ => anyhow::bail!("Cannot access field '{name}' on non-object"),
                }
            };

            if expand {
                match target {
                    Value::Array(items) => {
                        next.extend(items);
                    }
                    _ => anyhow::bail!("Expected array for '{segment}' expansion"),
                }
            } else {
                next.push(target);
            }
        }

        current = next;
    }

    Ok(current)
}

fn eval_jq_filter(filter: &str, input: &Value) -> Result<Vec<Value>> {
    let filter = filter.trim();
    if filter.is_empty() || filter == "." {
        return Ok(vec![input.clone()]);
    }

    if let Some((left, right)) = split_top_level(filter, "==") {
        let left_values = eval_jq_filter(&left, input)?;
        let right_value = parse_literal(&right)?;
        let results = left_values
            .into_iter()
            .map(|value| Value::Bool(value == right_value))
            .collect();
        return Ok(results);
    }

    let segments = split_pipeline(filter);
    let mut values = vec![input.clone()];

    for segment in segments {
        let segment = segment.trim();
        if segment.is_empty() {
            continue;
        }

        if let Some(inner) = segment
            .strip_prefix("select(")
            .and_then(|s| s.strip_suffix(')'))
        {
            let mut filtered = Vec::new();
            for value in values {
                if eval_jq_filter(inner, &value)?.iter().any(is_truthy) {
                    filtered.push(value);
                }
            }
            values = filtered;
            continue;
        }

        if segment == "not" {
            values = values
                .into_iter()
                .map(|value| Value::Bool(!is_truthy(&value)))
                .collect();
            continue;
        }

        if let Some(arg) = segment
            .strip_prefix("contains(")
            .and_then(|s| s.strip_suffix(')'))
        {
            let needle = parse_literal(arg)?;
            let needle = needle
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("contains() expects a string literal"))?;
            values = values
                .into_iter()
                .map(|value| match value.as_str() {
                    Some(haystack) => Ok(Value::Bool(haystack.contains(needle))),
                    None => anyhow::bail!("contains() expects a string input"),
                })
                .collect::<Result<Vec<_>>>()?;
            continue;
        }

        if segment.starts_with('.') {
            values = eval_path(values, segment)?;
            continue;
        }

        anyhow::bail!("Unsupported jq segment: {segment}");
    }

    Ok(values)
}

fn line_contains_jq(line: &str) -> bool {
    line.split_whitespace().any(|token| {
        token == "jq"
            || token.ends_with("\\jq")
            || token.ends_with("/jq")
            || token.ends_with("jq.exe")
    })
}

fn parse_jq_segment(segment: &str) -> Result<(JqFlags, String, Option<String>)> {
    let tokens = shell_words::split(segment)
        .with_context(|| format!("Failed to parse jq command segment: {segment}"))?;
    if tokens.is_empty() {
        anyhow::bail!("Empty jq command segment");
    }

    let jq_pos = tokens.iter().position(|token| {
        token == "jq"
            || token.ends_with("\\jq")
            || token.ends_with("/jq")
            || token.ends_with("jq.exe")
    });

    let jq_pos = jq_pos.ok_or_else(|| anyhow::anyhow!("No jq command found in segment"))?;

    let mut flags = JqFlags::default();
    let mut filter: Option<String> = None;
    let mut files = Vec::new();
    let mut parsing_flags = true;

    for token in tokens.iter().skip(jq_pos + 1) {
        if parsing_flags && token == "--" {
            parsing_flags = false;
            continue;
        }

        if parsing_flags && token.starts_with('-') {
            for ch in token.trim_start_matches('-').chars() {
                match ch {
                    'e' => flags.exit_on_false = true,
                    'r' => flags.raw_output = true,
                    _ => {}
                }
            }
            continue;
        }

        parsing_flags = false;
        if filter.is_none() {
            filter = Some(token.to_string());
        } else {
            files.push(token.to_string());
        }
    }

    let filter = filter.unwrap_or_else(|| ".".to_string());
    let file = files.first().cloned();

    Ok((flags, filter, file))
}

fn load_json_from_path(path: &Path) -> Result<Value> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read JSON file: {}", path.display()))?;
    serde_json::from_str(&content)
        .with_context(|| format!("Failed to parse JSON file: {}", path.display()))
}

fn try_load_json(path: &Path) -> Option<Value> {
    if !path.exists() {
        return None;
    }
    load_json_from_path(path).ok()
}

fn load_fallback_json(filter: &str) -> Value {
    let doctor_sample = PathBuf::from("docs/schemas/doctor.v1.minimal.json");
    let status_sample = PathBuf::from("docs/schemas/status.v1.minimal.json");
    let receipt_sample = PathBuf::from("docs/schemas/receipt.v1.minimal.json");

    let sample = if filter.contains(".ok") || filter.contains("checks") {
        try_load_json(&doctor_sample)
    } else if filter.contains("phase_statuses") || filter.contains("pending_fixups") {
        try_load_json(&status_sample)
    } else {
        try_load_json(&receipt_sample)
    };

    sample.unwrap_or_else(|| json!({ "schema_version": "1", "ok": true }))
}

/// Extract the subcommand from an xchecker command line.
///
/// Scans for a known subcommand token rather than just "first non-flag token",
/// which avoids false positives when flag values (e.g., `--output-dir /tmp`)
/// appear before the subcommand.
///
/// Returns the subcommand if found, or None if not an xchecker command or
/// no known subcommand is present.
fn xchecker_subcommand(cmd: &str) -> Option<&str> {
    // Known xchecker subcommands (from src/cli.rs Commands enum)
    const SUBCMDS: &[&str] = &[
        "spec",
        "status",
        "resume",
        "clean",
        "benchmark",
        "test",
        "doctor",
        "init",
        "project",
        "gate",
        "template",
    ];

    let mut tokens = cmd.split_whitespace();

    // First token must be xchecker
    if tokens.next()? != "xchecker" {
        return None;
    }

    // Find first token that matches a known subcommand
    tokens.find(|tok| SUBCMDS.contains(tok))
}

fn resolve_jq_input(
    segments: &[String],
    jq_index: usize,
    file_arg: Option<String>,
    filter: &str,
    runner: &StubRunner,
) -> Result<Value> {
    if let Some(file) = file_arg {
        let path = Path::new(&file);
        if path.exists() {
            return load_json_from_path(path);
        }
        return Ok(load_fallback_json(filter));
    }

    if jq_index == 0 {
        return Ok(load_fallback_json(filter));
    }

    let input_segment = segments[jq_index - 1].trim();
    if input_segment.is_empty() {
        return Ok(load_fallback_json(filter));
    }

    let input_segment = strip_shell_prompt(input_segment);

    if input_segment.starts_with("xchecker") {
        let result = runner.run_command(input_segment)?;

        // Allow exit code 1 for `xchecker doctor --json` since it means
        // "some checks failed", not "command error". The doctor command
        // still produces valid JSON that we can process.
        //
        // We only relax for:
        // - subcommand == "doctor" (detected structurally, not via substring)
        // - --json flag present (so we expect JSON output)
        // - exit code == 1 specifically (not 2 for bad args, 70 for provider failure, etc.)
        let subcmd = xchecker_subcommand(input_segment);
        let is_doctor_json = subcmd == Some("doctor") && input_segment.contains("--json");

        // Fail on non-zero exit, unless it's doctor --json with exit code 1
        // (exit code 1 means "checks failed" but JSON is still valid)
        if result.exit_code != 0 && !(is_doctor_json && result.exit_code == 1) {
            anyhow::bail!(
                "xchecker command failed (exit {}): {}",
                result.exit_code,
                input_segment
            );
        }

        let stdout = result.stdout.trim();
        return serde_json::from_str(stdout)
            .with_context(|| format!("Failed to parse JSON from: {input_segment}"));
    }

    if input_segment.starts_with("cat ") {
        let tokens = shell_words::split(input_segment)?;
        if tokens.len() < 2 {
            anyhow::bail!("cat command missing file argument: {input_segment}");
        }
        let path = Path::new(&tokens[1]);
        return load_json_from_path(path);
    }

    anyhow::bail!("Unsupported jq input segment: {input_segment}");
}

fn execute_jq_example(line: &str, runner: &StubRunner) -> Result<()> {
    let line = strip_shell_prompt(line);
    let line = extract_command_substitution(line);
    let segments = split_pipeline(line);

    let jq_index = segments.iter().position(|segment| {
        segment
            .split_whitespace()
            .any(|token| token == "jq" || token.ends_with("jq.exe") || token.ends_with("/jq"))
    });

    let jq_index = jq_index.ok_or_else(|| anyhow::anyhow!("No jq command found in: {line}"))?;
    let (flags, filter, file_arg) = parse_jq_segment(&segments[jq_index])?;
    let input = resolve_jq_input(&segments, jq_index, file_arg, &filter, runner)?;
    let results = eval_jq_filter(&filter, &input)?;

    if flags.exit_on_false && !results.iter().any(is_truthy) {
        anyhow::bail!("jq -e expression evaluated to false: {filter}");
    }

    Ok(())
}

/// Test jq examples from documentation (when they exist)
///
/// This test will extract jq commands from documentation and execute
/// equivalent Rust queries using `JsonQuery`.
#[test]
fn test_jq_examples_from_docs() -> Result<()> {
    // Check all documentation files for jq examples
    let doc_files = vec![
        "README.md",
        "docs/CONFIGURATION.md",
        "docs/DOCTOR.md",
        "docs/reference/CONTRACTS.md",
    ];

    let mut jq_examples_found = 0;
    let mut jq_examples_executed = 0;
    let runner = StubRunner::new()?;

    for doc_file in doc_files {
        let path = Path::new(doc_file);
        if !path.exists() {
            continue;
        }

        // Look for jq commands in shell blocks or as separate jq blocks
        let extractor = FenceExtractor::new(path)?;
        let bash_blocks = extractor.extract_by_language("bash");
        let sh_blocks = extractor.extract_by_language("sh");
        let jq_blocks = extractor.extract_by_language("jq");

        for block in [bash_blocks, sh_blocks, jq_blocks].concat() {
            for line in block.content.lines() {
                let trimmed = line.trim();
                if trimmed.is_empty() || trimmed.starts_with('#') {
                    continue;
                }

                let is_jq_block = block.language == "jq";
                if !is_jq_block && !line_contains_jq(trimmed) {
                    continue;
                }

                jq_examples_found += 1;
                let command = if is_jq_block {
                    format!("jq {trimmed}")
                } else {
                    trimmed.to_string()
                };

                println!("Found jq example in {}: {}", doc_file, trimmed);
                execute_jq_example(&command, &runner)
                    .with_context(|| format!("jq example failed in {doc_file}: {trimmed}"))?;
                jq_examples_executed += 1;
            }
        }
    }

    if jq_examples_found == 0 {
        println!(
            "No jq examples found in documentation (this is expected if none have been added yet)"
        );
    } else {
        println!("Executed {jq_examples_executed} jq examples");
    }

    Ok(())
}

#[cfg(test)]
mod subcommand_tests {
    use super::xchecker_subcommand;

    #[test]
    fn test_xchecker_subcommand_basic() {
        assert_eq!(xchecker_subcommand("xchecker doctor"), Some("doctor"));
        assert_eq!(xchecker_subcommand("xchecker status"), Some("status"));
        assert_eq!(xchecker_subcommand("xchecker spec"), Some("spec"));
        assert_eq!(xchecker_subcommand("xchecker resume"), Some("resume"));
        assert_eq!(xchecker_subcommand("xchecker gate"), Some("gate"));
    }

    #[test]
    fn test_xchecker_subcommand_with_flags_before() {
        // Flags before subcommand
        assert_eq!(
            xchecker_subcommand("xchecker --json doctor"),
            Some("doctor")
        );
        assert_eq!(xchecker_subcommand("xchecker -v doctor"), Some("doctor"));
    }

    #[test]
    fn test_xchecker_subcommand_with_flags_after() {
        // Flags after subcommand - still returns the subcommand
        assert_eq!(
            xchecker_subcommand("xchecker doctor --json"),
            Some("doctor")
        );
        assert_eq!(xchecker_subcommand("xchecker status -v"), Some("status"));
    }

    #[test]
    fn test_xchecker_subcommand_no_match() {
        // Not xchecker command
        assert_eq!(xchecker_subcommand("cargo build"), None);
        assert_eq!(xchecker_subcommand("echo doctor"), None);
    }

    #[test]
    fn test_xchecker_subcommand_only_flags() {
        // No subcommand, only flags
        assert_eq!(xchecker_subcommand("xchecker --help"), None);
        assert_eq!(xchecker_subcommand("xchecker -V"), None);
    }

    #[test]
    fn test_xchecker_subcommand_false_positive_prevention() {
        // These should NOT match "doctor" via substring
        assert_eq!(
            xchecker_subcommand("xchecker status --spec doctor-fix"),
            Some("status")
        );
        // A file path containing "doctor" should not be detected as a subcommand
        // (since "run" is not in SUBCMDS, this returns None, which is correct)
        assert_eq!(
            xchecker_subcommand("xchecker --verbose /path/to/doctor/spec"),
            None
        );
    }

    #[test]
    fn test_xchecker_subcommand_with_flag_value_paths() {
        // Non-subcommand tokens (paths, values) should be ignored when scanning
        // for the first known subcommand. This works because paths like "/some/path"
        // are not in the SUBCMDS list.
        //
        // Note: This heuristic can still be fooled if a flag value is literally
        // a subcommand name (e.g., `--config doctor`), but that's rare in practice.
        assert_eq!(
            xchecker_subcommand("xchecker --output-dir /some/path doctor --json"),
            Some("doctor")
        );
        assert_eq!(
            xchecker_subcommand("xchecker --config /tmp/config.toml status my-spec"),
            Some("status")
        );
    }
}