kelora 0.2.2

A command-line log analysis tool with embedded Rhai scripting
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
use rhai::{Dynamic, Engine};
use std::cell::RefCell;
use std::collections::HashMap;

// Thread-local storage for tracking state
thread_local! {
    pub static THREAD_TRACKING_STATE: RefCell<HashMap<String, Dynamic>> = RefCell::new(HashMap::new());
}

/// Unified error tracking function that handles counts, samples, and verbose output
/// This replaces both stats-based and tracking-based error mechanisms
pub fn track_error(
    error_type: &str,
    line_num: Option<usize>,
    message: &str,
    verbose: bool,
    quiet: bool,
    config: Option<&crate::pipeline::PipelineConfig>,
) {
    // Also update stats for the termination case (minimal error count only)
    if error_type == "parse" {
        crate::stats::stats_add_line_error();
    } else {
        crate::stats::stats_add_error();
    }

    THREAD_TRACKING_STATE.with(|state| {
        let mut state = state.borrow_mut();

        // Track error count by type
        let count_key = format!("__kelora_error_count_{}", error_type);
        let current_count = state
            .get(&count_key)
            .cloned()
            .unwrap_or(Dynamic::from(0i64));
        let new_count = current_count.as_int().unwrap_or(0) + 1;
        state.insert(count_key.clone(), Dynamic::from(new_count));
        state.insert(format!("__op_{}", count_key), Dynamic::from("count"));

        // Output verbose errors - use ordered capture system for proper interleaving
        if verbose && !quiet {
            let formatted_error = crate::config::format_verbose_error_with_pipeline_config(
                line_num,
                &format!("{} error", error_type),
                message,
                config,
            );

            if crate::rhai_functions::strings::is_parallel_mode() {
                // In parallel mode, capture stderr message for ordered output later
                crate::rhai_functions::strings::capture_stderr(formatted_error);
            } else {
                // In sequential mode, output immediately but also capture for consistency
                crate::rhai_functions::strings::capture_stderr(formatted_error.clone());
                eprintln!("{}", formatted_error);
            }
        }

        // Track error samples (max 3 per type)
        let samples_key = format!("__kelora_error_samples_{}", error_type);
        let current_samples = state
            .get(&samples_key)
            .cloned()
            .unwrap_or_else(|| Dynamic::from(rhai::Array::new()));

        if let Ok(mut arr) = current_samples.into_array() {
            // Only store up to 3 samples per error type
            if arr.len() < 3 {
                let formatted_error = crate::config::format_verbose_error_with_pipeline_config(
                    line_num,
                    &format!("{} error", error_type),
                    message,
                    config,
                );
                arr.push(Dynamic::from(formatted_error));
            }

            state.insert(samples_key.clone(), Dynamic::from(arr));
            state.insert(format!("__op_{}", samples_key), Dynamic::from("unique"));
        }
    });
}

/// Check if any errors occurred based on tracking data
#[allow(dead_code)] // Used by main.rs binary target, not detected by clippy in lib context
pub fn has_errors_in_tracking(tracked: &HashMap<String, Dynamic>) -> bool {
    for (key, value) in tracked {
        if let Some(_error_type) = key.strip_prefix("__kelora_error_count_") {
            if let Ok(count) = value.as_int() {
                if count > 0 {
                    return true;
                }
            }
        }
    }
    false
}

/// Extract error summary from tracking state with different verbosity levels
#[allow(dead_code)] // Used by main.rs binary target, not detected by clippy in lib context
pub fn extract_error_summary_from_tracking(
    tracked: &HashMap<String, Dynamic>,
    verbose: bool,
) -> Option<String> {
    let mut total_errors = 0;
    let mut error_types = Vec::new();
    let mut samples = Vec::new();

    // Collect error counts by type
    for (key, value) in tracked {
        if let Some(error_type) = key.strip_prefix("__kelora_error_count_") {
            if let Ok(count) = value.as_int() {
                if count > 0 {
                    total_errors += count;
                    error_types.push((error_type.to_string(), count));
                }
            }
        }
    }

    if total_errors == 0 {
        return None;
    }

    // In verbose mode, also collect samples
    if verbose {
        for (key, value) in tracked {
            if let Some(_error_type) = key.strip_prefix("__kelora_error_samples_") {
                if let Ok(sample_array) = value.clone().into_array() {
                    for sample in sample_array {
                        if let Ok(sample_msg) = sample.into_string() {
                            samples.push(sample_msg);
                        }
                    }
                }
            }
        }
    }

    // Format summary based on verbosity
    let mut summary = String::new();

    if error_types.len() == 1 && error_types[0].0 == "parse" {
        // Simple case: only parse errors
        let count = error_types[0].1;
        if count == 1 {
            summary.push_str("Processing completed with 1 parse error");
        } else {
            summary.push_str(&format!("Processing completed with {} parse errors", count));
        }
    } else if error_types.len() == 1 {
        // Simple case: only one error type
        let (error_type, count) = &error_types[0];
        if *count == 1 {
            summary.push_str(&format!("Processing completed with 1 {} error", error_type));
        } else {
            summary.push_str(&format!(
                "Processing completed with {} {} errors",
                count, error_type
            ));
        }
    } else {
        // Multiple error types
        summary.push_str(&format!(
            "Processing completed with {} errors: ",
            total_errors
        ));
        let type_summaries: Vec<String> = error_types
            .iter()
            .map(|(error_type, count)| format!("{} {}", count, error_type))
            .collect();
        summary.push_str(&type_summaries.join(", "));
    }

    // Add samples in verbose mode
    if verbose && !samples.is_empty() {
        summary.push_str("\n\nError examples:");
        for sample in samples {
            summary.push_str(&format!("\n  {}", sample));
        }
    }

    Some(summary)
}

pub fn register_functions(engine: &mut Engine) {
    // Track functions using thread-local storage - clean user API
    // Store operation metadata for proper parallel merging
    engine.register_fn("track_count", |key: &str| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let count = state.get(key).cloned().unwrap_or(Dynamic::from(0i64));
            let new_count = count.as_int().unwrap_or(0) + 1;
            state.insert(key.to_string(), Dynamic::from(new_count));
            // Store operation type metadata for parallel merging
            state.insert(format!("__op_{}", key), Dynamic::from("count"));
        });
    });

    engine.register_fn("track_count", |key: &str, delta: i64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let count = state.get(key).cloned().unwrap_or(Dynamic::from(0i64));
            let new_count = count.as_int().unwrap_or(0) + delta;
            state.insert(key.to_string(), Dynamic::from(new_count));
            // Store operation type metadata for parallel merging
            state.insert(format!("__op_{}", key), Dynamic::from("count"));
        });
    });

    engine.register_fn("track_count", |key: &str, delta: i32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let count = state.get(key).cloned().unwrap_or(Dynamic::from(0i64));
            let new_count = count.as_int().unwrap_or(0) + (delta as i64);
            state.insert(key.to_string(), Dynamic::from(new_count));
            // Store operation type metadata for parallel merging
            state.insert(format!("__op_{}", key), Dynamic::from("count"));
        });
    });

    engine.register_fn("track_count", |key: &str, delta: f64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let count = state.get(key).cloned().unwrap_or(Dynamic::from(0i64));
            let new_count = count.as_int().unwrap_or(0) + (delta as i64);
            state.insert(key.to_string(), Dynamic::from(new_count));
            // Store operation type metadata for parallel merging
            state.insert(format!("__op_{}", key), Dynamic::from("count"));
        });
    });

    engine.register_fn("track_count", |key: &str, delta: f32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let count = state.get(key).cloned().unwrap_or(Dynamic::from(0i64));
            let new_count = count.as_int().unwrap_or(0) + (delta as i64);
            state.insert(key.to_string(), Dynamic::from(new_count));
            // Store operation type metadata for parallel merging
            state.insert(format!("__op_{}", key), Dynamic::from("count"));
        });
    });

    // track_min overloads for different number types
    engine.register_fn("track_min", |key: &str, value: i64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let current = state
                .get(key)
                .cloned()
                .unwrap_or(Dynamic::from(f64::INFINITY));
            let current_val = if current.is_int() {
                current.as_int().unwrap_or(i64::MAX) as f64
            } else {
                current.as_float().unwrap_or(f64::INFINITY)
            };
            let value_f64 = value as f64;
            if value_f64 < current_val {
                state.insert(key.to_string(), Dynamic::from(value));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("min"));
            }
        });
    });

    engine.register_fn("track_min", |key: &str, value: i32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let current = state
                .get(key)
                .cloned()
                .unwrap_or(Dynamic::from(f64::INFINITY));
            let current_val = if current.is_int() {
                current.as_int().unwrap_or(i64::MAX) as f64
            } else {
                current.as_float().unwrap_or(f64::INFINITY)
            };
            let value_f64 = value as f64;
            if value_f64 < current_val {
                state.insert(key.to_string(), Dynamic::from(value));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("min"));
            }
        });
    });

    engine.register_fn("track_min", |key: &str, value: f64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let current = state
                .get(key)
                .cloned()
                .unwrap_or(Dynamic::from(f64::INFINITY));
            let current_val = if current.is_int() {
                current.as_int().unwrap_or(i64::MAX) as f64
            } else {
                current.as_float().unwrap_or(f64::INFINITY)
            };
            if value < current_val {
                state.insert(key.to_string(), Dynamic::from(value));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("min"));
            }
        });
    });

    engine.register_fn("track_min", |key: &str, value: f32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let current = state
                .get(key)
                .cloned()
                .unwrap_or(Dynamic::from(f64::INFINITY));
            let current_val = if current.is_int() {
                current.as_int().unwrap_or(i64::MAX) as f64
            } else {
                current.as_float().unwrap_or(f64::INFINITY)
            };
            let value_f64 = value as f64;
            if value_f64 < current_val {
                state.insert(key.to_string(), Dynamic::from(value));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("min"));
            }
        });
    });

    // track_max overloads for different number types
    engine.register_fn("track_max", |key: &str, value: i64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let current = state
                .get(key)
                .cloned()
                .unwrap_or(Dynamic::from(f64::NEG_INFINITY));
            let current_val = if current.is_int() {
                current.as_int().unwrap_or(i64::MIN) as f64
            } else {
                current.as_float().unwrap_or(f64::NEG_INFINITY)
            };
            let value_f64 = value as f64;
            if value_f64 > current_val {
                state.insert(key.to_string(), Dynamic::from(value));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("max"));
            }
        });
    });

    engine.register_fn("track_max", |key: &str, value: i32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let current = state
                .get(key)
                .cloned()
                .unwrap_or(Dynamic::from(f64::NEG_INFINITY));
            let current_val = if current.is_int() {
                current.as_int().unwrap_or(i64::MIN) as f64
            } else {
                current.as_float().unwrap_or(f64::NEG_INFINITY)
            };
            let value_f64 = value as f64;
            if value_f64 > current_val {
                state.insert(key.to_string(), Dynamic::from(value));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("max"));
            }
        });
    });

    engine.register_fn("track_max", |key: &str, value: f64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let current = state
                .get(key)
                .cloned()
                .unwrap_or(Dynamic::from(f64::NEG_INFINITY));
            let current_val = if current.is_int() {
                current.as_int().unwrap_or(i64::MIN) as f64
            } else {
                current.as_float().unwrap_or(f64::NEG_INFINITY)
            };
            if value > current_val {
                state.insert(key.to_string(), Dynamic::from(value));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("max"));
            }
        });
    });

    engine.register_fn("track_max", |key: &str, value: f32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            let current = state
                .get(key)
                .cloned()
                .unwrap_or(Dynamic::from(f64::NEG_INFINITY));
            let current_val = if current.is_int() {
                current.as_int().unwrap_or(i64::MIN) as f64
            } else {
                current.as_float().unwrap_or(f64::NEG_INFINITY)
            };
            let value_f64 = value as f64;
            if value_f64 > current_val {
                state.insert(key.to_string(), Dynamic::from(value));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("max"));
            }
        });
    });

    engine.register_fn("track_unique", |key: &str, value: &str| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing set or create new one
            let current = state.get(key).cloned().unwrap_or_else(|| {
                // Create a new array to store unique values
                Dynamic::from(rhai::Array::new())
            });

            if let Ok(mut arr) = current.into_array() {
                let value_dynamic = Dynamic::from(value.to_string());
                // Check if value already exists in array
                if !arr
                    .iter()
                    .any(|v| v.clone().into_string().unwrap_or_default() == value)
                {
                    arr.push(value_dynamic);
                }
                state.insert(key.to_string(), Dynamic::from(arr));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("unique"));
            }
        });
    });

    engine.register_fn("track_unique", |key: &str, value: i64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing set or create new one
            let current = state.get(key).cloned().unwrap_or_else(|| {
                // Create a new array to store unique values
                Dynamic::from(rhai::Array::new())
            });

            if let Ok(mut arr) = current.into_array() {
                let value_dynamic = Dynamic::from(value);
                // Check if value already exists in array
                if !arr.iter().any(|v| v.as_int().unwrap_or(i64::MIN) == value) {
                    arr.push(value_dynamic);
                }
                state.insert(key.to_string(), Dynamic::from(arr));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("unique"));
            }
        });
    });

    engine.register_fn("track_unique", |key: &str, value: i32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing set or create new one
            let current = state.get(key).cloned().unwrap_or_else(|| {
                // Create a new array to store unique values
                Dynamic::from(rhai::Array::new())
            });

            if let Ok(mut arr) = current.into_array() {
                let value_dynamic = Dynamic::from(value);
                // Check if value already exists in array
                if !arr
                    .iter()
                    .any(|v| v.as_int().unwrap_or(i64::MIN) == (value as i64))
                {
                    arr.push(value_dynamic);
                }
                state.insert(key.to_string(), Dynamic::from(arr));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("unique"));
            }
        });
    });

    engine.register_fn("track_unique", |key: &str, value: f64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing set or create new one
            let current = state.get(key).cloned().unwrap_or_else(|| {
                // Create a new array to store unique values
                Dynamic::from(rhai::Array::new())
            });

            if let Ok(mut arr) = current.into_array() {
                let value_dynamic = Dynamic::from(value);
                // Check if value already exists in array
                if !arr
                    .iter()
                    .any(|v| v.as_float().unwrap_or(f64::NAN) == value)
                {
                    arr.push(value_dynamic);
                }
                state.insert(key.to_string(), Dynamic::from(arr));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("unique"));
            }
        });
    });

    engine.register_fn("track_unique", |key: &str, value: f32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing set or create new one
            let current = state.get(key).cloned().unwrap_or_else(|| {
                // Create a new array to store unique values
                Dynamic::from(rhai::Array::new())
            });

            if let Ok(mut arr) = current.into_array() {
                let value_dynamic = Dynamic::from(value);
                // Check if value already exists in array
                if !arr
                    .iter()
                    .any(|v| v.as_float().unwrap_or(f64::NAN) == (value as f64))
                {
                    arr.push(value_dynamic);
                }
                state.insert(key.to_string(), Dynamic::from(arr));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("unique"));
            }
        });
    });

    engine.register_fn("track_bucket", |key: &str, bucket: &str| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing map or create new one
            let current = state
                .get(key)
                .cloned()
                .unwrap_or_else(|| Dynamic::from(rhai::Map::new()));

            if let Some(mut map) = current.try_cast::<rhai::Map>() {
                let count = map.get(bucket).cloned().unwrap_or(Dynamic::from(0i64));
                let new_count = count.as_int().unwrap_or(0) + 1;
                map.insert(bucket.into(), Dynamic::from(new_count));
                state.insert(key.to_string(), Dynamic::from(map));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("bucket"));
            }
        });
    });

    engine.register_fn("track_bucket", |key: &str, bucket: i64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing map or create new one
            let current = state
                .get(key)
                .cloned()
                .unwrap_or_else(|| Dynamic::from(rhai::Map::new()));

            if let Some(mut map) = current.try_cast::<rhai::Map>() {
                let bucket_str = bucket.to_string();
                let count = map
                    .get(bucket_str.as_str())
                    .cloned()
                    .unwrap_or(Dynamic::from(0i64));
                let new_count = count.as_int().unwrap_or(0) + 1;
                map.insert(bucket_str.into(), Dynamic::from(new_count));
                state.insert(key.to_string(), Dynamic::from(map));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("bucket"));
            }
        });
    });

    engine.register_fn("track_bucket", |key: &str, bucket: i32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing map or create new one
            let current = state
                .get(key)
                .cloned()
                .unwrap_or_else(|| Dynamic::from(rhai::Map::new()));

            if let Some(mut map) = current.try_cast::<rhai::Map>() {
                let bucket_str = bucket.to_string();
                let count = map
                    .get(bucket_str.as_str())
                    .cloned()
                    .unwrap_or(Dynamic::from(0i64));
                let new_count = count.as_int().unwrap_or(0) + 1;
                map.insert(bucket_str.into(), Dynamic::from(new_count));
                state.insert(key.to_string(), Dynamic::from(map));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("bucket"));
            }
        });
    });

    engine.register_fn("track_bucket", |key: &str, bucket: f64| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing map or create new one
            let current = state
                .get(key)
                .cloned()
                .unwrap_or_else(|| Dynamic::from(rhai::Map::new()));

            if let Some(mut map) = current.try_cast::<rhai::Map>() {
                let bucket_str = bucket.to_string();
                let count = map
                    .get(bucket_str.as_str())
                    .cloned()
                    .unwrap_or(Dynamic::from(0i64));
                let new_count = count.as_int().unwrap_or(0) + 1;
                map.insert(bucket_str.into(), Dynamic::from(new_count));
                state.insert(key.to_string(), Dynamic::from(map));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("bucket"));
            }
        });
    });

    engine.register_fn("track_bucket", |key: &str, bucket: f32| {
        THREAD_TRACKING_STATE.with(|state| {
            let mut state = state.borrow_mut();
            // Get existing map or create new one
            let current = state
                .get(key)
                .cloned()
                .unwrap_or_else(|| Dynamic::from(rhai::Map::new()));

            if let Some(mut map) = current.try_cast::<rhai::Map>() {
                let bucket_str = bucket.to_string();
                let count = map
                    .get(bucket_str.as_str())
                    .cloned()
                    .unwrap_or(Dynamic::from(0i64));
                let new_count = count.as_int().unwrap_or(0) + 1;
                map.insert(bucket_str.into(), Dynamic::from(new_count));
                state.insert(key.to_string(), Dynamic::from(map));
                // Store operation type metadata for parallel merging
                state.insert(format!("__op_{}", key), Dynamic::from("bucket"));
            }
        });
    });
}

// Expose the thread-local state management functions for engine.rs
pub fn set_thread_tracking_state(tracked: &HashMap<String, Dynamic>) {
    THREAD_TRACKING_STATE.with(|state| {
        let mut state = state.borrow_mut();
        state.clear();
        for (k, v) in tracked {
            state.insert(k.clone(), v.clone());
        }
    });
}

pub fn get_thread_tracking_state() -> HashMap<String, Dynamic> {
    THREAD_TRACKING_STATE.with(|state| state.borrow().clone())
}

/// Merge thread-local tracking state into context tracker for sequential mode
#[allow(dead_code)] // Planned feature for parallel mode metrics merging
pub fn merge_thread_tracking_to_context(ctx: &mut crate::pipeline::PipelineContext) {
    let thread_state = get_thread_tracking_state();
    for (key, value) in thread_state {
        ctx.tracker.insert(key, value);
    }
}

/// Create a dynamic map that gives access to current metrics state
#[allow(dead_code)] // Planned feature for exposing metrics to Rhai scripts
fn get_metrics_map() -> Dynamic {
    Dynamic::from(rhai::Map::new()) // Will be populated by accessing current state
}

/// Format metrics for CLI output according to specification
#[allow(dead_code)] // Used by main.rs binary target, not detected by clippy in lib context
pub fn format_metrics_output(tracked: &HashMap<String, Dynamic>) -> String {
    let mut output = String::new();

    // Filter out internal keys (operation metadata and stats)
    let mut user_values: Vec<_> = tracked
        .iter()
        .filter(|(k, _)| !k.starts_with("__op_") && !k.starts_with("__kelora_stats_"))
        .collect();

    if user_values.is_empty() {
        return "No metrics tracked".to_string();
    }

    // Sort by key for consistent output
    user_values.sort_by_key(|(k, _)| k.as_str());

    for (key, value) in user_values {
        if value.is::<rhai::Map>() {
            // Handle unique tracking format: { count: N, sample: [...] }
            if let Some(map) = value.clone().try_cast::<rhai::Map>() {
                if let (Some(count), Some(sample)) = (map.get("count"), map.get("sample")) {
                    if let Ok(sample_array) = sample.clone().into_array() {
                        let sample_strings: Vec<String> = sample_array
                            .iter()
                            .take(3) // Only show first 3 in output
                            .map(|v| format!("\"{}\"", v.clone().into_string().unwrap_or_default()))
                            .collect();
                        output.push_str(&format!(
                            "{:<12} = {{ count: {}, sample: [{}] }}\n",
                            key,
                            count.as_int().unwrap_or(0),
                            sample_strings.join(", ")
                        ));
                        continue;
                    }
                }
            }
        }

        // Handle regular values (count, max, etc.)
        if value.is_int() {
            output.push_str(&format!("{:<12} = {}\n", key, value.as_int().unwrap_or(0)));
        } else if value.is_float() {
            output.push_str(&format!(
                "{:<12} = {}\n",
                key,
                value.as_float().unwrap_or(0.0)
            ));
        } else {
            output.push_str(&format!("{:<12} = {}\n", key, value));
        }
    }

    output.trim_end().to_string()
}

/// Format metrics for JSON output
#[allow(dead_code)] // Used by main.rs binary target, not detected by clippy in lib context
pub fn format_metrics_json(
    tracked: &HashMap<String, Dynamic>,
) -> Result<String, serde_json::Error> {
    let mut json_obj = serde_json::Map::new();

    // Filter out internal keys
    for (key, value) in tracked.iter() {
        if key.starts_with("__op_")
            || key.starts_with("__kelora_stats_")
            || key.starts_with("__kelora_error_")
        {
            continue;
        }

        if value.is::<rhai::Map>() {
            if let Some(map) = value.clone().try_cast::<rhai::Map>() {
                if let (Some(count), Some(sample)) = (map.get("count"), map.get("sample")) {
                    // Handle unique tracking format
                    let mut unique_obj = serde_json::Map::new();
                    unique_obj.insert(
                        "count".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(
                            count.as_int().unwrap_or(0),
                        )),
                    );

                    if let Ok(sample_array) = sample.clone().into_array() {
                        let sample_values: Vec<serde_json::Value> = sample_array
                            .iter()
                            .map(|v| {
                                serde_json::Value::String(
                                    v.clone().into_string().unwrap_or_default(),
                                )
                            })
                            .collect();
                        unique_obj.insert(
                            "sample".to_string(),
                            serde_json::Value::Array(sample_values),
                        );
                    }

                    json_obj.insert(key.clone(), serde_json::Value::Object(unique_obj));
                    continue;
                }
            }
        }

        // Handle regular values
        if value.is_int() {
            json_obj.insert(
                key.clone(),
                serde_json::Value::Number(serde_json::Number::from(value.as_int().unwrap_or(0))),
            );
        } else if value.is_float() {
            if let Some(num) = serde_json::Number::from_f64(value.as_float().unwrap_or(0.0)) {
                json_obj.insert(key.clone(), serde_json::Value::Number(num));
            }
        } else {
            json_obj.insert(key.clone(), serde_json::Value::String(value.to_string()));
        }
    }

    serde_json::to_string_pretty(&json_obj)
}

/// Extract error summary from tracking state
#[allow(dead_code)] // Planned feature for error reporting
pub fn extract_error_summary(tracked: &HashMap<String, Dynamic>) -> Option<String> {
    let mut has_errors = false;
    let mut summary = serde_json::Map::new();

    // Collect error types and their counts
    let mut error_types: std::collections::HashSet<String> = std::collections::HashSet::new();
    for key in tracked.keys() {
        if let Some(suffix) = key.strip_prefix("__kelora_error_count_") {
            error_types.insert(suffix.to_string());
        }
    }

    for error_type in error_types {
        let count_key = format!("__kelora_error_count_{}", error_type);
        let examples_key = format!("__kelora_error_examples_{}", error_type);

        if let Some(count_value) = tracked.get(&count_key) {
            let count = count_value.as_int().unwrap_or(0);
            if count > 0 {
                has_errors = true;
                let mut error_obj = serde_json::Map::new();
                error_obj.insert(
                    "count".to_string(),
                    serde_json::Value::Number(serde_json::Number::from(count)),
                );

                // Add examples if available
                if let Some(examples_value) = tracked.get(&examples_key) {
                    if let Ok(examples_array) = examples_value.clone().into_array() {
                        let examples: Vec<serde_json::Value> = examples_array
                            .iter()
                            .map(|v| {
                                serde_json::Value::String(
                                    v.clone().into_string().unwrap_or_default(),
                                )
                            })
                            .collect();
                        error_obj
                            .insert("examples".to_string(), serde_json::Value::Array(examples));
                    }
                }

                summary.insert(error_type, serde_json::Value::Object(error_obj));
            }
        }
    }

    if has_errors {
        Some(
            serde_json::to_string_pretty(&summary)
                .unwrap_or_else(|_| "Error serializing summary".to_string()),
        )
    } else {
        None
    }
}

/// Write error summary to file if configured
#[allow(dead_code)] // Planned feature for error reporting
pub fn write_error_summary_to_file(
    tracked: &HashMap<String, Dynamic>,
    file_path: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(summary) = extract_error_summary(tracked) {
        use std::fs::File;
        use std::io::Write;
        let mut file = File::create(file_path)?;
        file.write_all(summary.as_bytes())?;
    }
    Ok(())
}