kelora 0.3.0

A command-line log analysis tool with embedded Rhai scripting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
#![allow(dead_code)]
use anyhow::{Context, Result};
use rhai::{Dynamic, Engine, EvalAltResult, Scope, AST};
use std::collections::HashMap;

use rhai::debugger::{DebuggerCommand, DebuggerEvent};

use crate::event::Event;
use crate::rhai_functions;

use rhai::Map;

// Temporary debug types until module structure is fixed
#[derive(Debug, Clone)]
pub struct DebugConfig {
    pub verbosity: u8,
    pub show_timing: bool,
    pub trace_events: bool,
    pub use_emoji: bool,
}

impl DebugConfig {
    pub fn new(verbose_count: u8) -> Self {
        DebugConfig {
            verbosity: verbose_count,
            show_timing: verbose_count >= 1,
            trace_events: verbose_count >= 2,
            use_emoji: true, // Default to true, will be overridden
        }
    }

    pub fn with_emoji(mut self, use_emoji: bool) -> Self {
        self.use_emoji = use_emoji;
        self
    }

    pub fn is_enabled(&self) -> bool {
        self.verbosity > 0
    }
}

#[derive(Debug, Clone, Default)]
pub struct ExecutionContext {
    pub position: Option<rhai::Position>,
    pub source_snippet: Option<String>,
    pub last_operation: Option<String>,
    pub error_location: Option<String>,
}

use std::sync::{Arc, Mutex};
pub struct DebugTracker {
    pub config: DebugConfig,
    context: Arc<Mutex<ExecutionContext>>,
    event_count: Arc<Mutex<u64>>,
    error_count: Arc<Mutex<u64>>,
}

impl DebugTracker {
    pub fn new(config: DebugConfig) -> Self {
        DebugTracker {
            config,
            context: Arc::new(Mutex::new(ExecutionContext::default())),
            event_count: Arc::new(Mutex::new(0)),
            error_count: Arc::new(Mutex::new(0)),
        }
    }

    pub fn log_basic(&self, message: &str) {
        if self.config.is_enabled() && self.config.verbosity >= 1 {
            eprintln!("{}", message);
        }
    }

    pub fn log_detailed(&self, stage: &str, event_num: u64, operation: &str) {
        if self.config.is_enabled() && self.config.verbosity >= 2 {
            eprintln!("Trace: Event #{} {} → {}", event_num, stage, operation);
        }
    }

    pub fn log_step(&self, step_info: &str, result: &str) {
        if self.config.is_enabled() && self.config.verbosity >= 3 {
            eprintln!("  → {} → {}", step_info, result);
        }
    }

    pub fn log_execution_start(&self, stage: &str, script: &str, event_data: &str) {
        match self.config.verbosity {
            1 => {
                if self.config.is_enabled() {
                    let prefix = if self.config.use_emoji {
                        "🔹"
                    } else {
                        "kelora: "
                    };
                    eprintln!("{} Executing {} stage", prefix, stage);
                }
            }
            2 => {
                if self.config.is_enabled() {
                    eprintln!("{} execution started", stage);
                    eprintln!("  Script: {}", self.truncate_for_display(script, 100));
                }
            }
            3.. => {
                if self.config.is_enabled() {
                    eprintln!("{} execution trace:", stage);
                    eprintln!("  Script: {}", script.trim());
                    eprintln!("  Event: {}", self.truncate_for_display(event_data, 150));
                }
            }
            _ => {}
        }
    }

    pub fn log_execution_result(&self, stage: &str, success: bool, result_info: &str) {
        if self.config.is_enabled() && self.config.verbosity >= 2 {
            let status = if success { "✓" } else { "✗" };
            eprintln!("{} {} ({})", stage, status, result_info);
        }
    }

    fn truncate_for_display(&self, text: &str, max_len: usize) -> String {
        if text.len() > max_len {
            format!("{}...", &text[..max_len - 3])
        } else {
            text.to_string()
        }
    }

    pub fn update_context(&self, position: Option<rhai::Position>, source: Option<&str>) {
        if self.config.is_enabled() {
            if let Ok(mut ctx) = self.context.lock() {
                ctx.position = position;
                ctx.source_snippet = source.map(|s| s.to_string());
            }
        }
    }

    pub fn get_context(&self) -> ExecutionContext {
        if let Ok(ctx) = self.context.lock() {
            ctx.clone()
        } else {
            ExecutionContext::default()
        }
    }
}

impl Clone for DebugTracker {
    fn clone(&self) -> Self {
        DebugTracker {
            config: self.config.clone(),
            context: Arc::clone(&self.context),
            event_count: Arc::clone(&self.event_count),
            error_count: Arc::clone(&self.error_count),
        }
    }
}

pub struct ErrorEnhancer {
    debug_config: DebugConfig,
}

impl ErrorEnhancer {
    pub fn new(debug_config: DebugConfig) -> Self {
        ErrorEnhancer { debug_config }
    }

    pub fn enhance_error(
        &self,
        error: &EvalAltResult,
        scope: &Scope,
        script: &str,
        stage: &str,
        execution_context: &ExecutionContext,
    ) -> String {
        let mut output = String::new();

        // Basic error info
        output.push_str(&format!("🔸Stage {} failed\n", stage));
        output.push_str(&format!("  Code: {}\n", script.trim()));
        output.push_str(&format!("  Error: {}\n", error));

        // Add execution context if available
        if let Some(pos) = &execution_context.position {
            output.push_str(&format!("   Position: {}\n", pos));
        }

        // Show scope information if debug enabled
        if self.debug_config.is_enabled() {
            output.push_str("\n   Variables in scope:\n");
            for (name, _is_const, value) in scope.iter() {
                let preview = format!("{:?}", value);
                let preview = if preview.len() > 50 {
                    format!("{}...", &preview[..47])
                } else {
                    preview
                };
                output.push_str(&format!(
                    "   • {}: {} = {}\n",
                    name,
                    value.type_name(),
                    preview
                ));
            }

            // Add suggestions based on error type
            if let Some(suggestions) = self.generate_suggestions(error, scope) {
                output.push_str(&format!("\n   💡 {}\n", suggestions));
            }

            // Add stage-specific help
            output.push_str(&self.get_stage_help(stage, error));
        }

        output
    }

    fn generate_suggestions(&self, error: &EvalAltResult, scope: &Scope) -> Option<String> {
        match error {
            EvalAltResult::ErrorVariableNotFound(var_name, _) => {
                let similar = self.find_similar_variables(var_name, scope);
                if !similar.is_empty() {
                    Some(format!("Did you mean: {}?", similar.join(", ")))
                } else {
                    // Check for common patterns
                    if var_name.contains('.') {
                        Some("Check if the field exists and use safe access like 'if \"field\" in e { e.field } else { \"default\" }'".to_string())
                    } else if var_name.starts_with("e.") {
                        Some("Try using bracket notation for special characters: e[\"field-name\"] or e[\"field.with.dots\"]".to_string())
                    } else {
                        Some("Available variables: e (event), meta (metadata), conf (initialization data), line (raw line)".to_string())
                    }
                }
            },
            EvalAltResult::ErrorPropertyNotFound(prop_name, _) => {
                Some(format!("Property '{}' not found. Use 'if \"{}\" in e {{ ... }}' to check existence first", prop_name, prop_name))
            },
            EvalAltResult::ErrorIndexNotFound(index, _) => {
                Some(format!("Index '{}' not found. Check array bounds with 'if e.array.len() > {} {{ ... }}'", index, index))
            },
            EvalAltResult::ErrorFunctionNotFound(func_sig, _) => {
                self.suggest_function_alternatives(func_sig)
            },
            EvalAltResult::ErrorMismatchDataType(expected, actual, _) => {
                Some(format!("Type mismatch: expected {}, got {}. Use type_of() to check types or to_string(), to_number() for conversion", expected, actual))
            },
            _ => None
        }
    }

    fn suggest_function_alternatives(&self, func_sig: &str) -> Option<String> {
        let func_name = func_sig.split('(').next().unwrap_or(func_sig).trim();

        // Common function alternatives
        match func_name {
            "length" => Some("Use 'len()' instead of 'length()'".to_string()),
            "size" => Some("Use 'len()' instead of 'size()'".to_string()),
            "substr" | "substring" => Some(
                "Use string slicing: s[start..end] or extract_re() for pattern matching"
                    .to_string(),
            ),
            "indexOf" | "index_of" => Some(
                "Use 'contains()' to check existence or 'split()' to find positions".to_string(),
            ),
            "push_back" | "append" => Some("Use 'push()' to add elements to arrays".to_string()),
            "to_int" | "parseInt" => {
                Some("Use 'parse()' or to_number() for type conversion".to_string())
            }
            "to_str" | "toString" => Some("Use 'to_string()' for string conversion".to_string()),
            "match" => Some(
                "Use 'extract_re()' for regex matching or 'contains()' for simple checks"
                    .to_string(),
            ),
            name if name.ends_with("_re") => Some(
                "Regex functions: extract_re(), extract_all_re(), split_re(), replace_re()"
                    .to_string(),
            ),
            _ => None,
        }
    }

    fn find_similar_variables(&self, target: &str, scope: &Scope) -> Vec<String> {
        let mut suggestions = Vec::new();
        let target_lower = target.to_lowercase();

        for (name, _is_const, _value) in scope.iter() {
            let name_lower = name.to_lowercase();
            let similarity = self.calculate_similarity(&target_lower, &name_lower);

            // Include variables with good similarity or common patterns
            if similarity > 0.6
                || name_lower.contains(&target_lower)
                || target_lower.contains(&name_lower)
                || self.has_common_prefix(&target_lower, &name_lower)
            {
                suggestions.push(name.to_string());
            }
        }

        // Sort by similarity (best matches first)
        suggestions.sort_by(|a, b| {
            let sim_a = self.calculate_similarity(&target_lower, &a.to_lowercase());
            let sim_b = self.calculate_similarity(&target_lower, &b.to_lowercase());
            sim_b
                .partial_cmp(&sim_a)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Return top 3 suggestions
        suggestions.truncate(3);
        suggestions
    }

    fn calculate_similarity(&self, s1: &str, s2: &str) -> f64 {
        if s1 == s2 {
            return 1.0;
        }
        if s1.is_empty() || s2.is_empty() {
            return 0.0;
        }

        // Simple Levenshtein-based similarity
        let len1 = s1.len();
        let len2 = s2.len();
        let max_len = len1.max(len2);

        let distance = self.levenshtein_distance(s1, s2);
        1.0 - (distance as f64 / max_len as f64)
    }

    fn levenshtein_distance(&self, s1: &str, s2: &str) -> usize {
        let chars1: Vec<char> = s1.chars().collect();
        let chars2: Vec<char> = s2.chars().collect();
        let len1 = chars1.len();
        let len2 = chars2.len();

        if len1 == 0 {
            return len2;
        }
        if len2 == 0 {
            return len1;
        }

        let mut prev_row: Vec<usize> = (0..=len2).collect();

        for i in 1..=len1 {
            let mut curr_row = vec![i];

            for j in 1..=len2 {
                let cost = if chars1[i - 1] == chars2[j - 1] { 0 } else { 1 };
                curr_row.push(
                    (curr_row[j - 1] + 1) // insertion
                        .min(prev_row[j] + 1) // deletion
                        .min(prev_row[j - 1] + cost), // substitution
                );
            }

            prev_row = curr_row;
        }

        prev_row[len2]
    }

    fn has_common_prefix(&self, s1: &str, s2: &str) -> bool {
        if s1.len() < 2 || s2.len() < 2 {
            return false;
        }
        let prefix_len = 2.min(s1.len()).min(s2.len());
        s1[..prefix_len] == s2[..prefix_len]
    }

    fn get_stage_help(&self, stage: &str, error: &EvalAltResult) -> String {
        let mut help = String::new();

        match stage {
            "filter" => {
                help.push_str("\n   🔹 Filter stage tips:\n");
                help.push_str("   • Filters must return true/false (boolean values)\n");
                help.push_str("   • Use 'e.field_name' to access event fields\n");
                help.push_str(
                    "   • Use 'e[\"field-with-special-chars\"]' for complex field names\n",
                );
                help.push_str("   • Use 'if \"field\" in e { ... }' to check field existence\n");

                if let EvalAltResult::ErrorMismatchDataType(_, _, _) = error {
                    help.push_str(
                        "   • Remember: filters need boolean results, not strings or numbers\n",
                    );
                }
            }
            "exec" => {
                help.push_str("\n   🔹 Exec stage tips:\n");
                help.push_str("   • Use 'e.new_field = value' to add fields to events\n");
                help.push_str("   • Use 'e.field = ()' to remove fields from events\n");
                help.push_str("   • Use 'e = ()' to remove entire event (filter out)\n");
                help.push_str("   • Use 'let variable = value' for temporary variables\n");
                help.push_str("   • Use 'print(\"debug: \" + value)' for debugging output\n");
            }
            "begin" => {
                help.push_str("\n   🔹 Begin stage tips:\n");
                help.push_str("   • Use 'conf.field = value' to set global initialization data\n");
                help.push_str("   • Use 'read_file(\"path\")' to load external data\n");
                help.push_str("   • Variables set here are available in all event processing\n");
            }
            "end" => {
                help.push_str("\n   🔹 End stage tips:\n");
                help.push_str("   • Use 'metrics.key' to access accumulated tracking data\n");
                help.push_str("   • Use 'print()' to output final results\n");
                help.push_str("   • This runs after all events are processed\n");
            }
            _ => {}
        }

        help
    }
}

// Execution Tracer for step-by-step debugging
pub struct ExecutionTracer {
    config: DebugConfig,
    current_event: Arc<Mutex<u64>>,
    step_counter: Arc<Mutex<u32>>,
}

impl ExecutionTracer {
    pub fn new(config: DebugConfig) -> Self {
        ExecutionTracer {
            config,
            current_event: Arc::new(Mutex::new(0)),
            step_counter: Arc::new(Mutex::new(0)),
        }
    }

    pub fn trace_stage_execution(&self, stage_number: usize, stage_type: &str) {
        if self.config.verbosity >= 1 {
            let prefix = if self.config.use_emoji {
                "🔹"
            } else {
                "kelora: "
            };
            eprintln!(
                "{}Executing stage {} ({})",
                prefix, stage_number, stage_type
            );
        }
    }

    pub fn trace_step(&self, _event_num: u64, step_info: &str, result: &str) {
        if self.config.verbosity >= 2 {
            eprintln!("  → {} → {}", step_info, result);
        }
    }

    pub fn trace_event_start(&self, event_num: u64, event_data: &str) {
        if self.config.verbosity >= 2 {
            eprintln!("  Filter execution trace for event {}:", event_num);
            eprintln!("    Event: {}", self.truncate_for_display(event_data, 100));
        }
    }

    pub fn trace_event_result(&self, result: bool, action: &str) {
        if self.config.verbosity >= 2 {
            eprintln!("    Result: {} ({})", result, action);
        }
    }

    pub fn trace_expression_evaluation(&self, expression: &str, intermediate_result: &str) {
        if self.config.verbosity >= 3 {
            eprintln!("    Eval: {} → {}", expression, intermediate_result);
        }
    }

    pub fn trace_variable_access(&self, var_name: &str, value: &str) {
        if self.config.verbosity >= 3 {
            eprintln!(
                "    Access: {} = {}",
                var_name,
                self.truncate_for_display(value, 30)
            );
        }
    }

    pub fn trace_function_call(&self, func_name: &str, args: &str, result: &str) {
        if self.config.verbosity >= 3 {
            eprintln!(
                "    Call: {}({}) → {}",
                func_name,
                args,
                self.truncate_for_display(result, 30)
            );
        }
    }

    // Enhanced detailed tracing for -vvv level
    pub fn trace_detailed_step(
        &self,
        context: &str,
        operation: &str,
        input: &str,
        output: &str,
        step_type: &str,
    ) {
        if self.config.verbosity >= 3 {
            let step_num = {
                match self.step_counter.lock() {
                    Ok(mut counter) => {
                        *counter += 1;
                        *counter
                    }
                    Err(_) => {
                        // If mutex is poisoned, continue with a default value
                        eprintln!("Warning: Step counter mutex poisoned, using default");
                        0
                    }
                }
            };

            eprintln!(
                "    [Step {}:{}] {}: {} → {}",
                step_num,
                context,
                operation,
                self.truncate_for_display(input, 30),
                self.truncate_for_display(output, 30)
            );

            if step_type != "default" {
                eprintln!("      Type: {}", step_type);
            }
        }
    }

    pub fn trace_scope_inspection(&self, scope: &rhai::Scope) {
        if self.config.verbosity >= 3 {
            eprintln!("    Scope contents:");
            let mut scope_items: Vec<_> = scope.iter().collect();
            scope_items.sort_by(|a, b| a.0.cmp(b.0));
            for (name, _is_const, value) in scope_items {
                let type_info = value.type_name();
                let preview = format!("{:?}", value);
                eprintln!("      {} ({}): {}", name, type_info, preview);
            }
        }
    }

    pub fn trace_ast_node(&self, node_type: &str, position: &str, source: &str) {
        if self.config.verbosity >= 3 {
            eprintln!(
                "    AST: {} at {} → \"{}\"",
                node_type,
                position,
                self.truncate_for_display(source, 40)
            );
        }
    }

    fn truncate_for_display(&self, text: &str, max_len: usize) -> String {
        if text.len() > max_len {
            format!("{}...", &text[..max_len - 3])
        } else {
            text.to_string()
        }
    }

    pub fn next_event(&self) -> u64 {
        if let Ok(mut counter) = self.current_event.lock() {
            *counter += 1;
            *counter
        } else {
            0
        }
    }

    pub fn reset_step_counter(&self) {
        if let Ok(mut counter) = self.step_counter.lock() {
            *counter = 0;
        }
    }
}

impl Clone for ExecutionTracer {
    fn clone(&self) -> Self {
        ExecutionTracer {
            config: self.config.clone(),
            current_event: Arc::clone(&self.current_event),
            step_counter: Arc::clone(&self.step_counter),
        }
    }
}

// Performance and Statistics Tracking using thread-local storage
// This integrates with kelora's parallel processing infrastructure like track_count()

use std::cell::RefCell;

#[derive(Debug, Clone, Default)]
pub struct DebugStatistics {
    pub start_time: Option<std::time::Instant>,
    pub events_processed: u64,
    pub events_passed: u64,
    pub errors_encountered: u64,
    pub script_executions: u64,
}

impl DebugStatistics {
    pub fn new() -> Self {
        DebugStatistics {
            start_time: Some(std::time::Instant::now()),
            events_processed: 0,
            events_passed: 0,
            errors_encountered: 0,
            script_executions: 0,
        }
    }
}

// Thread-local storage for debug statistics (following track_count pattern)
thread_local! {
    static THREAD_DEBUG_STATS: RefCell<DebugStatistics> = RefCell::new(DebugStatistics::new());
}

// Debug statistics collection functions (following stats.rs pattern)
pub fn debug_stats_increment_events_processed() {
    THREAD_DEBUG_STATS.with(|stats| {
        stats.borrow_mut().events_processed += 1;
    });
}

pub fn debug_stats_increment_events_passed() {
    THREAD_DEBUG_STATS.with(|stats| {
        stats.borrow_mut().events_passed += 1;
    });
}

pub fn debug_stats_increment_errors() {
    THREAD_DEBUG_STATS.with(|stats| {
        stats.borrow_mut().errors_encountered += 1;
    });
}

pub fn debug_stats_increment_script_executions() {
    THREAD_DEBUG_STATS.with(|stats| {
        stats.borrow_mut().script_executions += 1;
    });
}

pub fn debug_stats_get_thread_state() -> DebugStatistics {
    THREAD_DEBUG_STATS.with(|stats| stats.borrow().clone())
}

pub fn debug_stats_set_thread_state(stats: &DebugStatistics) {
    THREAD_DEBUG_STATS.with(|local_stats| {
        *local_stats.borrow_mut() = stats.clone();
    });
}

#[derive(Clone)]
pub struct CompiledExpression {
    ast: AST,
    expr: String,
}

pub struct RhaiEngine {
    engine: Engine,
    compiled_filters: Vec<CompiledExpression>,
    compiled_execs: Vec<CompiledExpression>,
    compiled_begin: Option<CompiledExpression>,
    compiled_end: Option<CompiledExpression>,
    scope_template: Scope<'static>,
    suppress_side_effects: bool,
    conf_map: Option<rhai::Map>,
    debug_tracker: Option<DebugTracker>,
    execution_tracer: Option<ExecutionTracer>,
}

impl Clone for RhaiEngine {
    fn clone(&self) -> Self {
        let mut engine = Engine::new();
        engine.set_optimization_level(rhai::OptimizationLevel::Simple);

        // Apply the same on_print override as in new(), respecting suppress_side_effects
        let suppress_side_effects = self.suppress_side_effects;
        engine.on_print(move |text| {
            if suppress_side_effects {
                // Suppress all print output
                return;
            }

            if crate::rhai_functions::strings::is_parallel_mode() {
                crate::rhai_functions::strings::capture_print(text.to_string());
            } else {
                println!("{}", text);
            }
        });

        rhai_functions::register_all_functions(&mut engine);

        Self {
            engine,
            compiled_filters: self.compiled_filters.clone(),
            compiled_execs: self.compiled_execs.clone(),
            compiled_begin: self.compiled_begin.clone(),
            compiled_end: self.compiled_end.clone(),
            scope_template: self.scope_template.clone(),
            suppress_side_effects,
            conf_map: self.conf_map.clone(),
            debug_tracker: self.debug_tracker.clone(),
            execution_tracer: self.execution_tracer.clone(),
        }
    }
}

impl RhaiEngine {
    // Thread-local state management functions
    pub fn set_thread_tracking_state(metrics: &HashMap<String, Dynamic>) {
        rhai_functions::tracking::set_thread_tracking_state(metrics);
    }

    pub fn get_thread_tracking_state() -> HashMap<String, Dynamic> {
        rhai_functions::tracking::get_thread_tracking_state()
    }

    fn format_rhai_error(err: Box<EvalAltResult>, script_name: &str, _script_text: &str) -> String {
        match *err {
            EvalAltResult::ErrorParsing(parse_err, pos) => {
                format!("Syntax error in {} at {}: {}", script_name, pos, parse_err)
            }
            EvalAltResult::ErrorRuntime(runtime_err, pos) => {
                format!(
                    "Runtime error in {} at {}: {}",
                    script_name, pos, runtime_err
                )
            }
            EvalAltResult::ErrorVariableNotFound(var, pos) => {
                format!("Variable '{}' not found in {} at {}", var, script_name, pos)
            }
            EvalAltResult::ErrorFunctionNotFound(func, pos) => {
                Self::format_function_not_found_error(func, script_name, pos)
            }
            EvalAltResult::ErrorMismatchDataType(expected, actual, pos) => {
                format!("Type mismatch in {} at {}: expected {}, got {} (this often indicates a function was called with incorrect argument types)", 
                        script_name, pos, expected, actual)
            }
            EvalAltResult::ErrorInFunctionCall(func, _source, inner_err, pos) => {
                let inner_msg = Self::format_rhai_error(inner_err, "function", "");
                format!(
                    "Error in function '{}' in {} at {}: {}",
                    func, script_name, pos, inner_msg
                )
            }
            EvalAltResult::ErrorPropertyNotFound(prop, pos) => {
                format!(
                    "Property '{}' not found in {} at {}",
                    prop, script_name, pos
                )
            }
            EvalAltResult::ErrorIndexNotFound(index, pos) => {
                format!("Index '{}' not found in {} at {}", index, script_name, pos)
            }
            EvalAltResult::ErrorDotExpr(msg, pos) => {
                format!(
                    "Property access error in {} at {}: {}",
                    script_name, pos, msg
                )
            }
            EvalAltResult::ErrorArithmetic(msg, pos) => {
                format!("Arithmetic error in {} at {}: {}", script_name, pos, msg)
            }
            EvalAltResult::ErrorTooManyOperations(pos) => {
                format!("Too many operations in {} at {}", script_name, pos)
            }
            EvalAltResult::ErrorStackOverflow(pos) => {
                format!("Stack overflow in {} at {}", script_name, pos)
            }
            EvalAltResult::ErrorDataTooLarge(msg, pos) => {
                format!("Data too large in {} at {}: {}", script_name, pos, msg)
            }
            EvalAltResult::ErrorTerminated(val, pos) => {
                format!("Script terminated in {} at {}: {}", script_name, pos, val)
            }
            _ => format!("Error in {}: {}", script_name, err),
        }
    }

    fn format_function_not_found_error(
        func_signature: String,
        script_name: &str,
        pos: rhai::Position,
    ) -> String {
        // Extract function name from signature (before the first '(' or space)
        let func_name = if let Some(paren_pos) = func_signature.find('(') {
            &func_signature[..paren_pos]
        } else if let Some(space_pos) = func_signature.find(' ') {
            &func_signature[..space_pos]
        } else {
            &func_signature
        }
        .trim();

        // Check if this looks like a type mismatch rather than a missing function
        if Self::is_likely_type_mismatch(&func_signature, func_name) {
            let expected_types = Self::get_expected_function_signature(func_name);
            if !expected_types.is_empty() {
                let called_types = Self::extract_called_types(&func_signature);
                return format!(
                    "Wrong argument types for '{}' in {} at {}: got {}, expected {}. Note: x.{}() = {}(x)",
                    func_name,
                    script_name,
                    pos,
                    called_types,
                    expected_types,
                    func_name,
                    func_name
                );
            }
        }

        // Fall back to "function not found" with suggestions
        let base_msg = format!(
            "Function '{}' not found in {} at {}",
            func_signature, script_name, pos
        );
        let suggestions = Self::get_function_suggestions(func_name);

        if suggestions.is_empty() {
            base_msg
        } else {
            format!("{}. Did you mean: {}", base_msg, suggestions.join(", "))
        }
    }

    fn is_likely_type_mismatch(func_signature: &str, func_name: &str) -> bool {
        // Check if the function name is one we know exists
        let known_functions = vec![
            "extract_re",
            "extract_all_re",
            "split_re",
            "replace_re",
            "count",
            "strip",
            "before",
            "after",
            "between",
            "starting_with",
            "ending_with",
            "is_digit",
            "join",
            "extract_ip",
            "extract_ips",
            "mask_ip",
            "is_private_ip",
            "extract_url",
            "extract_domain",
            "parse_json",
            "parse_kv",
            "col",
            "cols",
            "status_class",
            "track_count",
            "track_sum",
            "track_min",
            "track_max",
            "track_avg",
            "track_unique",
            "track_bucket",
            // Common Rhai built-ins that work on strings
            "len",
            "contains",
            "starts_with",
            "ends_with",
            "split",
            "replace",
            "trim",
        ];

        known_functions.contains(&func_name) && func_signature.contains('(')
    }

    fn extract_called_types(func_signature: &str) -> String {
        if let Some(start) = func_signature.find('(') {
            if let Some(end) = func_signature.find(')') {
                return func_signature[start + 1..end].to_string();
            }
        }
        "unknown types".to_string()
    }

    fn get_expected_function_signature(func_name: &str) -> String {
        match func_name {
            "extract_re" => "string, regex_pattern, optional_group_index".to_string(),
            "extract_all_re" => "string, regex_pattern, optional_group_index".to_string(),
            "split_re" => "string, regex_pattern".to_string(),
            "replace_re" => "string, regex_pattern, replacement".to_string(),
            "before" | "after" => "string, delimiter".to_string(),
            "between" => "string, start_delimiter, end_delimiter".to_string(),
            "starting_with" | "ending_with" => "string, prefix_or_suffix".to_string(),
            "strip" => "string, optional_characters_to_strip".to_string(),
            "join" => "string_separator, array OR array, string_separator".to_string(),
            "extract_ip" | "extract_ips" | "extract_url" | "extract_domain" => "string".to_string(),
            "mask_ip" => "string, optional_octets_to_mask".to_string(),
            "is_private_ip" | "is_digit" => "string".to_string(),
            "parse_json" => "json_string".to_string(),
            "parse_kv" => "string, optional_separator, optional_kv_separator".to_string(),
            "col" => "string, column_selector".to_string(),
            "cols" => "string, column_selectors...".to_string(),
            "status_class" => "status_code_number".to_string(),
            "track_count" | "track_sum" | "track_min" | "track_max" | "track_avg" => {
                "key, optional_value".to_string()
            }
            "track_unique" => "key, value".to_string(),
            "track_bucket" => "key, value, bucket_size".to_string(),
            "count" => "string, substring".to_string(),
            // Common string functions that expect strings
            "len" | "trim" => "string".to_string(),
            "contains" | "starts_with" | "ends_with" => "string, substring".to_string(),
            "split" | "replace" => "string, delimiter_or_pattern, optional_replacement".to_string(),
            _ => "".to_string(),
        }
    }

    fn get_function_suggestions(func_name: &str) -> Vec<String> {
        // List of common Rhai built-in functions and our custom functions
        let available_functions = vec![
            // String functions
            "lower",
            "upper",
            "trim",
            "len",
            "contains",
            "starts_with",
            "ends_with",
            "split",
            "replace",
            "substring",
            "to_string",
            "parse",
            // Our custom string functions
            "extract_re",
            "extract_all_re",
            "split_re",
            "replace_re",
            "count",
            "strip",
            "before",
            "after",
            "between",
            "starting_with",
            "ending_with",
            "is_digit",
            "join",
            "extract_ip",
            "extract_ips",
            "mask_ip",
            "is_private_ip",
            "extract_url",
            "extract_domain",
            // Math functions
            "abs",
            "floor",
            "ceil",
            "round",
            "min",
            "max",
            "pow",
            "sqrt",
            // Array functions
            "push",
            "pop",
            "shift",
            "unshift",
            "reverse",
            "sort",
            "clear",
            // Map functions
            "keys",
            "values",
            "remove",
            "contains",
            // Our custom functions
            "parse_json",
            "parse_kv",
            "col",
            "cols",
            "status_class",
            "track_count",
            "track_sum",
            "track_min",
            "track_max",
            "track_avg",
            "track_unique",
            "track_bucket",
            // Utility functions
            "print",
            "debug",
            "type_of",
            "is_def_fn",
        ];

        // Find functions that are similar to the requested one
        let suggestions: Vec<String> = available_functions
            .iter()
            .filter(|&f| {
                // Check for starts with or contains
                f.starts_with(func_name) || (func_name.len() > 1 && f.contains(func_name))
            })
            .take(3) // Limit to 3 suggestions
            .map(|s| s.to_string())
            .collect();

        // For debugging: always include at least one suggestion if the function name contains common patterns
        if suggestions.is_empty() && func_name.len() > 2 {
            if func_name.contains("extract") {
                return vec![
                    "extract_re".to_string(),
                    "extract_ip".to_string(),
                    "extract_url".to_string(),
                ];
            } else if func_name.contains("track") {
                return vec![
                    "track_count".to_string(),
                    "track_sum".to_string(),
                    "track_unique".to_string(),
                ];
            } else if func_name.contains("pars") {
                return vec!["parse_json".to_string(), "parse_kv".to_string()];
            }
        }

        suggestions
    }

    pub fn new() -> Self {
        let mut engine = Engine::new();

        engine.set_optimization_level(rhai::OptimizationLevel::Simple);

        // Override the built-in print function to support capture in parallel mode
        // Note: suppress_side_effects is false by default in new()
        engine.on_print(|text| {
            if crate::rhai_functions::strings::is_parallel_mode() {
                // Use both old capture system (for compatibility) and new ordered system
                crate::rhai_functions::strings::capture_print(text.to_string());
                crate::rhai_functions::strings::capture_stdout(text.to_string());
            } else {
                println!("{}", text);
            }
        });

        // Register custom functions for log analysis (includes eprint() for stderr output)
        rhai_functions::register_all_functions(&mut engine);

        // Register variable access callback for tracking functions
        Self::register_variable_resolver(&mut engine);

        let mut scope_template = Scope::new();
        scope_template.push("line", "");
        scope_template.push("e", rhai::Map::new());
        scope_template.push("meta", rhai::Map::new());
        scope_template.push("conf", rhai::Map::new());

        Self {
            engine,
            compiled_filters: Vec::new(),
            compiled_execs: Vec::new(),
            compiled_begin: None,
            compiled_end: None,
            scope_template,
            suppress_side_effects: false,
            conf_map: None,
            debug_tracker: None,
            execution_tracer: None,
        }
    }

    pub fn get_execution_tracer(&self) -> &Option<ExecutionTracer> {
        &self.execution_tracer
    }

    /// Set up debugging with the provided configuration
    pub fn setup_debugging(&mut self, debug_config: DebugConfig) {
        if !debug_config.is_enabled() {
            return;
        }

        self.debug_tracker = Some(DebugTracker::new(debug_config.clone()));
        self.execution_tracer = Some(ExecutionTracer::new(debug_config.clone()));

        // These unwraps are safe because we just created the debug components above
        let debug_tracker = self
            .debug_tracker
            .as_ref()
            .expect("debug_tracker should be initialized")
            .clone();
        let execution_tracer = self
            .execution_tracer
            .as_ref()
            .expect("execution_tracer should be initialized")
            .clone();
        // Allow deprecated API: register_debugger is marked as volatile/experimental but is the
        // only way to access Rhai's debugging functionality. The API is stable in practice and
        // essential for our debugging features. We'll update when a stable replacement is available.
        #[allow(deprecated)]
        self.engine.register_debugger(
            move |_engine, debugger| {
                // Set up breakpoint-based tracing for enhanced debugging
                if debug_config.trace_events {
                    // Enable step-by-step debugging mode for detailed tracing
                    // Note: Specific breakpoint methods may not be available in current Rhai version
                    // The debugger will still trigger Step events for detailed tracing
                }
                debugger
            },
            move |_context, event, node, source, pos| {
                // Update execution context
                debug_tracker.update_context(Some(pos), source);

                // Enhanced event logging with verbosity levels
                match event {
                    DebuggerEvent::Start => {
                        debug_tracker.log_basic("Script execution started");
                        if debug_tracker.config.verbosity >= 3 {
                            if let Some(src) = source {
                                debug_tracker
                                    .log_step("Starting script", &format!("\"{}\"", src.trim()));
                            }
                        }
                    }
                    DebuggerEvent::End => {
                        debug_tracker.log_basic("Script execution completed");
                    }
                    DebuggerEvent::Step => {
                        // Enhanced step-by-step tracing
                        if debug_tracker.config.verbosity >= 2 {
                            // Use execution tracer for step-level tracing
                            let step_info = format!("Step at {}", pos);
                            if let Some(src) = source {
                                execution_tracer.trace_step(0, &step_info, src);
                            } else {
                                execution_tracer.trace_step(0, &step_info, "unknown");
                            }
                        }

                        if debug_tracker.config.verbosity >= 3 {
                            // Even more detailed tracing for -vvv
                            let step_info = format!("Step at {}", pos);
                            let node_info = format!("{:?}", node);
                            debug_tracker.log_step(&step_info, &node_info);

                            // Use execution tracer for expression-level details
                            if let Some(src) = source {
                                execution_tracer.trace_expression_evaluation(src, "evaluating");
                            }
                        }
                    }
                    DebuggerEvent::BreakPoint(_) => {
                        if debug_tracker.config.verbosity >= 2 {
                            debug_tracker.log_detailed("breakpoint", 0, &format!("hit at {}", pos));
                            // Use execution tracer for breakpoint details
                            if let Some(src) = source {
                                execution_tracer.trace_step(0, "Breakpoint hit", src);
                            }
                        }
                    }
                    // Note: Specific function call events may not be available in current Rhai version
                    // We handle function call tracing through Step events and other mechanisms
                    _ => {
                        // Enhanced event tracing
                        if debug_tracker.config.verbosity >= 3 {
                            let event_name = format!("{:?}", event);
                            debug_tracker.log_step("Debug event", &event_name);

                            // Use execution tracer for detailed event tracking
                            if let Some(src) = source {
                                execution_tracer.trace_step(0, &event_name, src);
                            }
                        }
                    }
                }

                // Update execution context with more details
                if debug_tracker.config.verbosity >= 2 {
                    if let Ok(mut ctx) = debug_tracker.context.lock() {
                        ctx.last_operation = Some(format!("{:?}", event));
                        if let Some(src) = source {
                            ctx.source_snippet = Some(src.to_string());
                        }
                    }
                }

                Ok(DebuggerCommand::Continue)
            },
        );
    }

    /// Set whether to suppress side effects (print, eprint, etc.)
    pub fn set_suppress_side_effects(&mut self, suppress: bool) {
        self.suppress_side_effects = suppress;

        // Set the thread-local flag for eprint and other functions
        crate::rhai_functions::strings::set_suppress_side_effects(suppress);

        // Re-register the print handler with the new suppression setting
        let suppress_copy = suppress;
        self.engine.on_print(move |text| {
            if suppress_copy {
                // Suppress all print output
                return;
            }

            if crate::rhai_functions::strings::is_parallel_mode() {
                crate::rhai_functions::strings::capture_print(text.to_string());
            } else {
                println!("{}", text);
            }
        });
    }

    // Individual compilation methods for pipeline stages
    pub fn compile_filter(&mut self, filter: &str) -> Result<CompiledExpression> {
        let ast = self
            .engine
            .compile_expression(filter)
            .with_context(|| format!("Failed to compile filter expression: {}", filter))?;
        Ok(CompiledExpression {
            ast,
            expr: filter.to_string(),
        })
    }

    pub fn compile_exec(&mut self, exec: &str) -> Result<CompiledExpression> {
        let ast = self
            .engine
            .compile(exec)
            .with_context(|| format!("Failed to compile exec script: {}", exec))?;
        Ok(CompiledExpression {
            ast,
            expr: exec.to_string(),
        })
    }

    pub fn compile_begin(&mut self, begin: &str) -> Result<CompiledExpression> {
        let ast = self
            .engine
            .compile(begin)
            .with_context(|| format!("Failed to compile begin expression: {}", begin))?;
        Ok(CompiledExpression {
            ast,
            expr: begin.to_string(),
        })
    }

    pub fn compile_end(&mut self, end: &str) -> Result<CompiledExpression> {
        let ast = self
            .engine
            .compile(end)
            .with_context(|| format!("Failed to compile end expression: {}", end))?;
        Ok(CompiledExpression {
            ast,
            expr: end.to_string(),
        })
    }

    // Individual execution methods for pipeline stages
    pub fn execute_compiled_filter(
        &mut self,
        compiled: &CompiledExpression,
        event: &Event,
        metrics: &mut HashMap<String, Dynamic>,
    ) -> Result<bool> {
        Self::set_thread_tracking_state(metrics);
        let mut scope = self.create_scope_for_event(event);

        // Debug statistics tracking
        debug_stats_increment_events_processed();
        debug_stats_increment_script_executions();

        // Add execution tracing for filter execution
        if let Some(ref tracer) = self.execution_tracer {
            let event_num = tracer.next_event();
            let event_data = format!("{:?}", event.fields);

            // Level 2+: Detailed execution tracing
            if tracer.config.verbosity >= 2 {
                tracer.trace_event_start(event_num, &event_data);
                eprintln!("  Script: {}", compiled.expr.trim());
            }

            // Enhanced detailed tracing for -vvv
            if tracer.config.verbosity >= 3 {
                tracer.trace_scope_inspection(&scope);
                tracer.trace_detailed_step(
                    "filter",
                    "evaluation",
                    &compiled.expr,
                    "starting",
                    "script",
                );
            }
        }

        let result = self
            .engine
            .eval_expression_with_scope::<bool>(&mut scope, &compiled.expr)
            .map_err(|e| {
                // Track errors in debug statistics
                debug_stats_increment_errors();

                let detailed_msg = if let Some(ref debug_tracker) = self.debug_tracker {
                    let enhancer = ErrorEnhancer::new(debug_tracker.config.clone());
                    let context = debug_tracker.get_context();
                    enhancer.enhance_error(&e, &scope, &compiled.expr, "filter", &context)
                } else {
                    Self::format_rhai_error(e, "filter expression", &compiled.expr)
                };
                anyhow::anyhow!("{}", detailed_msg)
            })?;

        // Add execution result tracing
        if let Some(ref tracer) = self.execution_tracer {
            let action = if result { "passed" } else { "filtered out" };
            tracer.trace_event_result(result, action);

            // Enhanced detailed result tracing
            if tracer.config.verbosity >= 3 {
                let result_str = if result { "true" } else { "false" };
                tracer.trace_detailed_step(
                    "filter",
                    "result",
                    &compiled.expr,
                    result_str,
                    "boolean",
                );
            }
        }

        // Track successful events in debug statistics
        if result {
            debug_stats_increment_events_passed();
        }

        *metrics = Self::get_thread_tracking_state();
        Ok(result)
    }

    pub fn execute_compiled_exec(
        &mut self,
        compiled: &CompiledExpression,
        event: &mut Event,
        metrics: &mut HashMap<String, Dynamic>,
    ) -> Result<()> {
        Self::set_thread_tracking_state(metrics);
        let mut scope = self.create_scope_for_event(event);

        // Debug statistics tracking
        debug_stats_increment_script_executions();

        // Add execution tracing for exec execution
        if let Some(ref tracer) = self.execution_tracer {
            let event_num = tracer.next_event();
            let event_data = format!("{:?}", event.fields);

            // Level 2+: Detailed execution tracing
            if tracer.config.verbosity >= 2 {
                tracer.trace_event_start(event_num, &event_data);
                eprintln!("  Script: {}", compiled.expr.trim());
            }

            // Enhanced detailed tracing for -vvv
            if tracer.config.verbosity >= 3 {
                tracer.trace_scope_inspection(&scope);
                tracer.trace_detailed_step(
                    "exec",
                    "transformation",
                    &compiled.expr,
                    "starting",
                    "script",
                );
            }
        }

        let _ = self
            .engine
            .eval_ast_with_scope::<Dynamic>(&mut scope, &compiled.ast)
            .map_err(|e| {
                // Track errors in debug statistics
                debug_stats_increment_errors();

                let detailed_msg = if let Some(ref debug_tracker) = self.debug_tracker {
                    let enhancer = ErrorEnhancer::new(debug_tracker.config.clone());
                    let context = debug_tracker.get_context();
                    enhancer.enhance_error(&e, &scope, &compiled.expr, "exec", &context)
                } else {
                    Self::format_rhai_error(e, "exec script", &compiled.expr)
                };
                anyhow::anyhow!("{}", detailed_msg)
            })?;

        // Add execution result tracing
        if let Some(ref tracer) = self.execution_tracer {
            tracer.trace_event_result(true, "executed successfully");

            // Enhanced detailed result tracing
            if tracer.config.verbosity >= 3 {
                tracer.trace_detailed_step(
                    "exec",
                    "result",
                    &compiled.expr,
                    "success",
                    "execution",
                );
            }
        }

        self.update_event_from_scope(event, &scope);
        *metrics = Self::get_thread_tracking_state();
        Ok(())
    }

    pub fn execute_compiled_begin(
        &mut self,
        compiled: &CompiledExpression,
        metrics: &mut HashMap<String, Dynamic>,
    ) -> Result<rhai::Map> {
        Self::set_thread_tracking_state(metrics);

        // Set begin phase flag to allow read_file/read_lines
        crate::rhai_functions::conf::set_begin_phase(true);

        let mut scope = self.scope_template.clone();

        let _ = self
            .engine
            .eval_ast_with_scope::<Dynamic>(&mut scope, &compiled.ast)
            .map_err(|e| {
                let detailed_msg = Self::format_rhai_error(e, "begin expression", &compiled.expr);
                anyhow::anyhow!("{}", detailed_msg)
            })?;

        // Reset begin phase flag
        crate::rhai_functions::conf::set_begin_phase(false);

        *metrics = Self::get_thread_tracking_state();

        // Extract the conf map from scope and store it
        let mut conf_map = scope.get_value::<rhai::Map>("conf").unwrap_or_default();

        // Deep freeze the conf map to make it read-only
        crate::rhai_functions::conf::deep_freeze_map(&mut conf_map);

        // Store the frozen conf map
        self.conf_map = Some(conf_map.clone());

        Ok(conf_map)
    }

    pub fn execute_compiled_end(
        &self,
        compiled: &CompiledExpression,
        metrics: &HashMap<String, Dynamic>,
    ) -> Result<()> {
        let mut scope = self.scope_template.clone();
        let mut tracked_map = rhai::Map::new();

        // Convert HashMap to Rhai Map (read-only)
        for (k, v) in metrics.iter() {
            tracked_map.insert(k.clone().into(), v.clone());
        }
        scope.set_value("metrics", tracked_map);

        let _ = self
            .engine
            .eval_ast_with_scope::<Dynamic>(&mut scope, &compiled.ast)
            .map_err(|e| {
                let detailed_msg = Self::format_rhai_error(e, "end expression", &compiled.expr);
                anyhow::anyhow!("{}", detailed_msg)
            })?;

        Ok(())
    }

    fn register_variable_resolver(_engine: &mut Engine) {
        // For now, keep this empty - we'll implement proper function-based approach
        // Variable resolver is not the right tool for function calls
    }

    #[allow(dead_code)]
    pub fn execute_begin(&mut self, metrics: &mut HashMap<String, Dynamic>) -> Result<()> {
        if let Some(compiled) = &self.compiled_begin {
            // Set thread-local state from metrics
            Self::set_thread_tracking_state(metrics);

            let mut scope = self.scope_template.clone();

            let _ = self
                .engine
                .eval_ast_with_scope::<Dynamic>(&mut scope, &compiled.ast)
                .map_err(|e| {
                    let detailed_msg =
                        Self::format_rhai_error(e, "begin expression", &compiled.expr);
                    anyhow::anyhow!("{}", detailed_msg)
                })?;

            // Update metrics from thread-local state
            *metrics = Self::get_thread_tracking_state();
        }

        Ok(())
    }

    #[allow(dead_code)]
    pub fn execute_end(&mut self, metrics: &HashMap<String, Dynamic>) -> Result<()> {
        if let Some(compiled) = &self.compiled_end {
            let mut scope = self.scope_template.clone();
            let mut tracked_map = rhai::Map::new();

            // Convert HashMap to Rhai Map (read-only)
            for (k, v) in metrics.iter() {
                tracked_map.insert(k.clone().into(), v.clone());
            }
            scope.set_value("metrics", tracked_map);

            let _ = self
                .engine
                .eval_ast_with_scope::<Dynamic>(&mut scope, &compiled.ast)
                .map_err(|e| {
                    let detailed_msg = Self::format_rhai_error(e, "end expression", &compiled.expr);
                    anyhow::anyhow!("{}", detailed_msg)
                })?;
        }

        Ok(())
    }

    // Window-aware execution methods
    pub fn execute_compiled_filter_with_window(
        &mut self,
        compiled: &CompiledExpression,
        event: &Event,
        window: &[Event],
        metrics: &mut HashMap<String, Dynamic>,
    ) -> Result<bool> {
        Self::set_thread_tracking_state(metrics);
        let mut scope = self.create_scope_for_event_with_window(event, window);

        // Debug statistics tracking
        debug_stats_increment_events_processed();
        debug_stats_increment_script_executions();

        // Add execution tracing for windowed filter execution
        if let Some(ref tracer) = self.execution_tracer {
            let event_num = tracer.next_event();
            let event_data = format!("{:?}", event.fields);

            // Level 2+: Detailed execution tracing
            if tracer.config.verbosity >= 2 {
                tracer.trace_event_start(event_num, &event_data);
                eprintln!(
                    "  Script (windowed, size {}): {}",
                    window.len(),
                    compiled.expr.trim()
                );
            }

            // Enhanced detailed tracing for -vvv
            if tracer.config.verbosity >= 3 {
                tracer.trace_scope_inspection(&scope);
                tracer.trace_detailed_step(
                    "windowed-filter",
                    "evaluation",
                    &compiled.expr,
                    "starting",
                    "script",
                );
                tracer.trace_detailed_step(
                    "windowed-filter",
                    "window-size",
                    &window.len().to_string(),
                    &window.len().to_string(),
                    "size",
                );
            }
        }

        let result = self
            .engine
            .eval_expression_with_scope::<bool>(&mut scope, &compiled.expr)
            .map_err(|e| {
                // Track errors in debug statistics
                debug_stats_increment_errors();

                let detailed_msg = Self::format_rhai_error(e, "filter expression", &compiled.expr);
                anyhow::anyhow!("{}", detailed_msg)
            })?;

        // Add execution result tracing
        if let Some(ref tracer) = self.execution_tracer {
            let action = if result { "passed" } else { "filtered out" };
            tracer.trace_event_result(result, action);

            // Enhanced detailed result tracing
            if tracer.config.verbosity >= 3 {
                let result_str = if result { "true" } else { "false" };
                tracer.trace_detailed_step(
                    "windowed-filter",
                    "result",
                    &compiled.expr,
                    result_str,
                    "boolean",
                );
            }
        }

        // Track successful events in debug statistics
        if result {
            debug_stats_increment_events_passed();
        }

        *metrics = Self::get_thread_tracking_state();
        Ok(result)
    }

    pub fn execute_compiled_exec_with_window(
        &mut self,
        compiled: &CompiledExpression,
        event: &mut Event,
        window: &[Event],
        metrics: &mut HashMap<String, Dynamic>,
    ) -> Result<()> {
        Self::set_thread_tracking_state(metrics);
        let mut scope = self.create_scope_for_event_with_window(event, window);

        // Debug statistics tracking
        debug_stats_increment_script_executions();

        // Add execution tracing for windowed exec execution
        if let Some(ref tracer) = self.execution_tracer {
            let event_num = tracer.next_event();
            let event_data = format!("{:?}", event.fields);

            // Level 2+: Detailed execution tracing
            if tracer.config.verbosity >= 2 {
                tracer.trace_event_start(event_num, &event_data);
                eprintln!(
                    "  Script (windowed, size {}): {}",
                    window.len(),
                    compiled.expr.trim()
                );
            }

            // Enhanced detailed tracing for -vvv
            if tracer.config.verbosity >= 3 {
                tracer.trace_scope_inspection(&scope);
                tracer.trace_detailed_step(
                    "windowed-exec",
                    "transformation",
                    &compiled.expr,
                    "starting",
                    "script",
                );
                tracer.trace_detailed_step(
                    "windowed-exec",
                    "window-size",
                    &window.len().to_string(),
                    &window.len().to_string(),
                    "size",
                );
            }
        }

        let _ = self
            .engine
            .eval_ast_with_scope::<Dynamic>(&mut scope, &compiled.ast)
            .map_err(|e| {
                // Track errors in debug statistics
                debug_stats_increment_errors();

                let detailed_msg = Self::format_rhai_error(e, "exec script", &compiled.expr);
                anyhow::anyhow!("{}", detailed_msg)
            })?;

        // Add execution result tracing
        if let Some(ref tracer) = self.execution_tracer {
            tracer.trace_event_result(true, "executed successfully");

            // Enhanced detailed result tracing
            if tracer.config.verbosity >= 3 {
                tracer.trace_detailed_step(
                    "windowed-exec",
                    "result",
                    &compiled.expr,
                    "success",
                    "execution",
                );
            }
        }

        self.update_event_from_scope(event, &scope);
        *metrics = Self::get_thread_tracking_state();
        Ok(())
    }

    fn create_scope_for_event(&self, event: &Event) -> Scope<'_> {
        let mut scope = self.scope_template.clone();

        // Update built-in variables
        scope.set_value("line", event.original_line.clone());

        // Update event map for fields with invalid identifiers
        let mut event_map = rhai::Map::new();
        for (k, v) in &event.fields {
            event_map.insert(k.clone().into(), v.clone());
        }
        scope.set_value("e", event_map);

        // Update metadata
        let mut meta_map = rhai::Map::new();
        if let Some(line_num) = event.line_num {
            meta_map.insert("line_num".into(), Dynamic::from(line_num as i64));
        }
        if let Some(filename) = &event.filename {
            meta_map.insert("filename".into(), Dynamic::from(filename.clone()));
        }

        // Add raw line for quarantine mode
        meta_map.insert("line".into(), Dynamic::from(event.original_line.clone()));

        // Check for quarantine metadata
        if let Some(parse_error) = event.fields.get("__kelora_quarantine_parse_error") {
            meta_map.insert("parse_error".into(), parse_error.clone());
        }
        if let Some(decode_error) = event.fields.get("__kelora_quarantine_decode_error") {
            meta_map.insert("decode_error".into(), decode_error.clone());
        }

        scope.set_value("meta", meta_map);

        // Set the frozen conf map
        if let Some(ref conf_map) = self.conf_map {
            scope.set_value("conf", conf_map.clone());
        }

        scope
    }

    fn create_scope_for_event_with_window(&self, event: &Event, window: &[Event]) -> Scope<'_> {
        let mut scope = self.create_scope_for_event(event);

        // Add window array to scope
        let window_array: rhai::Array = window
            .iter()
            .map(|event| {
                let mut event_map = rhai::Map::new();
                // Add all event fields to the map
                for (k, v) in &event.fields {
                    event_map.insert(k.clone().into(), v.clone());
                }
                // Add built-in fields
                event_map.insert("line".into(), Dynamic::from(event.original_line.clone()));
                if let Some(line_num) = event.line_num {
                    event_map.insert("line_num".into(), Dynamic::from(line_num as i64));
                }
                if let Some(filename) = &event.filename {
                    event_map.insert("filename".into(), Dynamic::from(filename.clone()));
                }
                Dynamic::from(event_map)
            })
            .collect();

        scope.set_value("window", window_array);
        scope
    }

    fn update_event_from_scope(&self, event: &mut Event, scope: &Scope) {
        // Check if entire event 'e' was set to unit () - clear all fields
        if scope.get_value::<()>("e").is_some() {
            event.fields.clear();
            return;
        }

        // Capture mutations made directly to the `e` event map
        if let Some(obj) = scope.get_value::<Map>("e") {
            for (k, v) in obj {
                // Remove fields that are set to unit () - allows easy field removal
                if v.is::<()>() {
                    event.fields.shift_remove(&k.to_string());
                } else {
                    event.fields.insert(k.to_string(), v.clone());
                }
            }
        }
    }
}