postscriptum 0.1.1

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
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
//! Cross-engine test suite (Rhai vs Python) plus file-based behavior tests.
//!
//! Requires both the `rhai` and `python` features (the crate defaults to both).

#![cfg(all(feature = "python", feature = "rhai"))]

use std::collections::HashMap;
use std::fs;
use std::io::{self, Result};
use std::path::{Path, PathBuf};

use postscriptum::{EngineType, ScriptEngine, get_engine};

/// Directory holding the `{language}.{ext}` behavior fixtures.
fn cases_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/cases")
}

// Test suite for both Rhai and Python engines - integrated from test_suite.rs
struct TestSuite {
    rhai_engine: Box<dyn ScriptEngine>,
    python_engine: Box<dyn ScriptEngine>,
}

impl TestSuite {
    fn new() -> Self {
        TestSuite {
            rhai_engine: get_engine(EngineType::Rhai),
            python_engine: get_engine(EngineType::Python),
        }
    }

    // Helper method to run tests on both engines
    fn test_both_engines(&mut self, code: &str, expected_result: &str) -> bool {
        let rhai_result = self.rhai_engine.eval(code);
        let python_result = self.python_engine.eval(code);

        match (rhai_result, python_result) {
            (Ok(rhai_val), Ok(python_val)) => {
                // Compare results (trim whitespace for better comparison)
                let rhai_trimmed = rhai_val.trim();
                let python_trimmed = python_val.trim();
                let expected_trimmed = expected_result.trim();

                if rhai_trimmed == expected_trimmed && python_trimmed == expected_trimmed {
                    println!(
                        "✓ PASS: '{}' - Rhai: '{}', Python: '{}'",
                        code.replace('\n', " "),
                        rhai_trimmed,
                        python_trimmed
                    );
                    true
                } else {
                    println!(
                        "✗ FAIL: '{}' - Expected: '{}', Rhai: '{}', Python: '{}'",
                        code.replace('\n', " "),
                        expected_trimmed,
                        rhai_trimmed,
                        python_trimmed
                    );
                    false
                }
            }
            (Err(rhai_err), Err(python_err)) => {
                // Both engines failed, which might be expected for error cases
                println!(
                    "✓ PASS (both failed): '{}' - Rhai: '{}', Python: '{}'",
                    code.replace('\n', " "),
                    rhai_err,
                    python_err
                );
                true // Consider this a pass if both handle errors the same way
            }
            (Ok(rhai_val), Err(python_err)) => {
                println!(
                    "✗ FAIL: '{}' - Rhai: '{}', Python: '{}'",
                    code.replace('\n', " "),
                    rhai_val,
                    python_err
                );
                false
            }
            (Err(rhai_err), Ok(python_val)) => {
                println!(
                    "✗ FAIL: '{}' - Rhai: '{}', Python: '{}'",
                    code.replace('\n', " "),
                    rhai_err,
                    python_val
                );
                false
            }
        }
    }

    // Helper method to run a test expecting an error on both engines
    fn test_both_engines_error(&mut self, code: &str) -> bool {
        let rhai_result = self.rhai_engine.eval(code);
        let python_result = self.python_engine.eval(code);

        match (rhai_result, python_result) {
            (Err(_), Err(_)) => {
                println!("✓ PASS (both engines error): '{}'", code.replace('\n', " "));
                true
            }
            (Ok(rhai_val), Err(_)) => {
                println!(
                    "✗ FAIL: '{}' - Rhai: '{}', Python: error",
                    code.replace('\n', " "),
                    rhai_val
                );
                false
            }
            (Err(_), Ok(python_val)) => {
                println!(
                    "✗ FAIL: '{}' - Rhai: error, Python: '{}'",
                    code.replace('\n', " "),
                    python_val
                );
                false
            }
            (Ok(rhai_val), Ok(python_val)) => {
                println!(
                    "✗ FAIL: '{}' - Expected both to error, but Rhai: '{}', Python: '{}'",
                    code.replace('\n', " "),
                    rhai_val,
                    python_val
                );
                false
            }
        }
    }

    // Evaluate `code` on ONE engine and compare against `expected`.
    //
    // Unlike `test_both_engines`, this lets each language run its own
    // syntax: Rhai `let`/`fn` snippets are SyntaxErrors in Python and
    // vice versa, so a shared vector can never pass both engines.
    fn check_single(
        engine: &mut Box<dyn ScriptEngine>,
        lang_name: &str,
        code: &str,
        expected: &str,
    ) -> bool {
        match engine.eval(code) {
            Ok(val) => {
                if val.trim() == expected.trim() {
                    println!(
                        "✓ PASS ({}): '{}' - Got: '{}'",
                        lang_name,
                        code.replace('\n', " "),
                        val.trim()
                    );
                    true
                } else {
                    println!(
                        "✗ FAIL ({}): '{}' - Expected: '{}', Got: '{}'",
                        lang_name,
                        code.replace('\n', " "),
                        expected.trim(),
                        val.trim()
                    );
                    false
                }
            }
            Err(err) => {
                println!(
                    "✗ FAIL ({}): '{}' - Error: '{}'",
                    lang_name,
                    code.replace('\n', " "),
                    err
                );
                false
            }
        }
    }
}

pub struct TestRunner {
    pub engines: HashMap<EngineType, Box<dyn ScriptEngine>>,
}

impl TestRunner {
    pub fn new() -> Self {
        let mut engines: HashMap<EngineType, Box<dyn ScriptEngine>> = HashMap::new();
        engines.insert(EngineType::Rhai, get_engine(EngineType::Rhai));
        engines.insert(EngineType::Python, get_engine(EngineType::Python));

        TestRunner { engines }
    }
}

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

impl TestRunner {
    pub fn run_all_tests(&mut self) -> Result<bool> {
        println!("Running comprehensive test suite...");

        // Run the integrated test suite (from test_suite.rs functionality)
        let mut suite = TestSuite::new();
        let mut total_passed = 0;
        let mut total_tests = 0;

        // Run basic functionality tests
        for (passed, count) in [
            self.run_basic_arithmetic_tests(&mut suite),
            self.run_variables_and_assignments_tests(&mut suite),
            self.run_conditionals_tests(&mut suite),
            self.run_loops_tests(&mut suite),
            self.run_functions_tests(&mut suite),
            self.run_string_operations_tests(&mut suite),
            self.run_error_handling_tests(&mut suite),
            self.run_python_specific_syntax_tests(&mut suite),
            self.run_rhai_specific_syntax_tests(&mut suite),
        ] {
            total_passed += passed;
            total_tests += count;
        }

        println!("\n=== INTEGRATED TEST SUITE SUMMARY ===");
        println!("Total integrated tests: {}", total_tests);
        println!("Passed: {}", total_passed);
        println!("Failed: {}", total_tests - total_passed);
        println!(
            "Success rate: {:.1}%",
            (total_passed as f64 / total_tests as f64) * 100.0
        );

        let integrated_all_passed = total_passed == total_tests;

        // Run file-based tests
        let file_dirs = fs::read_dir(cases_dir())?;

        let mut total_file_tests = 0;
        let mut passed_file_tests = 0;

        for dir in file_dirs {
            let dir = dir?;
            if dir.file_type()?.is_dir() {
                println!(
                    "\nRunning file-based tests in: {}",
                    dir.file_name().to_string_lossy()
                );

                let (dir_passed, dir_total) = self.run_test_directory(&dir.path())?;
                total_file_tests += dir_total;
                passed_file_tests += dir_passed;
            }
        }

        println!("\n=== FILE-BASED TEST SUITE SUMMARY ===");
        println!("Total file-based tests: {}", total_file_tests);
        println!("Passed: {}", passed_file_tests);
        println!("Failed: {}", total_file_tests - passed_file_tests);
        if total_file_tests > 0 {
            println!(
                "Success rate: {:.1}%",
                (passed_file_tests as f64 / total_file_tests as f64) * 100.0
            );
        }

        let file_all_passed = total_file_tests == 0 || passed_file_tests == total_file_tests;

        // Overall summary
        let overall_total_tests = total_tests + total_file_tests;
        let overall_passed_tests = total_passed + passed_file_tests;

        println!("\n=== OVERALL SUMMARY ===");
        println!("Total tests: {}", overall_total_tests);
        println!("Passed: {}", overall_passed_tests);
        println!("Failed: {}", overall_total_tests - overall_passed_tests);
        if overall_total_tests > 0 {
            println!(
                "Success rate: {:.1}%",
                (overall_passed_tests as f64 / overall_total_tests as f64) * 100.0
            );
        }

        Ok(integrated_all_passed && file_all_passed)
    }

    fn run_basic_arithmetic_tests(&mut self, suite: &mut TestSuite) -> (usize, usize) {
        let mut passed = 0;
        let mut total = 0;

        // Basic arithmetic operations shared by both languages.
        // NOTE: `/` is NOT shared: Python yields `5.0` for `15 / 3` while
        // Rhai yields `5`, so division is covered per-language below.
        let tests = vec![
            ("2 + 2", "4"),
            ("5 - 3", "2"),
            ("4 * 5", "20"),
            ("10 % 3", "1"),
            ("2 + 3 * 4", "14"), // Operator precedence
            ("(2 + 3) * 4", "20"), // Parentheses
                                 // Note: Python has ** for power, but Rhai might not support ** the same way
                                 // so we'll test power separately based on language-specific syntax
        ];

        for (code, expected) in tests {
            total += 1;
            if suite.test_both_engines(code, expected) {
                passed += 1;
            }
        }

        println!("\nBasic Arithmetic Tests: {}/{} passed", passed, total);
        (passed, total)
    }

    fn run_variables_and_assignments_tests(&mut self, suite: &mut TestSuite) -> (usize, usize) {
        let mut passed = 0;
        let mut total = 0;

        // Variable assignments and usage.
        // Each language runs its own assignment syntax: Rhai `let` is a
        // SyntaxError in Python, so a shared vector can never pass both.
        let rhai_tests = vec![
            ("let x = 5; x", "5"),
            ("let a = 10; let b = 20; a + b", "30"),
            ("let z = 42; z * 2", "84"),
        ];

        for (code, expected) in rhai_tests {
            total += 1;
            if TestSuite::check_single(&mut suite.rhai_engine, "Rhai", code, expected) {
                passed += 1;
            }
        }

        let python_tests = vec![
            ("x = 5\nx", "5"),
            ("a = 10\nb = 20\na + b", "30"),
            ("z = 42\nz * 2", "84"),
        ];

        for (code, expected) in python_tests {
            total += 1;
            if TestSuite::check_single(&mut suite.python_engine, "Python", code, expected) {
                passed += 1;
            }
        }

        println!(
            "\nVariables and Assignments Tests: {}/{} passed",
            passed, total
        );
        (passed, total)
    }

    fn run_conditionals_tests(&mut self, suite: &mut TestSuite) -> (usize, usize) {
        let mut passed = 0;
        let mut total = 0;

        // Conditional statements: Rhai blocks on the Rhai engine,
        // Python conditional expressions on the Python engine.
        let rhai_tests = vec![
            ("if true { 1 } else { 0 }", "1"),
            ("if false { 1 } else { 0 }", "0"),
            ("let x = 5; if x > 3 { 10 } else { 20 }", "10"),
            ("let y = 2; if y > 3 { 10 } else { 20 }", "20"),
        ];

        for (code, expected) in rhai_tests {
            total += 1;
            if TestSuite::check_single(&mut suite.rhai_engine, "Rhai", code, expected) {
                passed += 1;
            }
        }

        let python_tests = vec![
            ("1 if True else 0", "1"),
            ("0 if False else 1", "1"),
            ("10 if 5 > 3 else 20", "10"),
            ("10 if 2 > 3 else 20", "20"),
        ];

        for (code, expected) in python_tests {
            total += 1;
            if TestSuite::check_single(&mut suite.python_engine, "Python", code, expected) {
                passed += 1;
            }
        }

        println!("\nConditionals Tests: {}/{} passed", passed, total);
        (passed, total)
    }

    fn run_loops_tests(&mut self, suite: &mut TestSuite) -> (usize, usize) {
        let mut passed = 0;
        let mut total = 0;

        // Loops: `while` on the Rhai engine, `for/range` on Python.
        let rhai_tests = vec![(
            "let sum = 0; let i = 0; while i < 3 { sum = sum + 1; i = i + 1; } sum",
            "3",
        )];

        for (code, expected) in rhai_tests {
            total += 1;
            if TestSuite::check_single(&mut suite.rhai_engine, "Rhai", code, expected) {
                passed += 1;
            }
        }

        let python_tests = vec![("total = 0\nfor i in range(3):\n    total += 1\ntotal", "3")];

        for (code, expected) in python_tests {
            total += 1;
            if TestSuite::check_single(&mut suite.python_engine, "Python", code, expected) {
                passed += 1;
            }
        }

        println!("\nLoops Tests: {}/{} passed", passed, total);
        (passed, total)
    }

    fn run_functions_tests(&mut self, suite: &mut TestSuite) -> (usize, usize) {
        let mut passed = 0;
        let mut total = 0;

        // Function definition and calling, per language.
        let rhai_tests = vec![
            ("fn add(x, y) { x + y } add(3, 4)", "7"),
            ("fn square(x) { x * x } square(5)", "25"),
        ];

        for (code, expected) in rhai_tests {
            total += 1;
            if TestSuite::check_single(&mut suite.rhai_engine, "Rhai", code, expected) {
                passed += 1;
            }
        }

        let python_tests = vec![
            ("(lambda x, y: x + y)(3, 4)", "7"),
            ("def square(n):\n    return n * n\nsquare(5)", "25"),
        ];

        for (code, expected) in python_tests {
            total += 1;
            if TestSuite::check_single(&mut suite.python_engine, "Python", code, expected) {
                passed += 1;
            }
        }

        println!("\nFunctions Tests: {}/{} passed", passed, total);
        (passed, total)
    }

    fn run_string_operations_tests(&mut self, suite: &mut TestSuite) -> (usize, usize) {
        let mut passed = 0;
        let mut total = 0;

        // String operations (basic concatenation in Rhai, will need different approach for Python)
        let rhai_tests = vec![
            ("\"Hello\" + \" \" + \"World\"", "Hello World"),
            ("\"Test\" + \"123\"", "Test123"),
        ];

        for (code, expected) in rhai_tests {
            total += 1;
            if suite.test_both_engines(code, expected) {
                passed += 1;
            }
        }

        println!("\nString Operations Tests: {}/{} passed", passed, total);
        (passed, total)
    }

    fn run_error_handling_tests(&mut self, suite: &mut TestSuite) -> (usize, usize) {
        let mut passed = 0;
        let mut total = 0;

        // Test cases that should cause errors in both engines
        let error_tests = vec![
            "undefined_variable", // Should cause an error
                                  // Note: Division by zero may be handled differently between engines
        ];

        for code in error_tests {
            total += 1;
            if suite.test_both_engines_error(code) {
                passed += 1;
            }
        }

        println!("\nError Handling Tests: {}/{} passed", passed, total);
        (passed, total)
    }

    fn run_python_specific_syntax_tests(&mut self, suite: &mut TestSuite) -> (usize, usize) {
        let mut passed = 0;
        let mut total = 0;

        // Python-specific tests - only test against Python engine
        let python_tests = vec![
            ("2 + 2", "4"),
            ("5 - 3", "2"),
            ("4 * 5", "20"),
            ("15 // 3", "5"), // Integer division in Python
            ("10 % 3", "1"),  // Modulo
            ("2 ** 3", "8"),  // Power in Python
            ("\"Hello\" + \" \" + \"World\"", "Hello World"),
            ("len([1, 2, 3])", "3"),
            ("[1, 2, 3][0]", "1"),
            // Note: Function definitions in Python syntax will not work in Rhai
            // so we'll test them separately
        ];

        for (code, expected) in python_tests {
            total += 1;
            let python_result = suite.python_engine.eval(code);
            match python_result {
                Ok(python_val) => {
                    if python_val.trim() == expected.trim() {
                        println!(
                            "✓ PASS (Python): '{}' - Python: '{}'",
                            code.replace('\n', " "),
                            python_val.trim()
                        );
                        passed += 1;
                    } else {
                        println!(
                            "✗ FAIL (Python): '{}' - Expected: '{}', Python: '{}'",
                            code.replace('\n', " "),
                            expected.trim(),
                            python_val.trim()
                        );
                    }
                }
                Err(err) => {
                    println!(
                        "✗ FAIL (Python): '{}' - Error: '{}'",
                        code.replace('\n', " "),
                        err
                    );
                }
            }
        }

        println!(
            "\nPython-Specific Syntax Tests: {}/{} passed",
            passed, total
        );
        (passed, total)
    }

    fn run_rhai_specific_syntax_tests(&mut self, suite: &mut TestSuite) -> (usize, usize) {
        let mut passed = 0;
        let mut total = 0;

        // Rhai-specific tests
        let rhai_tests = vec![
            ("2 + 2", "4"),
            ("5 - 3", "2"),
            ("4 * 5", "20"),
            ("15 / 3", "5"),
            ("10 % 3", "1"),
            ("2 ** 3", "8"), // Power in Rhai
            ("\"Hello\" + \" \" + \"World\"", "Hello World"),
            ("let arr = [1, 2, 3]; arr.len()", "3"), // Using .len() method
            ("let arr = [1, 2, 3]; arr[0]", "1"),
            ("fn add(x, y) { x + y } add(3, 4)", "7"),
            ("let x = 5; if x > 3 { 10 } else { 20 }", "10"),
            (
                "let sum = 0; let i = 0; while i < 3 { sum = sum + 1; i = i + 1; } sum",
                "3",
            ),
            ("let s = \"test\"; s.len()", "4"), // String length
        ];

        for (code, expected) in rhai_tests {
            total += 1;
            let rhai_result = suite.rhai_engine.eval(code);
            match rhai_result {
                Ok(rhai_val) => {
                    if rhai_val.trim() == expected.trim() {
                        println!(
                            "✓ PASS (Rhai): '{}' - Rhai: '{}'",
                            code.replace('\n', " "),
                            rhai_val.trim()
                        );
                        passed += 1;
                    } else {
                        println!(
                            "✗ FAIL (Rhai): '{}' - Expected: '{}', Rhai: '{}'",
                            code.replace('\n', " "),
                            expected.trim(),
                            rhai_val.trim()
                        );
                    }
                }
                Err(err) => {
                    println!(
                        "✗ FAIL (Rhai): '{}' - Error: '{}'",
                        code.replace('\n', " "),
                        err
                    );
                }
            }
        }

        println!("\nRhai-Specific Syntax Tests: {}/{} passed", passed, total);
        (passed, total)
    }

    fn run_test_directory(&mut self, dir_path: &Path) -> Result<(usize, usize)> {
        let mut total_tests = 0;
        let mut passed_tests = 0;

        // Collect all test files by name (without extension)
        let mut test_files: HashMap<String, HashMap<EngineType, String>> = HashMap::new();

        for entry in fs::read_dir(dir_path)? {
            let entry = entry?;
            let file_path = entry.path();

            if file_path.is_file() {
                if let Some(file_name) = file_path.file_name().and_then(|n| n.to_str()) {
                    // Extract test name and language from filename
                    if let Some((test_name, ext)) = file_name.rsplit_once('.') {
                        let lang = match ext {
                            "rhai" => EngineType::Rhai,
                            "py" | "python" => EngineType::Python,
                            _ => continue, // Skip unsupported extensions
                        };

                        test_files
                            .entry(test_name.to_string())
                            .or_default()
                            .insert(lang, file_path.to_string_lossy().to_string());
                    }
                }
            }
        }

        // Run tests for each test name
        for (test_name, file_paths) in test_files {
            let test_result = self.run_single_test(&test_name, &file_paths)?;
            total_tests += 1;
            if test_result {
                passed_tests += 1;
            }
        }

        Ok((passed_tests, total_tests))
    }

    fn run_single_test(
        &mut self,
        test_name: &str,
        file_paths: &HashMap<EngineType, String>,
    ) -> Result<bool> {
        let mut all_passed = true;

        for (language, file_path) in file_paths {
            let lang_name = match language {
                EngineType::Rhai => "Rhai",
                EngineType::Python => "Python",
            };
            // Every fixture must have a `<stem>.expected` sidecar holding the
            // expected (trimmed) eval output. A test with no expectation
            // validates nothing, so a missing sidecar is a loud failure.
            let expected_path = Path::new(file_path).with_extension("expected");
            let expected = match fs::read_to_string(&expected_path) {
                Ok(contents) => contents,
                Err(e) => {
                    println!(
                        "✗ FAIL ({}): {} - Missing expectation file {} ({})",
                        lang_name,
                        test_name,
                        expected_path.display(),
                        e
                    );
                    all_passed = false;
                    continue;
                }
            };
            match fs::read_to_string(file_path) {
                Ok(code) => match self.engines.get_mut(language) {
                    Some(engine) => match engine.as_mut().eval(&code) {
                        Ok(result) => {
                            if result.trim() == expected.trim() {
                                println!(
                                    "✓ PASS ({}): {} - Result: {}",
                                    lang_name,
                                    test_name,
                                    result.trim()
                                );
                            } else {
                                println!(
                                    "✗ FAIL ({}): {} - Expected: '{}', Got: '{}'",
                                    lang_name,
                                    test_name,
                                    expected.trim(),
                                    result.trim()
                                );
                                all_passed = false;
                            }
                        }
                        Err(e) => {
                            println!("✗ FAIL ({}): {} - Error: {}", lang_name, test_name, e);
                            all_passed = false;
                        }
                    },
                    None => {
                        println!("⚠ SKIP: {} - No engine for {:?}", test_name, language);
                    }
                },
                Err(e) => {
                    println!("✗ ERROR: Could not read test file {} - {}", file_path, e);
                    all_passed = false;
                }
            }
        }

        Ok(all_passed)
    }

    pub fn run_specific_test(&mut self, test_category: &str, test_name: &str) -> Result<bool> {
        let dir_path = cases_dir().join(test_category);
        if !dir_path.exists() {
            println!("Test directory {} does not exist", test_category);
            return Ok(false);
        }

        // Find the specific test files
        let mut test_files: HashMap<EngineType, String> = HashMap::new();

        // Look for files that match the test name
        for entry in fs::read_dir(&dir_path)? {
            let entry = entry?;
            let file_path = entry.path();

            if !file_path.is_file() {
                return Ok(false);
            }

            let file_name = match file_path.file_name() {
                Some(name) => name
                    .to_str()
                    .ok_or(io::Error::other("can't convert file path to file name"))?,
                None => return Ok(false),
            };

            if !file_name.starts_with(test_name) {
                return Ok(false);
            }

            // NOTE: no let-chains (`if let … && …`) — MSRV is 1.85.
            if let Some((name, ext)) = file_name.rsplit_once('.') {
                if name == test_name {
                    let lang = match ext {
                        "rhai" => EngineType::Rhai,
                        "py" | "python" => EngineType::Python,
                        _ => {
                            return Err(io::Error::other("unsupported test file extension"));
                        }
                    };
                    test_files.insert(lang, file_path.to_string_lossy().to_string());
                }
            }
        }

        self.run_single_test(test_name, &test_files)
    }
}

/// Runs the full cross-engine suite plus the file-based tests under
/// `tests/cases/{arithmetic,conditionals,functions,loops,strings}`.
///
/// Every section asserts: shared-syntax vectors run on both engines,
/// language-specific vectors run on their own engine, and each file
/// fixture is compared against its `<stem>.expected` sidecar. Any
/// mismatch fails this test — red means red.
#[test]
fn test_complete_file_based_suite() {
    let mut runner = TestRunner::new();
    assert!(
        runner.run_all_tests().expect("test suite should run"),
        "not all engine tests passed"
    );
}

#[cfg(test)]
mod function_bundle_tests {
    use postscriptum::{FunctionBundle, ScriptEngine, python::PythonEngine, rhai::RhaiEngine};

    // Test suite specifically for FunctionBundle functionality
    struct FunctionBundleTestSuite;

    impl FunctionBundleTestSuite {
        fn new() -> Self {
            FunctionBundleTestSuite
        }

        // Test adding functions to Python bundle
        fn test_python_function_bundle(&mut self) -> bool {
            // Create a new Python engine with a bundle
            let mut python_bundle = FunctionBundle::new_python();

            // Add a nullary function (no arguments)
            python_bundle.add_python_fn0::<fn() -> f64, f64>("get_pi", || std::f64::consts::PI);

            // Add a unary function (1 argument)
            python_bundle.add_python_fn1::<fn(i64) -> i64, i64, i64>("add_one", |x: i64| x + 1);

            // Add a binary function (2 arguments)
            python_bundle
                .add_python_fn2::<fn(i64, i64) -> i64, i64, i64, i64>("add", |a: i64, b: i64| {
                    a + b
                });

            // Create a new Python engine with the bundle
            let mut engine = match PythonEngine::with_bundle(&python_bundle) {
                Ok(engine) => engine,
                Err(_) => {
                    println!("✗ FAIL: Could not create Python engine with bundle");
                    return false;
                }
            };

            // Test the registered functions
            let result1 = engine.eval("get_pi()");
            match result1 {
                Ok(val) => {
                    println!("raw value returned from Python: {val}");
                    let pi_val = val.trim().parse::<f64>().unwrap_or(0.0);
                    if (pi_val - std::f64::consts::PI).abs() < 0.0001 {
                        println!("✓ PASS: Python get_pi() returned correct value");
                    } else {
                        println!("✗ FAIL: Python get_pi() returned {}, expected PI", val);
                        return false;
                    }
                }
                Err(e) => {
                    println!("✗ FAIL: Python get_pi() evaluation failed: {}", e);
                    return false;
                }
            }

            let result2 = engine.eval("add_one(5)");
            match result2 {
                Ok(val) => {
                    if val.trim() == "6" {
                        println!("✓ PASS: Python add_one(5) returned correct value");
                    } else {
                        println!("✗ FAIL: Python add_one(5) returned {}, expected 6", val);
                        return false;
                    }
                }
                Err(e) => {
                    println!("✗ FAIL: Python add_one(5) evaluation failed: {}", e);
                    return false;
                }
            }

            let result3 = engine.eval("add(3, 4)");
            match result3 {
                Ok(val) => {
                    if val.trim() == "7" {
                        println!("✓ PASS: Python add(3, 4) returned correct value");
                    } else {
                        println!("✗ FAIL: Python add(3, 4) returned {}, expected 7", val);
                        return false;
                    }
                }
                Err(e) => {
                    println!("✗ FAIL: Python add(3, 4) evaluation failed: {}", e);
                    return false;
                }
            }

            true
        }

        // Test adding functions to Rhai bundle
        fn test_rhai_function_bundle(&mut self) -> bool {
            // Create a new Rhai engine with a bundle
            let mut rhai_bundle = FunctionBundle::new_rhai();

            // Add a nullary function (no arguments)
            rhai_bundle.add_rhai_fn0::<fn() -> f64, f64>("get_e", || std::f64::consts::E);

            // Add a unary function (1 argument)
            rhai_bundle.add_rhai_fn1::<fn(i64) -> i64, i64, i64>("double", |x: i64| x * 2);

            // Add a binary function (2 arguments)
            rhai_bundle.add_rhai_fn2::<fn(i64, i64) -> i64, i64, i64, i64>(
                "multiply",
                |a: i64, b: i64| a * b,
            );

            // Create a new Rhai engine with the bundle
            let mut engine = RhaiEngine::with_bundle(&rhai_bundle);

            // Test the registered functions
            let result1 = engine.eval("get_e()");
            match result1 {
                Ok(val) => {
                    let e_val = val.trim().parse::<f64>().unwrap_or(0.0);
                    if (e_val - std::f64::consts::E).abs() < 0.0001 {
                        println!("✓ PASS: Rhai get_e() returned correct value");
                    } else {
                        println!("✗ FAIL: Rhai get_e() returned {}, expected E", val);
                        return false;
                    }
                }
                Err(e) => {
                    println!("✗ FAIL: Rhai get_e() evaluation failed: {}", e);
                    return false;
                }
            }

            let result2 = engine.eval("double(7)");
            match result2 {
                Ok(val) => {
                    if val.trim() == "14" {
                        println!("✓ PASS: Rhai double(7) returned correct value");
                    } else {
                        println!("✗ FAIL: Rhai double(7) returned {}, expected 14", val);
                        return false;
                    }
                }
                Err(e) => {
                    println!("✗ FAIL: Rhai double(7) evaluation failed: {}", e);
                    return false;
                }
            }

            let result3 = engine.eval("multiply(3, 5)");
            match result3 {
                Ok(val) => {
                    if val.trim() == "15" {
                        println!("✓ PASS: Rhai multiply(3, 5) returned correct value");
                    } else {
                        println!("✗ FAIL: Rhai multiply(3, 5) returned {}, expected 15", val);
                        return false;
                    }
                }
                Err(e) => {
                    println!("✗ FAIL: Rhai multiply(3, 5) evaluation failed: {}", e);
                    return false;
                }
            }

            true
        }

        // Run all function bundle tests
        fn run_tests(&mut self) -> bool {
            println!("\nRunning Function Bundle Tests...");

            let mut all_passed = true;
            let mut total = 0;
            let mut passed = 0;

            // Python function bundle test
            total += 1;
            if self.test_python_function_bundle() {
                passed += 1;
            } else {
                all_passed = false;
            }

            // Rhai function bundle test
            total += 1;
            if self.test_rhai_function_bundle() {
                passed += 1;
            } else {
                all_passed = false;
            }

            println!("\nFunction Bundle Tests: {}/{} passed", passed, total);
            println!(
                "Success rate: {:.1}%",
                (passed as f64 / total as f64) * 100.0
            );

            all_passed
        }
    }

    #[test]
    fn test_function_bundles_comprehensive() {
        let mut suite = FunctionBundleTestSuite::new();
        assert!(suite.run_tests(), "Not all function bundle tests passed");
    }

    #[test]
    fn test_simple_python_functions() {
        // Create a new Python engine with a bundle
        let mut python_bundle = FunctionBundle::new_python();
        python_bundle.add_python_fn0::<fn() -> i32, i32>("get_number", || 42);
        python_bundle.add_python_fn1::<fn(i64) -> i64, i64, i64>("square", |x: i64| x * x);
        python_bundle.add_python_fn2::<fn(f64, f64) -> f64, f64, f64, f64>(
            "power",
            |base: f64, exp: f64| base.powf(exp),
        );

        let mut engine = PythonEngine::with_bundle(&python_bundle).unwrap();

        // Test the functions
        match engine.eval("get_number()") {
            Ok(result) => assert_eq!(result.trim(), "42"),
            Err(e) => panic!("Failed to evaluate get_number(): {}", e),
        }

        match engine.eval("square(5)") {
            Ok(result) => assert_eq!(result.trim(), "25"),
            Err(e) => panic!("Failed to evaluate square(5): {}", e),
        }

        match engine.eval("power(2.0, 3.0)") {
            Ok(result) => {
                let power_result = result.trim().parse::<f64>().unwrap_or(0.0);
                assert!((power_result - 8.0).abs() < 0.0001);
            }
            Err(e) => panic!("Failed to evaluate power(2.0, 3.0): {}", e),
        }
    }

    #[test]
    fn test_simple_rhai_functions() {
        // Create a new Rhai engine with a bundle
        let mut rhai_bundle = FunctionBundle::new_rhai();
        rhai_bundle.add_rhai_fn0::<fn() -> i64, i64>("get_answer", || 42);
        rhai_bundle.add_rhai_fn1::<fn(i64) -> i64, i64, i64>("increment", |x: i64| x + 1);
        rhai_bundle
            .add_rhai_fn2::<fn(i64, i64) -> i64, i64, i64, i64>("modulo", |a: i64, b: i64| a % b);

        let mut engine = RhaiEngine::with_bundle(&rhai_bundle);

        // Test the functions
        assert_eq!(engine.eval("get_answer()").unwrap().trim(), "42");
        assert_eq!(engine.eval("increment(99)").unwrap().trim(), "100");
        assert_eq!(engine.eval("modulo(10, 3)").unwrap().trim(), "1");
    }
}

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

    #[test]
    fn test_runner_basic_functionality() {
        let runner = TestRunner::new();
        // Just test that the runner can be created without issues
        assert!(runner.engines.contains_key(&EngineType::Rhai));
        assert!(runner.engines.contains_key(&EngineType::Python));
    }

    #[test]
    fn test_run_arithmetic_tests() {
        let runner = TestRunner::new();
        // Just verify the runner can be created
        assert!(runner.engines.contains_key(&EngineType::Rhai));
        assert!(runner.engines.contains_key(&EngineType::Python));
    }

    #[test]
    fn test_counter_repro() {
        use postscriptum::{FunctionBundle, python::PythonEngine};

        let mut python_bundle = FunctionBundle::new_python();
        python_bundle.add_python_fn0::<fn() -> f64, f64>("get_pi", || std::f64::consts::PI);
        python_bundle.add_python_fn1::<fn(i64) -> i64, i64, i64>("plusone", |x: i64| x + 1);

        let mut python_engine = PythonEngine::with_bundle(&python_bundle).unwrap();
        assert_eq!(
            python_engine.eval("counter = 1\ncounter").unwrap().trim(),
            "1"
        );
        for (i, expected) in ["2", "3", "4", "5", "6", "7"].iter().enumerate() {
            let got = python_engine.eval("counter += 1\ncounter").unwrap();
            assert_eq!(got.trim(), *expected, "incr {i} should be {expected}");
        }
    }

    #[test]
    fn test_context_preservation_rhai() {
        use postscriptum::rhai::RhaiEngine;

        // Test Rhai engine context preservation following the same pattern as the working app
        let mut rhai_engine = RhaiEngine::new();

        // First evaluation - initialize variable with let and return its value
        let result1 = rhai_engine.eval("let a = 5; a").unwrap();
        assert_eq!(result1, "5");

        // Second evaluation - variable should persist and be updated
        let result2 = rhai_engine.eval("a = a + 1; a").unwrap();
        assert_eq!(result2, "6");

        // Third evaluation - variable should continue to persist
        let result3 = rhai_engine.eval("a * 2").unwrap();
        assert_eq!(result3, "12");
    }

    #[test]
    fn test_context_preservation_python() {
        use postscriptum::python::PythonEngine;

        // Test Python engine context preservation
        let mut python_engine = PythonEngine::new();

        // First evaluation - initialize variable and return its value
        let result1 = python_engine.eval("a = 5\na").unwrap();
        assert_eq!(result1, "5");

        // Second evaluation - variable should persist and be updated
        let result2 = python_engine.eval("a = a + 1\na").unwrap();
        assert_eq!(result2, "6");

        // Third evaluation - variable should continue to persist
        let result3 = python_engine.eval("a * 2").unwrap();
        assert_eq!(result3, "12");
    }

    /// Verifies that the Python engine uses a single namespace for globals and
    /// locals, so execution behaves like module-level (REPL) scope.
    ///
    /// This is the regression suite for the bug where separate globals/locals
    /// dicts caused variables to be invisible across evals when accessed from
    /// inside function bodies.
    #[test]
    fn test_python_globals_identity() {
        use postscriptum::python::PythonEngine;

        let mut engine = PythonEngine::new();

        // globals() and locals() must be the same object at module scope.
        let result = engine.eval("globals() is locals()").unwrap();
        assert_eq!(
            result.trim(),
            "True",
            "globals() and locals() should be identical"
        );
    }

    #[test]
    fn test_python_variable_visible_in_later_function() {
        use postscriptum::python::PythonEngine;

        let mut engine = PythonEngine::new();

        // Eval 1: define a variable.
        let r1 = engine.eval("x = 42\nx").unwrap();
        assert_eq!(r1.trim(), "42");

        // Eval 2: define a function that closes over x.
        let r2 = engine.eval("def get_x():\n    return x\n").unwrap();
        assert_eq!(r2.trim(), "Executed successfully");

        // Eval 3: call the function — it must see x from eval 1.
        let r3 = engine.eval("get_x()").unwrap();
        assert_eq!(
            r3.trim(),
            "42",
            "function defined in a later eval must see variables from prior evals"
        );
    }

    #[test]
    fn test_python_function_modifies_global_variable() {
        use postscriptum::python::PythonEngine;

        let mut engine = PythonEngine::new();

        // Initialize a counter.
        engine.eval("counter = 0\ncounter").unwrap();

        // Define a function that mutates the global.
        engine
            .eval("def bump():\n    global counter\n    counter += 1\n    return counter\n")
            .unwrap();

        // Call it repeatedly — each call must see the updated value.
        for expected in 1..=5 {
            let r = engine.eval("bump()").unwrap();
            assert_eq!(r.trim(), expected.to_string(), "bump() call #{expected}");
        }
    }

    #[test]
    fn test_python_globals_dict_persists_across_evals() {
        use postscriptum::python::PythonEngine;

        let mut engine = PythonEngine::new();

        // Store a value via globals().
        engine.eval("globals()['g'] = 99").unwrap();

        // Retrieve it in a later eval via globals().
        let r = engine.eval("globals()['g']").unwrap();
        assert_eq!(r.trim(), "99", "value stored in globals() must persist");
    }

    #[test]
    fn test_python_class_sees_module_variables() {
        use postscriptum::python::PythonEngine;

        let mut engine = PythonEngine::new();

        // Define a module-level constant.
        engine.eval("MAX_SIZE = 100").unwrap();

        // Define a class that references it.
        engine
            .eval("class Container:\n    def capacity(self):\n        return MAX_SIZE\n")
            .unwrap();

        // Instantiate and call — the class body's __globals__ must contain MAX_SIZE.
        let r = engine.eval("Container().capacity()").unwrap();
        assert_eq!(
            r.trim(),
            "100",
            "class method must see module-level variables"
        );
    }

    #[test]
    fn test_python_nested_function_scope_chain() {
        use postscriptum::python::PythonEngine;

        let mut engine = PythonEngine::new();

        // Outer variable.
        engine.eval("outer = 'hello'").unwrap();

        // Nested function definitions across evals.
        engine
            .eval("def make_closure():\n    def inner():\n        return outer\n    return inner\n")
            .unwrap();

        // Call the closure — inner() must resolve `outer` via the scope chain.
        let r = engine.eval("make_closure()()").unwrap();
        assert_eq!(
            r.trim(),
            "hello",
            "nested closure must resolve enclosing module variable"
        );
    }
}