kelora 0.5.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
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
#![allow(dead_code)]
use crate::colors::ColorScheme;
use crate::event::{flatten_dynamic, Event, FlattenStyle};
use crate::pipeline;

use chrono::{DateTime, FixedOffset, SecondsFormat, Utc};
use rhai::Dynamic;
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::Duration as StdDuration;

use once_cell::sync::Lazy;

/// Global header tracking registry for CSV formatters in parallel mode
/// Key format: "{delimiter}_{keys_hash}" for uniqueness across different CSV configurations
static CSV_FORMATTER_HEADER_REGISTRY: Lazy<Mutex<HashMap<String, bool>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

#[cfg(test)]
use crate::pipeline::Formatter;

/// Utility function for single-quote string escaping for default formatter
/// Escapes single quotes, backslashes, newlines, tabs, and carriage returns
fn escape_single_quote_string(input: &str) -> String {
    let mut output = String::with_capacity(input.len() + 10); // Some extra space for escapes

    for ch in input.chars() {
        match ch {
            '\'' => output.push_str("\\'"),
            '\\' => output.push_str("\\\\"),
            '\n' => output.push_str("\\n"),
            '\t' => output.push_str("\\t"),
            '\r' => output.push_str("\\r"),
            _ => output.push(ch),
        }
    }

    output
}

/// Utility function for logfmt-compliant string escaping
/// Escapes quotes, backslashes, newlines, tabs, and carriage returns
fn escape_logfmt_string(input: &str) -> String {
    let mut output = String::with_capacity(input.len() + 10); // Some extra space for escapes

    for ch in input.chars() {
        match ch {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            '\n' => output.push_str("\\n"),
            '\t' => output.push_str("\\t"),
            '\r' => output.push_str("\\r"),
            _ => output.push(ch),
        }
    }

    output
}

/// Check if a string value needs to be quoted with single quotes for default formatter
fn needs_single_quote_quoting(value: &str) -> bool {
    // Quote values that contain spaces, tabs, newlines, single quotes, equals, or are empty
    value.is_empty()
        || value.contains(' ')
        || value.contains('\t')
        || value.contains('\n')
        || value.contains('\r')
        || value.contains('\'')
        || value.contains('=')
}

/// Check if a string value needs to be quoted per logfmt rules
fn needs_logfmt_quoting(value: &str) -> bool {
    // Quote values that contain spaces, tabs, newlines, quotes, equals, or are empty
    value.is_empty()
        || value.contains(' ')
        || value.contains('\t')
        || value.contains('\n')
        || value.contains('\r')
        || value.contains('"')
        || value.contains('=')
}

/// Format a Dynamic value as a string representation suitable for output
/// Returns (string_value, needs_quotes) - the second bool indicates if it should be quoted
fn format_dynamic_value(value: &Dynamic) -> (String, bool) {
    if value.is_string() {
        if let Ok(s) = value.clone().into_string() {
            (s, true) // Strings can potentially need quotes
        } else {
            (value.to_string(), false)
        }
    } else {
        // Numbers, booleans, etc. - never need quotes
        (value.to_string(), false)
    }
}

/// Indent each subsequent line of a multiline string for consistent display
fn indent_multiline_value(value: &str, indent: &str) -> String {
    let mut lines = value.lines();
    match lines.next() {
        Some(first_line) => {
            let mut output = String::from(first_line);
            for line in lines {
                output.push('\n');
                output.push_str(indent);
                output.push_str(line);
            }
            output
        }
        None => String::new(),
    }
}

/// Utility to format a quoted logfmt value into a buffer
fn format_quoted_logfmt_value(value: &str, output: &mut String) {
    if needs_logfmt_quoting(value) {
        output.push('"');
        output.push_str(&escape_logfmt_string(value));
        output.push('"');
    } else {
        output.push_str(value);
    }
}

/// Convert rhai::Dynamic to serde_json::Value recursively
fn dynamic_to_json(value: &Dynamic) -> serde_json::Value {
    if value.is_string() {
        if let Ok(s) = value.clone().into_string() {
            serde_json::Value::String(s)
        } else {
            serde_json::Value::Null
        }
    } else if value.is_int() {
        if let Ok(i) = value.as_int() {
            serde_json::Value::Number(serde_json::Number::from(i))
        } else {
            serde_json::Value::Null
        }
    } else if value.is_float() {
        if let Ok(f) = value.as_float() {
            serde_json::Number::from_f64(f)
                .map(serde_json::Value::Number)
                .unwrap_or(serde_json::Value::Null)
        } else {
            serde_json::Value::Null
        }
    } else if value.is_bool() {
        if let Ok(b) = value.as_bool() {
            serde_json::Value::Bool(b)
        } else {
            serde_json::Value::Null
        }
    } else if value.is_unit() {
        serde_json::Value::Null
    } else if let Some(arr) = value.clone().try_cast::<rhai::Array>() {
        // Convert Rhai array to JSON array recursively
        let json_array: Vec<serde_json::Value> = arr.iter().map(dynamic_to_json).collect();
        serde_json::Value::Array(json_array)
    } else if let Some(map) = value.clone().try_cast::<rhai::Map>() {
        // Convert Rhai map to JSON object recursively
        let mut json_obj = serde_json::Map::new();
        for (key, val) in map {
            json_obj.insert(key.to_string(), dynamic_to_json(&val));
        }
        serde_json::Value::Object(json_obj)
    } else {
        // For any remaining types, convert to string
        serde_json::Value::String(value.to_string())
    }
}

/// Check if a CSV value needs quoting
fn needs_csv_quoting(value: &str, delimiter: char) -> bool {
    value.is_empty()
        || value.contains(delimiter)
        || value.contains('"')
        || value.contains('\n')
        || value.contains('\r')
        || value.starts_with(' ')
        || value.ends_with(' ')
}

/// Escape CSV value with proper quoting
fn escape_csv_value(value: &str, delimiter: char) -> String {
    if needs_csv_quoting(value, delimiter) {
        let escaped = value.replace('"', "\"\"");
        format!("\"{}\"", escaped)
    } else {
        value.to_string()
    }
}

// JSON formatter
pub struct JsonFormatter;

impl JsonFormatter {
    pub fn new() -> Self {
        Self
    }
}

impl pipeline::Formatter for JsonFormatter {
    fn format(&self, event: &Event) -> String {
        // Convert Dynamic values to JSON manually
        let mut json_obj = serde_json::Map::new();

        for (key, value) in crate::event::ordered_fields(event) {
            let json_value = dynamic_to_json(value);
            json_obj.insert(key.clone(), json_value);
        }

        serde_json::to_string(&serde_json::Value::Object(json_obj))
            .unwrap_or_else(|_| "{}".to_string())
    }
}

// Default formatter (logfmt-style with colors and brief mode)
pub struct DefaultFormatter {
    colors: ColorScheme,
    level_keys: Vec<&'static str>,
    brief: bool,
    timestamp_formatting: crate::config::TimestampFormatConfig,
    enable_wrapping: bool,
    terminal_width: usize,
    pretty_nested: bool,
    use_emoji: bool,
    quiet_level: u8,
}

impl DefaultFormatter {
    pub fn new(
        use_colors: bool,
        use_emoji: bool,
        brief: bool,
        timestamp_formatting: crate::config::TimestampFormatConfig,
        pretty_nested: bool,
        quiet_level: u8,
    ) -> Self {
        Self {
            colors: ColorScheme::new(use_colors),
            level_keys: vec![
                "level",
                "loglevel",
                "log_level",
                "lvl",
                "severity",
                "levelname",
                "@l",
            ],
            brief,
            timestamp_formatting,
            enable_wrapping: true, // Default to enabled
            terminal_width: crate::tty::get_terminal_width(),
            pretty_nested,
            use_emoji: use_emoji && use_colors,
            quiet_level,
        }
    }

    pub fn new_with_wrapping(
        use_colors: bool,
        use_emoji: bool,
        brief: bool,
        timestamp_formatting: crate::config::TimestampFormatConfig,
        enable_wrapping: bool,
        pretty_nested: bool,
        quiet_level: u8,
    ) -> Self {
        let terminal_width = if enable_wrapping {
            crate::tty::get_terminal_width()
        } else {
            100 // Doesn't matter if wrapping is disabled
        };

        Self {
            colors: ColorScheme::new(use_colors),
            level_keys: vec![
                "level",
                "loglevel",
                "log_level",
                "lvl",
                "severity",
                "levelname",
                "@l",
            ],
            brief,
            timestamp_formatting,
            enable_wrapping,
            terminal_width,
            pretty_nested,
            use_emoji: use_emoji && use_colors,
            quiet_level,
        }
    }

    /// Format a Dynamic value directly into buffer for performance (zero-allocation when possible)
    fn format_dynamic_value_into(&self, key: &str, value: &Dynamic, output: &mut String) {
        // Check if this field should be formatted as a timestamp
        if self.should_format_as_timestamp(key) {
            if let Some(formatted_ts) = self.try_format_timestamp(value) {
                // Use timestamp formatting
                if !self.colors.string.is_empty() {
                    output.push_str(self.colors.string);
                }
                output.push('\'');
                output.push_str(&escape_single_quote_string(&formatted_ts));
                output.push('\'');
                if !self.colors.string.is_empty() {
                    output.push_str(self.colors.reset);
                }
                return;
            }
        }

        // Choose color based on field type and value content
        let color = if self.is_level_field(key) {
            if let Ok(level_str) = value.clone().into_string() {
                self.level_color(&level_str)
            } else {
                self.colors.string
            }
        } else {
            self.colors.string
        };

        // Format value based on type - always quote strings for default formatter
        let (string_val, is_string) = self.format_default_value(value);
        if is_string {
            // Add opening quote (uncolored)
            output.push('\'');
            // Apply color to content only
            if !color.is_empty() {
                output.push_str(color);
            }
            output.push_str(&escape_single_quote_string(&string_val));
            // Reset color before closing quote
            if !color.is_empty() {
                output.push_str(self.colors.reset);
            }
            // Add closing quote (uncolored)
            output.push('\'')
        } else {
            // For non-strings, color the entire value
            if !color.is_empty() {
                output.push_str(color);
            }
            output.push_str(&string_val);
            if !color.is_empty() {
                output.push_str(self.colors.reset);
            }
        }
    }

    /// Format a Dynamic value for brief mode (no quotes, just the value with colors)
    fn format_dynamic_value_brief_into(&self, key: &str, value: &Dynamic, output: &mut String) {
        // Check if this field should be formatted as a timestamp
        if self.should_format_as_timestamp(key) {
            if let Some(formatted_ts) = self.try_format_timestamp(value) {
                // Use timestamp formatting (no quotes in brief mode)
                if !self.colors.string.is_empty() {
                    output.push_str(self.colors.string);
                }
                output.push_str(&formatted_ts);
                if !self.colors.string.is_empty() {
                    output.push_str(self.colors.reset);
                }
                return;
            }
        }

        // Choose color based on field type and value content
        let color = if self.is_level_field(key) {
            if let Ok(level_str) = value.clone().into_string() {
                self.level_color(&level_str)
            } else {
                self.colors.string
            }
        } else {
            self.colors.string
        };

        // Apply color
        if !color.is_empty() {
            output.push_str(color);
        }

        // In brief mode, output raw value (no quotes even for strings)
        let (formatted_val, _is_string) = self.format_default_value(value);
        output.push_str(&formatted_val);

        // Reset color
        if !color.is_empty() {
            output.push_str(self.colors.reset);
        }
    }

    /// Get appropriate color for log level values
    fn level_color(&self, level: &str) -> &str {
        match level.to_lowercase().as_str() {
            // Bright red for error levels
            "error" | "err" | "fatal" | "panic" | "alert" | "crit" | "critical" | "emerg"
            | "emergency" | "severe" => self.colors.level_error,
            // Bright yellow for warning levels
            "warn" | "warning" => self.colors.level_warn,
            // Bright green for info levels
            "info" | "informational" | "notice" => self.colors.level_info,
            // Bright cyan for debug levels
            "debug" | "finer" | "config" => self.colors.level_debug,
            // Cyan for trace levels
            "trace" | "finest" => self.colors.level_trace,
            // Default to no color for unknown levels
            _ => "",
        }
    }

    /// Check if key is likely a log level field
    fn is_level_field(&self, key: &str) -> bool {
        self.level_keys.contains(&key)
    }

    /// Check if a field should be formatted as a timestamp
    fn should_format_as_timestamp(&self, key: &str) -> bool {
        // Check if this field is explicitly listed in format_fields
        if self
            .timestamp_formatting
            .format_fields
            .contains(&key.to_string())
        {
            return true;
        }

        // Check if auto-formatting is enabled and this is a known timestamp field
        if self.timestamp_formatting.auto_format_all {
            return crate::event::TIMESTAMP_FIELD_NAMES.contains(&key);
        }

        false
    }

    /// Convert a parsed UTC timestamp into the configured display timezone
    fn format_timestamp_output(&self, dt: chrono::DateTime<chrono::Utc>) -> String {
        if self.timestamp_formatting.format_as_utc {
            dt.to_rfc3339()
        } else {
            dt.with_timezone(&chrono::Local).to_rfc3339()
        }
    }

    /// Try to format a value as a timestamp, returning formatted string if successful
    fn try_format_timestamp(&self, value: &Dynamic) -> Option<String> {
        use chrono::{DateTime, Utc};

        let format_hint = self.timestamp_formatting.parse_format_hint.as_deref();
        let timezone_hint = self.timestamp_formatting.parse_timezone_hint.as_deref();

        // First, try if it's already a DateTime value
        if let Some(dt) = value.clone().try_cast::<DateTime<Utc>>() {
            return Some(self.format_timestamp_output(dt));
        }

        // Try to parse numeric timestamps (Unix timestamps)
        if let Ok(timestamp_num) = value.as_int() {
            let timestamp_str = timestamp_num.to_string();
            let mut parser = crate::timestamp::AdaptiveTsParser::new();
            if let Some(parsed_dt) =
                parser.parse_ts_with_config(&timestamp_str, format_hint, timezone_hint)
            {
                return Some(self.format_timestamp_output(parsed_dt));
            }
        }

        // Try to parse float timestamps (Unix timestamps with fractional seconds)
        if let Ok(timestamp_float) = value.as_float() {
            // Handle Unix timestamps in float format by parsing directly
            use chrono::DateTime;

            // Determine precision based on magnitude
            let parsed_dt = if timestamp_float >= 1e15 {
                // Microseconds (16+ digits)
                DateTime::from_timestamp(
                    (timestamp_float / 1_000_000.0).floor() as i64,
                    ((timestamp_float % 1_000_000.0) * 1000.0) as u32,
                )
            } else if timestamp_float >= 1e12 {
                // Milliseconds (13+ digits)
                DateTime::from_timestamp(
                    (timestamp_float / 1000.0).floor() as i64,
                    ((timestamp_float % 1000.0) * 1_000_000.0) as u32,
                )
            } else if timestamp_float >= 1e9 {
                // Seconds with fractional part (10+ digits)
                DateTime::from_timestamp(
                    timestamp_float.floor() as i64,
                    (timestamp_float.fract() * 1_000_000_000.0) as u32,
                )
            } else {
                // Too small to be a valid Unix timestamp
                None
            };

            if let Some(dt) = parsed_dt {
                let utc_dt = dt.with_timezone(&Utc);
                return Some(self.format_timestamp_output(utc_dt));
            }
        }

        // Otherwise, try to parse it as a string timestamp
        if let Ok(ts_str) = value.clone().into_string() {
            let mut parser = crate::timestamp::AdaptiveTsParser::new();
            if let Some(parsed_dt) =
                parser.parse_ts_with_config(&ts_str, format_hint, timezone_hint)
            {
                return Some(self.format_timestamp_output(parsed_dt));
            }
        }

        None
    }

    /// Format a Dynamic value for default output, preserving nested structures
    fn format_default_value(&self, value: &Dynamic) -> (String, bool) {
        // Check if this is a complex nested structure and render it as JSON so the type is explicit
        if value.clone().try_cast::<rhai::Map>().is_some()
            || value.clone().try_cast::<rhai::Array>().is_some()
        {
            let json_value = dynamic_to_json(value);
            let serialized = if self.pretty_nested {
                serde_json::to_string_pretty(&json_value)
            } else {
                serde_json::to_string(&json_value)
            };

            match serialized {
                Ok(mut s) => {
                    if self.pretty_nested {
                        // Keep continuation lines aligned with formatter indentation
                        s = indent_multiline_value(&s, "  ");
                    }
                    (s, false)
                }
                Err(_) => (value.to_string(), false),
            }
        } else {
            // Use the original format_dynamic_value for scalar values
            format_dynamic_value(value)
        }
    }
}

impl pipeline::Formatter for DefaultFormatter {
    fn format(&self, event: &Event) -> String {
        if event.fields.is_empty() {
            return String::new();
        }

        // Add context prefix based on event context type
        let context_prefix = self.get_context_prefix(event);

        self.format_content_with_context(event, &context_prefix)
    }
}

impl DefaultFormatter {
    /// Get the context prefix for an event based on its context type
    fn get_context_prefix(&self, event: &Event) -> String {
        use crate::event::ContextType;

        // Suppress context markers in quiet modes (-q/-qq/-qqq)
        if self.quiet_level > 0 {
            return String::new();
        }

        match event.context_type {
            ContextType::Match => self.render_context_marker(self.colors.context_match, "â—‰", "*"),
            ContextType::Before => self.render_context_marker(self.colors.context_before, "/", "/"),
            ContextType::After => self.render_context_marker(self.colors.context_after, "\\", "\\"),
            ContextType::Both => self.render_context_marker(self.colors.context_overlap, "|", "|"),
            ContextType::None => String::new(),
        }
    }

    fn render_context_marker(
        &self,
        color: &'static str,
        emoji_marker: &str,
        ascii_marker: &str,
    ) -> String {
        let marker = if self.use_emoji {
            emoji_marker
        } else {
            ascii_marker
        };

        if !color.is_empty() {
            format!("{}{}{}", color, marker, self.colors.reset)
        } else {
            marker.to_string()
        }
    }

    /// Format the main content of an event while keeping wrapped lines aligned with the context marker
    fn format_content_with_context(&self, event: &Event, context_prefix: &str) -> String {
        if !self.enable_wrapping {
            // Use original single-line formatting when wrapping is disabled
            let single_line = self.format_single_line(event);
            if context_prefix.is_empty() {
                return single_line;
            } else {
                return format!("{} {}", context_prefix, single_line);
            }
        }

        // Word-wrapping implementation
        let estimated_capacity = event.fields.len() * 32;
        let mut output = String::with_capacity(estimated_capacity);

        // Add context prefix to the first line
        let mut current_line_length = 0;
        let prefix_display_length = self.display_length(context_prefix);
        if !context_prefix.is_empty() {
            output.push_str(context_prefix);
            output.push(' ');
            current_line_length = prefix_display_length + 1;
        }

        let mut first_on_line = true;
        let mut first_overall = true;

        for (key, value) in crate::event::ordered_fields(event) {
            // Build the field string first to measure its length
            let mut field_output = String::new();

            if self.brief {
                // Brief mode: only values (no keys, no quotes)
                self.format_dynamic_value_brief_into(key, value, &mut field_output);
            } else {
                // Normal mode: key=value pairs
                // Format key with color
                if !self.colors.key.is_empty() {
                    field_output.push_str(self.colors.key);
                }
                field_output.push_str(key);
                if !self.colors.key.is_empty() {
                    field_output.push_str(self.colors.reset);
                }

                // Add equals sign
                if !self.colors.equals.is_empty() {
                    field_output.push_str(self.colors.equals);
                }
                field_output.push('=');
                if !self.colors.equals.is_empty() {
                    field_output.push_str(self.colors.reset);
                }

                // Add formatted value (with proper quoting and colors)
                self.format_dynamic_value_into(key, value, &mut field_output);
            }

            // Calculate display length (ignoring ANSI escape codes)
            let field_display_length = self.display_length(&field_output);
            let space_needed = if first_on_line { 0 } else { 1 }; // Space before field

            // Check if we need to wrap (but always fit first field on first line)
            if !first_overall
                && current_line_length + space_needed + field_display_length > self.terminal_width
            {
                // Wrap: add newline, context prefix, and indentation
                output.push('\n');
                if !context_prefix.is_empty() {
                    output.push_str(&" ".repeat(prefix_display_length + 1));
                    current_line_length = prefix_display_length + 1;
                } else {
                    current_line_length = 0;
                }
                output.push_str("  "); // 2-space indentation as requested
                current_line_length += 2; // Account for indentation
                first_on_line = true;
            }

            // Add space separator if not first field on this line
            if !first_on_line {
                output.push(' ');
                current_line_length += 1;
            }

            // Add the field
            output.push_str(&field_output);
            current_line_length += field_display_length;

            first_on_line = false;
            first_overall = false;
        }

        output
    }
}

/// Helper that tracks time gaps between events and renders markers when needed
#[derive(Debug, Clone)]
pub struct GapTracker {
    threshold: chrono::Duration,
    last_timestamp: Option<DateTime<Utc>>,
    use_colors: bool,
}

impl GapTracker {
    pub fn new(threshold: chrono::Duration, use_colors: bool) -> Self {
        Self {
            threshold,
            last_timestamp: None,
            use_colors,
        }
    }

    /// Returns a marker string if the supplied timestamp is sufficiently far from the last one
    pub fn check(&mut self, timestamp: Option<DateTime<Utc>>) -> Option<String> {
        let current_ts = timestamp?;
        let marker = self.last_timestamp.and_then(|previous_ts| {
            let diff = current_ts.signed_duration_since(previous_ts);
            if diff >= self.threshold || diff <= -self.threshold {
                Some(self.render_marker(diff))
            } else {
                None
            }
        });

        self.last_timestamp = Some(current_ts);
        marker
    }

    fn render_marker(&self, diff: chrono::Duration) -> String {
        let diff = if diff >= chrono::Duration::zero() {
            diff
        } else {
            -diff
        };

        let std_duration = diff.to_std().unwrap_or_else(|_| StdDuration::from_secs(0));

        let total_seconds = std_duration.as_secs();
        let hours = total_seconds / 3600;
        let minutes = (total_seconds % 3600) / 60;
        let seconds = total_seconds % 60;
        let micros = std_duration.subsec_micros();

        let time_label = if micros == 0 {
            format!("{}:{:02}:{:02}", hours, minutes, seconds)
        } else {
            let mut fractional = format!("{:06}", micros);
            while fractional.ends_with('0') {
                fractional.pop();
            }
            format!("{}:{:02}:{:02}.{}", hours, minutes, seconds, fractional)
        };
        let label = format!(" time gap: {} ", time_label);

        let blue = "\x1b[34m";
        let reset = "\x1b[0m";

        let mut width = crate::tty::get_terminal_width();
        if width == 0 {
            width = 80;
        }

        if width <= label.len() {
            let marker = label.trim().to_string();
            if self.use_colors {
                return format!("{}{}{}", blue, marker, reset);
            }
            return marker;
        }

        let remaining = width - label.len();
        let left = remaining / 2;
        let right = remaining - left;

        let mut marker = String::with_capacity(width);
        marker.push_str(&"_".repeat(left));
        marker.push_str(&label);
        marker.push_str(&"_".repeat(right));
        if self.use_colors {
            return format!("{}{}{}", blue, marker, reset);
        }
        marker
    }
}

impl DefaultFormatter {
    /// Original single-line formatting for when wrapping is disabled
    fn format_single_line(&self, event: &Event) -> String {
        let estimated_capacity = event.fields.len() * 32;
        let mut output = String::with_capacity(estimated_capacity);
        let mut first = true;

        for (key, value) in crate::event::ordered_fields(event) {
            if !first {
                output.push(' ');
            }
            first = false;

            if self.brief {
                // Brief mode: only values (no keys, no quotes)
                self.format_dynamic_value_brief_into(key, value, &mut output);
            } else {
                // Normal mode: key=value pairs
                // Format key with color
                if !self.colors.key.is_empty() {
                    output.push_str(self.colors.key);
                }
                output.push_str(key);
                if !self.colors.key.is_empty() {
                    output.push_str(self.colors.reset);
                }

                // Add equals sign
                if !self.colors.equals.is_empty() {
                    output.push_str(self.colors.equals);
                }
                output.push('=');
                if !self.colors.equals.is_empty() {
                    output.push_str(self.colors.reset);
                }

                // Add formatted value (with proper quoting and colors)
                self.format_dynamic_value_into(key, value, &mut output);
            }
        }

        output
    }

    /// Calculate display length of a string, ignoring ANSI escape codes
    fn display_length(&self, text: &str) -> usize {
        let mut length = 0;
        let mut in_escape = false;

        for ch in text.chars() {
            if ch == '\x1b' {
                in_escape = true;
            } else if in_escape && ch == 'm' {
                in_escape = false;
            } else if !in_escape {
                length += 1;
            }
        }

        length
    }
}

// Hide formatter - suppresses all event output
pub struct HideFormatter;

impl HideFormatter {
    pub fn new() -> Self {
        Self
    }
}

impl pipeline::Formatter for HideFormatter {
    fn format(&self, _event: &Event) -> String {
        String::new()
    }
}

// Inspect formatter - detailed, type-aware introspection output
pub struct InspectFormatter {
    max_inline_chars: usize,
}

struct LineSpec<'a> {
    indent: usize,
    name: &'a str,
    name_width: usize,
    type_width: usize,
    type_label: &'a str,
    value_repr: &'a str,
}

impl InspectFormatter {
    const KEY_WIDTH_CAP: usize = 40;

    pub fn new(verbosity: u8) -> Self {
        // Gradually relax truncation with higher verbosity levels
        let max_inline_chars = match verbosity {
            0 => 80,
            1 => 160,
            _ => usize::MAX,
        };

        Self { max_inline_chars }
    }

    fn format_entries<'a, I>(&self, lines: &mut Vec<String>, entries: I, indent: usize)
    where
        I: IntoIterator<Item = (&'a str, &'a Dynamic)>,
    {
        // Collect to compute alignment without re-iterating source data
        let collected: Vec<(&str, &Dynamic)> = entries.into_iter().collect();
        if collected.is_empty() {
            return;
        }

        let name_width = self.compute_key_width(collected.iter().map(|(k, _)| *k));
        let type_width = self.compute_type_width(collected.iter().map(|(_, v)| *v));

        for (key, value) in collected {
            self.format_entry_with_width(lines, key, value, indent, name_width, type_width);
        }
    }

    fn format_entry_with_width(
        &self,
        lines: &mut Vec<String>,
        name: &str,
        value: &Dynamic,
        indent: usize,
        name_width: usize,
        type_width: usize,
    ) {
        if let Some(map) = value.clone().try_cast::<rhai::Map>() {
            let entries: Vec<(String, Dynamic)> =
                map.into_iter().map(|(k, v)| (k.into(), v)).collect();
            let type_label = format!("map({})", entries.len());
            self.push_line(
                lines,
                LineSpec {
                    indent,
                    name,
                    name_width,
                    type_width,
                    type_label: &type_label,
                    value_repr: "{",
                },
            );

            if !entries.is_empty() {
                let child_width = self.compute_key_width(entries.iter().map(|(k, _)| k.as_str()));
                let child_type_width = self.compute_type_width(entries.iter().map(|(_, v)| v));
                for (child_key, child_value) in &entries {
                    self.format_entry_with_width(
                        lines,
                        child_key,
                        child_value,
                        indent + 1,
                        child_width,
                        child_type_width,
                    );
                }
            }

            lines.push(format!("{}{}", "  ".repeat(indent), "}"));
        } else if let Some(array) = value.clone().try_cast::<rhai::Array>() {
            let elements: Vec<Dynamic> = array.into_iter().collect();
            let type_label = format!("array({})", elements.len());
            self.push_line(
                lines,
                LineSpec {
                    indent,
                    name,
                    name_width,
                    type_width,
                    type_label: &type_label,
                    value_repr: "[",
                },
            );

            if !elements.is_empty() {
                let index_labels: Vec<String> =
                    (0..elements.len()).map(|i| format!("[{}]", i)).collect();
                let child_width = self.compute_key_width(index_labels.iter().map(|s| s.as_str()));
                let child_type_width = self.compute_type_width(elements.iter());

                for (idx, element) in elements.iter().enumerate() {
                    let child_name = &index_labels[idx];
                    self.format_entry_with_width(
                        lines,
                        child_name,
                        element,
                        indent + 1,
                        child_width,
                        child_type_width,
                    );
                }
            }

            lines.push(format!("{}{}", "  ".repeat(indent), "]"));
        } else {
            let (type_label, value_repr) = self.describe_scalar(value);
            self.push_line(
                lines,
                LineSpec {
                    indent,
                    name,
                    name_width,
                    type_width,
                    type_label: &type_label,
                    value_repr: &value_repr,
                },
            );
        }
    }

    fn push_line(&self, lines: &mut Vec<String>, spec: LineSpec<'_>) {
        let indent_str = "  ".repeat(spec.indent);
        let name_cell = if spec.name_width > 0 {
            format!("{name:<width$}", name = spec.name, width = spec.name_width)
        } else {
            spec.name.to_string()
        };
        let effective_type_width = spec.type_width.max(spec.type_label.len());
        let type_cell = format!(
            "{type_label:<width$}",
            type_label = spec.type_label,
            width = effective_type_width
        );
        lines.push(format!(
            "{indent}{name_cell} | {type_cell} | {value}",
            indent = indent_str,
            name_cell = name_cell,
            type_cell = type_cell,
            value = spec.value_repr
        ));
    }

    fn compute_key_width<'a, I>(&self, keys: I) -> usize
    where
        I: Iterator<Item = &'a str>,
    {
        keys.map(|k| k.len())
            .max()
            .unwrap_or(0)
            .min(Self::KEY_WIDTH_CAP)
    }

    fn compute_type_width<'a, I>(&self, values: I) -> usize
    where
        I: Iterator<Item = &'a Dynamic>,
    {
        values
            .map(|value| self.type_label_for(value).len())
            .max()
            .unwrap_or(0)
    }

    fn type_label_for(&self, value: &Dynamic) -> String {
        if let Some(map) = value.clone().try_cast::<rhai::Map>() {
            return format!("map({})", map.len());
        }
        if let Some(array) = value.clone().try_cast::<rhai::Array>() {
            return format!("array({})", array.len());
        }
        if value.is_string() {
            return "string".to_string();
        }
        if value.is_bool() {
            return "bool".to_string();
        }
        if value.is_int() {
            return "int".to_string();
        }
        if value.is_float() {
            return "float".to_string();
        }
        if value.is_char() {
            return "char".to_string();
        }
        if value.is_unit() {
            return "null".to_string();
        }
        value.type_name().to_string()
    }

    fn describe_scalar(&self, value: &Dynamic) -> (String, String) {
        if value.is_string() {
            if let Ok(inner) = value.clone().into_string() {
                let escaped = self.escape_for_display(&inner);
                let (truncated, was_truncated) = self.truncate_value(&escaped);
                let mut rendered = format!("\"{}\"", truncated);
                if was_truncated {
                    rendered.push_str("...");
                }
                return ("string".to_string(), rendered);
            }
        }

        if value.is_bool() {
            if let Ok(b) = value.as_bool() {
                return ("bool".to_string(), b.to_string());
            }
        }

        if value.is_int() {
            if let Ok(i) = value.as_int() {
                return ("int".to_string(), i.to_string());
            }
        }

        if value.is_float() {
            if let Ok(f) = value.as_float() {
                return ("float".to_string(), format!("{f}"));
            }
        }

        if value.is_char() {
            if let Ok(c) = value.as_char() {
                return (
                    "char".to_string(),
                    format!("'{}'", self.escape_for_display(&c.to_string())),
                );
            }
        }

        if value.is_unit() {
            return ("null".to_string(), "null".to_string());
        }

        // Fallback for other scalar types
        let type_label = value.type_name().to_string();
        let rendered = self.escape_for_display(&value.to_string());
        let (truncated, was_truncated) = self.truncate_value(&rendered);
        let mut repr = truncated;
        if was_truncated {
            repr.push_str("...");
        }
        (type_label, repr)
    }

    fn escape_for_display(&self, input: &str) -> String {
        let mut escaped = String::with_capacity(input.len());
        for ch in input.chars() {
            match ch {
                '\\' => escaped.push_str("\\\\"),
                '\n' => escaped.push_str("\\n"),
                '\r' => escaped.push_str("\\r"),
                '\t' => escaped.push_str("\\t"),
                c if c.is_control() => {
                    escaped.push_str(&format!("\\x{:02X}", c as u32));
                }
                c => escaped.push(c),
            }
        }
        escaped
    }

    fn truncate_value(&self, value: &str) -> (String, bool) {
        if self.max_inline_chars == usize::MAX || value.chars().count() <= self.max_inline_chars {
            return (value.to_string(), false);
        }

        let truncated: String = value.chars().take(self.max_inline_chars).collect();

        (truncated, true)
    }
}

impl pipeline::Formatter for InspectFormatter {
    fn format(&self, event: &Event) -> String {
        if event.fields.is_empty() {
            return "---".to_string();
        }

        let mut lines = Vec::new();
        self.format_entries(
            &mut lines,
            crate::event::ordered_fields(event)
                .into_iter()
                .map(|(k, v)| (k.as_str(), v)),
            0,
        );
        lines.insert(0, "---".to_string());
        lines.join("\n")
    }
}

/// Sanitize a field key to ensure logfmt compliance
///
/// The logfmt specification requires keys to:
/// - Not contain whitespace (spaces, tabs, newlines, carriage returns)
/// - Not contain equals signs (=) as they delimit key-value pairs
///
/// This function replaces problematic characters with underscores to maintain
/// field information while ensuring valid logfmt output. This approach:
/// - Preserves all field data (no information loss)
/// - Produces parseable logfmt output
/// - Maintains deterministic key mapping
/// - Handles edge cases gracefully
///
/// # Examples
/// - sanitize_logfmt_key("field with spaces") -> "field_with_spaces"
/// - sanitize_logfmt_key("field=with=equals") -> "field_with_equals"  
/// - sanitize_logfmt_key("normal_field") -> "normal_field"
fn sanitize_logfmt_key(key: &str) -> String {
    key.chars()
        .map(|c| match c {
            ' ' | '\t' | '\n' | '\r' | '=' => '_',
            c => c,
        })
        .collect()
}

// Logfmt formatter - strict logfmt output formatter (no colors, no brief mode)
//
// This formatter produces logfmt-compliant output by:
// 1. Sanitizing field keys to replace invalid characters with underscores
// 2. Properly quoting string values that contain special characters
// 3. Leaving numeric and boolean values unquoted
//
// Key sanitization ensures that output can be parsed by standard logfmt parsers,
// including Kelora's own logfmt input parser.
pub struct LogfmtFormatter;

impl LogfmtFormatter {
    pub fn new() -> Self {
        Self
    }

    /// Format a Dynamic value directly into buffer for performance
    fn format_dynamic_value_into(&self, value: &Dynamic, output: &mut String) {
        let string_val = self.format_logfmt_value(value);
        let is_string = value.is_string();

        if is_string {
            format_quoted_logfmt_value(&string_val, output);
        } else {
            output.push_str(&string_val);
        }
    }

    /// Format a Dynamic value for logfmt output, flattening nested structures
    fn format_logfmt_value(&self, value: &Dynamic) -> String {
        // Check if this is a complex nested structure
        if value.clone().try_cast::<rhai::Map>().is_some()
            || value.clone().try_cast::<rhai::Array>().is_some()
        {
            // Flatten nested structures using underscore style for logfmt safety
            let flattened = flatten_dynamic(value, FlattenStyle::Underscore, 0);

            if flattened.len() == 1 {
                // Single flattened value - use it directly
                flattened.values().next().unwrap().to_string()
            } else if flattened.is_empty() {
                // Empty structure
                String::new()
            } else {
                // Multiple flattened values - create a compact representation
                // Format as "key1=val1,key2=val2" for logfmt-style readability
                flattened
                    .iter()
                    .map(|(k, v)| format!("{}={}", k, v))
                    .collect::<Vec<_>>()
                    .join(",")
            }
        } else {
            // Simple scalar value
            value.to_string()
        }
    }
}

impl pipeline::Formatter for LogfmtFormatter {
    fn format(&self, event: &Event) -> String {
        if event.fields.is_empty() {
            return String::new();
        }

        // Pre-allocate buffer with estimated capacity
        let estimated_capacity = event.fields.len() * 32;
        let mut output = String::with_capacity(estimated_capacity);
        let mut first = true;

        for (key, value) in crate::event::ordered_fields(event) {
            if !first {
                output.push(' ');
            }
            first = false;

            // Strict logfmt: key=value pairs with sanitized keys
            // Keys are sanitized to ensure logfmt compliance (no spaces, equals signs, etc.)
            let sanitized_key = sanitize_logfmt_key(key);
            output.push_str(&sanitized_key);
            output.push('=');
            self.format_dynamic_value_into(value, &mut output);
        }

        output
    }
}

struct LevelmapState {
    current_timestamp: Option<String>,
    buffer: String,
    visible_len: usize,
}

impl LevelmapState {
    fn new(initial_capacity: usize) -> Self {
        let base_capacity = initial_capacity.max(1) * 4;
        Self {
            current_timestamp: None,
            buffer: String::with_capacity(base_capacity),
            visible_len: 0,
        }
    }

    fn reset(&mut self) {
        self.current_timestamp = None;
        self.buffer.clear();
        self.visible_len = 0;
    }

    fn push_rendered(&mut self, rendered: &str) {
        self.buffer.push_str(rendered);
        self.visible_len += 1;
    }
}

pub struct LevelmapFormatter {
    state: Mutex<LevelmapState>,
    terminal_width: usize,
    buffer_width_override: Option<usize>,
    colors: ColorScheme,
}

impl LevelmapFormatter {
    const FALLBACK_TERMINAL_WIDTH: usize = 80;

    pub fn new(use_colors: bool) -> Self {
        let detected_width = crate::tty::get_terminal_width();
        let terminal_width = if detected_width == 0 {
            Self::FALLBACK_TERMINAL_WIDTH
        } else {
            detected_width
        };

        Self {
            state: Mutex::new(LevelmapState::new(terminal_width)),
            terminal_width,
            buffer_width_override: None,
            colors: ColorScheme::new(use_colors),
        }
    }

    #[cfg(test)]
    pub fn with_width(width: usize) -> Self {
        let effective_width = width.max(1);
        Self {
            state: Mutex::new(LevelmapState::new(effective_width)),
            terminal_width: effective_width,
            buffer_width_override: Some(effective_width),
            colors: ColorScheme::new(false),
        }
    }

    fn format_line(timestamp: Option<&String>, buffer: &str) -> String {
        match timestamp {
            Some(ts) if !ts.is_empty() => format!("{} {}", ts, buffer),
            _ => buffer.to_string(),
        }
    }

    fn available_width(&self, timestamp: Option<&String>) -> usize {
        if let Some(override_width) = self.buffer_width_override {
            return override_width.max(1);
        }

        let terminal_width = self.terminal_width.max(1);
        let reserved = timestamp
            .filter(|ts| !ts.is_empty())
            .map(|ts| ts.len().saturating_add(1))
            .unwrap_or(0);

        terminal_width.saturating_sub(reserved).max(1)
    }

    fn extract_level_string(event: &Event) -> Option<String> {
        for key in crate::event::LEVEL_FIELD_NAMES {
            if let Some(value) = event.fields.get(*key) {
                if let Some(level) = Self::dynamic_to_trimmed_string(value) {
                    return Some(level);
                }
            }
        }
        None
    }

    fn dynamic_to_trimmed_string(value: &Dynamic) -> Option<String> {
        if let Ok(s) = value.clone().into_string() {
            let trimmed = s.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        } else {
            let fallback = value.to_string();
            let trimmed = fallback.trim();
            if trimmed.is_empty() || trimmed == "()" {
                None
            } else {
                Some(trimmed.to_string())
            }
        }
    }

    fn render_level_char(&self, level: Option<&str>, ch: char) -> String {
        if let Some(level_str) = level {
            let color = self.level_color(level_str);
            if !color.is_empty() {
                let mut rendered = String::with_capacity(color.len() + self.colors.reset.len() + 1);
                rendered.push_str(color);
                rendered.push(ch);
                rendered.push_str(self.colors.reset);
                return rendered;
            }
        }

        ch.to_string()
    }

    fn level_color<'a>(&'a self, level: &str) -> &'a str {
        match level.to_lowercase().as_str() {
            "error" | "err" | "fatal" | "panic" | "alert" | "crit" | "critical" | "emerg"
            | "emergency" | "severe" => self.colors.level_error,
            "warn" | "warning" => self.colors.level_warn,
            "info" | "informational" | "notice" => self.colors.level_info,
            "debug" | "finer" | "config" => self.colors.level_debug,
            "trace" | "finest" => self.colors.level_trace,
            _ => "",
        }
    }

    fn extract_timestamp(event: &Event) -> String {
        if let Some(ts) = event.parsed_ts {
            return Self::format_timestamp(ts);
        }

        for key in crate::event::TIMESTAMP_FIELD_NAMES {
            if let Some(value) = event.fields.get(*key) {
                if let Some(ts) = value.clone().try_cast::<DateTime<Utc>>() {
                    return Self::format_timestamp(ts);
                }

                if let Some(ts) = value.clone().try_cast::<DateTime<FixedOffset>>() {
                    return Self::format_timestamp(ts.with_timezone(&Utc));
                }

                if let Ok(string_value) = value.clone().into_string() {
                    let trimmed = string_value.trim();
                    if !trimmed.is_empty() {
                        return trimmed.to_string();
                    }
                } else {
                    let fallback = value.to_string();
                    let trimmed = fallback.trim();
                    if !trimmed.is_empty() && trimmed != "()" {
                        return trimmed.to_string();
                    }
                }
            }
        }

        if let Some(line_num) = event.line_num {
            format!("line {}", line_num)
        } else {
            "unknown".to_string()
        }
    }

    fn format_timestamp(ts: DateTime<Utc>) -> String {
        ts.to_rfc3339_opts(SecondsFormat::Millis, true)
    }
}

impl pipeline::Formatter for LevelmapFormatter {
    fn format(&self, event: &Event) -> String {
        let mut state = self
            .state
            .lock()
            .expect("levelmap formatter mutex poisoned");

        if state.current_timestamp.is_none() {
            state.current_timestamp = Some(Self::extract_timestamp(event));
        }

        let available_width = self.available_width(state.current_timestamp.as_ref());

        let level_string = Self::extract_level_string(event);
        let display_char = level_string
            .as_deref()
            .and_then(|s| s.chars().next())
            .unwrap_or('?');
        let rendered = self.render_level_char(level_string.as_deref(), display_char);
        state.push_rendered(&rendered);

        if state.visible_len >= available_width {
            let line = Self::format_line(state.current_timestamp.as_ref(), &state.buffer);
            state.reset();
            line
        } else {
            String::new()
        }
    }

    fn finish(&self) -> Option<String> {
        let mut state = self
            .state
            .lock()
            .expect("levelmap formatter mutex poisoned");
        if state.visible_len == 0 {
            return None;
        }

        let line = Self::format_line(state.current_timestamp.as_ref(), &state.buffer);
        state.reset();

        if line.is_empty() {
            None
        } else {
            Some(line)
        }
    }
}

// CSV formatter - outputs CSV format with required field order
pub struct CsvFormatter {
    delimiter: char,
    keys: Vec<String>,
    include_header: bool,
    formatter_key: String,
    worker_mode: bool, // If true, never write headers (for parallel workers)
}

impl CsvFormatter {
    pub fn new(keys: Vec<String>) -> Self {
        let formatter_key = format!(",_{}", Self::keys_hash(&keys));
        Self {
            delimiter: ',',
            keys,
            include_header: true,
            formatter_key,
            worker_mode: false,
        }
    }

    pub fn new_tsv(keys: Vec<String>) -> Self {
        let formatter_key = format!("\t_{}", Self::keys_hash(&keys));
        Self {
            delimiter: '\t',
            keys,
            include_header: true,
            formatter_key,
            worker_mode: false,
        }
    }

    pub fn new_csv_no_header(keys: Vec<String>) -> Self {
        let formatter_key = format!(",_noheader_{}", Self::keys_hash(&keys));
        Self {
            delimiter: ',',
            keys,
            include_header: false,
            formatter_key,
            worker_mode: false,
        }
    }

    pub fn new_tsv_no_header(keys: Vec<String>) -> Self {
        let formatter_key = format!("\t_noheader_{}", Self::keys_hash(&keys));
        Self {
            delimiter: '\t',
            keys,
            include_header: false,
            formatter_key,
            worker_mode: false,
        }
    }

    /// Create worker-mode variants that never write headers
    pub fn new_worker(keys: Vec<String>) -> Self {
        let formatter_key = format!(",_worker_{}", Self::keys_hash(&keys));
        Self {
            delimiter: ',',
            keys,
            include_header: false, // Workers never write headers
            formatter_key,
            worker_mode: true,
        }
    }

    pub fn new_tsv_worker(keys: Vec<String>) -> Self {
        let formatter_key = format!("\t_worker_{}", Self::keys_hash(&keys));
        Self {
            delimiter: '\t',
            keys,
            include_header: false, // Workers never write headers
            formatter_key,
            worker_mode: true,
        }
    }

    pub fn new_csv_no_header_worker(keys: Vec<String>) -> Self {
        let formatter_key = format!(",_noheader_worker_{}", Self::keys_hash(&keys));
        Self {
            delimiter: ',',
            keys,
            include_header: false,
            formatter_key,
            worker_mode: true,
        }
    }

    pub fn new_tsv_no_header_worker(keys: Vec<String>) -> Self {
        let formatter_key = format!("\t_noheader_worker_{}", Self::keys_hash(&keys));
        Self {
            delimiter: '\t',
            keys,
            include_header: false,
            formatter_key,
            worker_mode: true,
        }
    }

    /// Create a simple hash of the keys for uniqueness
    fn keys_hash(keys: &[String]) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        keys.hash(&mut hasher);
        hasher.finish()
    }

    /// Mark header as written globally for this formatter configuration
    /// Returns true if this call was the first to mark it (header should be written)
    fn mark_header_written_globally(&self) -> bool {
        let mut registry = CSV_FORMATTER_HEADER_REGISTRY.lock().unwrap();
        if registry.get(&self.formatter_key).copied().unwrap_or(false) {
            // Already marked by another thread
            false
        } else {
            // This is the first thread to mark it
            registry.insert(self.formatter_key.clone(), true);
            true
        }
    }

    /// Format the header row
    pub fn format_header(&self) -> String {
        self.keys
            .iter()
            .map(|key| escape_csv_value(key, self.delimiter))
            .collect::<Vec<_>>()
            .join(&self.delimiter.to_string())
    }

    /// Format a data row
    fn format_data_row(&self, event: &Event) -> String {
        self.keys
            .iter()
            .map(|key| {
                if let Some(value) = event.fields.get(key) {
                    let string_value = self.format_csv_value(value);
                    escape_csv_value(&string_value, self.delimiter)
                } else {
                    String::new() // Empty field for missing values
                }
            })
            .collect::<Vec<_>>()
            .join(&self.delimiter.to_string())
    }

    /// Format a Dynamic value for CSV output, flattening nested structures
    fn format_csv_value(&self, value: &Dynamic) -> String {
        // Check if this is a complex nested structure
        if value.clone().try_cast::<rhai::Map>().is_some()
            || value.clone().try_cast::<rhai::Array>().is_some()
        {
            // Flatten nested structures using underscore style for CSV safety
            let flattened = flatten_dynamic(value, FlattenStyle::Underscore, 0);

            if flattened.len() == 1 {
                // Single flattened value - use it directly
                flattened.values().next().unwrap().to_string()
            } else if flattened.is_empty() {
                // Empty structure
                String::new()
            } else {
                // Multiple flattened values - create a compact representation
                // Format as "key1:val1,key2:val2" for readability in CSV cells
                flattened
                    .iter()
                    .map(|(k, v)| format!("{}:{}", k, v))
                    .collect::<Vec<_>>()
                    .join(",")
            }
        } else {
            // Simple scalar value
            value.to_string()
        }
    }
}

impl pipeline::Formatter for CsvFormatter {
    fn format(&self, event: &Event) -> String {
        let mut output = String::new();

        // Write header row if needed (thread-safe, once only across all workers)
        // Workers in parallel mode never write headers
        if !self.worker_mode && self.include_header && self.mark_header_written_globally() {
            output.push_str(&self.format_header());
            output.push('\n');
        }

        // Write data row
        output.push_str(&self.format_data_row(event));
        output
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::ContextType;
    use chrono::{Duration as ChronoDuration, TimeZone, Utc};
    use rhai::{Array, Map};

    fn parts(line: &str) -> Vec<String> {
        line.split('|')
            .map(|segment| segment.trim().to_string())
            .collect()
    }

    #[test]
    fn test_json_formatter_empty_event() {
        let event = Event::default();
        let formatter = JsonFormatter::new();
        let result = formatter.format(&event);
        assert!(result.starts_with('{') && result.ends_with('}'));
    }

    #[test]
    fn test_json_formatter_with_fields() {
        let mut event = Event::default();
        event.set_field("level".to_string(), Dynamic::from("INFO".to_string()));
        event.set_field("msg".to_string(), Dynamic::from("Test message".to_string()));
        event.set_field("user".to_string(), Dynamic::from("alice".to_string()));
        event.set_field("status".to_string(), Dynamic::from(200i64));

        let formatter = JsonFormatter::new();
        let result = formatter.format(&event);

        assert!(result.contains("\"level\":\"INFO\""));
        assert!(result.contains("\"msg\":\"Test message\""));
        assert!(result.contains("\"user\":\"alice\""));
        assert!(result.contains("\"status\":200"));
    }

    #[test]
    fn test_inspect_formatter_basic() {
        let mut event = Event::default();
        event.set_field("message".to_string(), Dynamic::from("hello"));
        event.set_field("code".to_string(), Dynamic::from(42_i64));
        event.set_field("active".to_string(), Dynamic::from(true));

        let formatter = InspectFormatter::new(0);
        let output = formatter.format(&event);
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines[0], "---");
        assert_eq!(lines.len(), 4);
        assert_eq!(
            parts(lines[1]),
            vec![
                "message".to_string(),
                "string".to_string(),
                "\"hello\"".to_string()
            ]
        );
        assert_eq!(
            parts(lines[2]),
            vec!["code".to_string(), "int".to_string(), "42".to_string()]
        );
        assert_eq!(
            parts(lines[3]),
            vec!["active".to_string(), "bool".to_string(), "true".to_string()]
        );
    }

    #[test]
    fn test_inspect_formatter_nested_structure() {
        let mut inner = Map::new();
        inner.insert("id".into(), Dynamic::from(7_i64));
        inner.insert("name".into(), Dynamic::from("alpha"));

        let mut event = Event::default();
        event.set_field("meta".to_string(), Dynamic::from(inner));

        let formatter = InspectFormatter::new(0);
        let output = formatter.format(&event);
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines[0], "---");
        assert_eq!(lines.len(), 5);
        assert_eq!(
            parts(lines[1]),
            vec!["meta".to_string(), "map(2)".to_string(), "{".to_string()]
        );
        assert_eq!(
            parts(lines[2]),
            vec!["id".to_string(), "int".to_string(), "7".to_string()]
        );
        assert_eq!(
            parts(lines[3]),
            vec![
                "name".to_string(),
                "string".to_string(),
                "\"alpha\"".to_string()
            ]
        );
        assert_eq!(lines[4], "}");
    }

    #[test]
    fn test_inspect_formatter_truncates_long_values() {
        let long_value = "a".repeat(120);
        let mut event = Event::default();
        event.set_field("payload".to_string(), Dynamic::from(long_value.clone()));

        let formatter = InspectFormatter::new(0);
        let output = formatter.format(&event);
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines[0], "---");
        assert_eq!(lines.len(), 2);
        let expected_truncated = format!("\"{}\"...", "a".repeat(80));
        assert_eq!(
            parts(lines[1]),
            vec![
                "payload".to_string(),
                "string".to_string(),
                expected_truncated.clone()
            ]
        );

        let verbose_formatter = InspectFormatter::new(2);
        let verbose_output = verbose_formatter.format(&event);
        let verbose_lines: Vec<&str> = verbose_output.lines().collect();
        assert_eq!(verbose_lines[0], "---");
        assert_eq!(verbose_lines.len(), 2);
        let expected_full = format!("\"{}\"", long_value);
        assert_eq!(
            parts(verbose_lines[1]),
            vec!["payload".to_string(), "string".to_string(), expected_full]
        );
        assert!(verbose_output.len() > output.len());
    }

    #[test]
    fn test_default_formatter() {
        let mut event = Event::default();
        event.set_field("level".to_string(), Dynamic::from("INFO".to_string()));
        event.set_field("user".to_string(), Dynamic::from("alice".to_string()));
        event.set_field("count".to_string(), Dynamic::from(42i64));

        let formatter = DefaultFormatter::new_with_wrapping(
            false,
            false,
            false,
            crate::config::TimestampFormatConfig::default(),
            false, // Disable wrapping for this test
            false,
            0, // No quiet mode
        ); // No colors, no brief mode, no wrapping
        let result = formatter.format(&event);

        // Check that all fields are present with proper formatting
        // Strings should be quoted with single quotes, numbers should not be
        assert!(result.contains("level='INFO'"));
        assert!(result.contains("user='alice'"));
        assert!(result.contains("count=42"));
        // Fields should be space-separated
        assert!(result.contains(" "));
    }

    #[test]
    fn test_default_formatter_uses_ts_format_hint() {
        let mut event = Event::default();
        event.set_field("ts".to_string(), Dynamic::from("2000/01/01 17.59.55,210"));
        event.set_field("msg".to_string(), Dynamic::from("hello"));

        let formatter = DefaultFormatter::new_with_wrapping(
            false,
            false,
            false,
            crate::config::TimestampFormatConfig {
                format_fields: Vec::new(),
                auto_format_all: true,
                format_as_utc: true,
                parse_format_hint: Some("%Y/%m/%d %H.%M.%S,%f".to_string()),
                parse_timezone_hint: Some("UTC".to_string()),
            },
            false,
            false,
            0,
        );

        let result = formatter.format(&event);
        assert!(result.contains("ts='2000-01-01T17:59:55.210+00:00'"));
    }

    #[test]
    fn test_default_formatter_nested_values_render_as_json() {
        let mut meta = Map::new();
        meta.insert("id".into(), Dynamic::from(7_i64));
        meta.insert("name".into(), Dynamic::from("alpha"));

        let tags: Array = vec![Dynamic::from("blue"), Dynamic::from("green")];

        let mut event = Event::default();
        event.set_field("meta".to_string(), Dynamic::from(meta));
        event.set_field("tags".to_string(), Dynamic::from(tags));

        let formatter = DefaultFormatter::new_with_wrapping(
            false,
            false,
            false,
            crate::config::TimestampFormatConfig::default(),
            false,
            false,
            0, // No quiet mode
        );
        let result = formatter.format(&event);

        assert!(result.contains("meta={\"id\":7,\"name\":\"alpha\"}"));
        assert!(result.contains("tags=[\"blue\",\"green\"]"));
    }

    #[test]
    fn test_default_formatter_pretty_nested_output() {
        let mut meta = Map::new();
        meta.insert("id".into(), Dynamic::from(7_i64));
        meta.insert("name".into(), Dynamic::from("alpha"));

        let tags: Array = vec![Dynamic::from("blue"), Dynamic::from("green")];

        let mut event = Event::default();
        event.set_field("meta".to_string(), Dynamic::from(meta));
        event.set_field("tags".to_string(), Dynamic::from(tags));

        let formatter = DefaultFormatter::new_with_wrapping(
            false,
            false,
            false,
            crate::config::TimestampFormatConfig::default(),
            false,
            true,
            0, // No quiet mode
        );
        let result = formatter.format(&event);

        assert!(result.contains("meta={\n    \"id\": 7,\n    \"name\": \"alpha\"\n  }"));
        assert!(result.contains("tags=[\n    \"blue\",\n    \"green\"\n  ]"));
    }

    #[test]
    fn test_default_formatter_brief_mode() {
        let mut event = Event::default();
        event.set_field("level".to_string(), Dynamic::from("info".to_string()));
        event.set_field("msg".to_string(), Dynamic::from("test message".to_string()));

        let formatter = DefaultFormatter::new_with_wrapping(
            false,
            false,
            true,
            crate::config::TimestampFormatConfig::default(),
            false, // Disable wrapping for this test
            false,
            0, // No quiet mode
        ); // No colors, brief mode, no wrapping
        let result = formatter.format(&event);

        // Brief mode should output only values, space-separated
        assert_eq!(result, "info test message");
    }

    #[test]
    fn test_context_markers_use_emoji_when_enabled() {
        let formatter = DefaultFormatter::new_with_wrapping(
            true,
            true,
            false,
            crate::config::TimestampFormatConfig::default(),
            false,
            false,
            0, // No quiet mode
        );

        let mut before_event = Event {
            context_type: ContextType::Before,
            ..Default::default()
        };
        before_event.set_field("msg".to_string(), Dynamic::from("before".to_string()));
        let before_line = formatter.format(&before_event);
        assert!(before_line.starts_with("\x1b[34m/\x1b[0m "));

        let mut match_event = Event {
            context_type: ContextType::Match,
            ..Default::default()
        };
        match_event.set_field("msg".to_string(), Dynamic::from("match".to_string()));
        let match_line = formatter.format(&match_event);
        assert!(match_line.starts_with("\x1b[95mâ—‰\x1b[0m "));

        let mut after_event = Event {
            context_type: ContextType::After,
            ..Default::default()
        };
        after_event.set_field("msg".to_string(), Dynamic::from("after".to_string()));
        let after_line = formatter.format(&after_event);
        assert!(after_line.starts_with("\x1b[34m\\\x1b[0m "));

        let mut overlap_event = Event {
            context_type: ContextType::Both,
            ..Default::default()
        };
        overlap_event.set_field("msg".to_string(), Dynamic::from("overlap".to_string()));
        let overlap_line = formatter.format(&overlap_event);
        assert!(overlap_line.starts_with("\x1b[36m|\x1b[0m "));
    }

    #[test]
    fn test_logfmt_formatter_basic() {
        let mut event = Event::default();
        event.set_field("level".to_string(), Dynamic::from("INFO".to_string()));
        event.set_field("msg".to_string(), Dynamic::from("Test message".to_string()));
        event.set_field("user".to_string(), Dynamic::from("alice".to_string()));
        event.set_field("status".to_string(), Dynamic::from(200i64));

        let formatter = LogfmtFormatter::new();
        let result = formatter.format(&event);

        // Should properly quote strings with spaces, leave numbers unquoted
        assert!(result.contains("level=INFO"));
        assert!(result.contains("msg=\"Test message\""));
        assert!(result.contains("user=alice"));
        assert!(result.contains("status=200"));
        // Fields should be space-separated
        assert!(result.contains(" "));
    }

    #[test]
    fn test_logfmt_formatter_quoting() {
        let mut event = Event::default();
        event.set_field("simple".to_string(), Dynamic::from("value".to_string()));
        event.set_field(
            "spaced".to_string(),
            Dynamic::from("has spaces".to_string()),
        );
        event.set_field("empty".to_string(), Dynamic::from("".to_string()));
        event.set_field(
            "quoted".to_string(),
            Dynamic::from("has\"quotes".to_string()),
        );
        event.set_field("equals".to_string(), Dynamic::from("has=sign".to_string()));

        let formatter = LogfmtFormatter::new();
        let result = formatter.format(&event);

        assert!(result.contains("simple=value")); // No quotes needed
        assert!(result.contains("spaced=\"has spaces\"")); // Quotes due to space
        assert!(result.contains("empty=\"\"")); // Quotes due to empty
        assert!(result.contains("quoted=\"has\\\"quotes\"")); // Escaped quotes
        assert!(result.contains("equals=\"has=sign\"")); // Quotes due to equals sign
    }

    #[test]
    fn test_logfmt_formatter_types() {
        let mut event = Event::default();
        event.set_field("string".to_string(), Dynamic::from("hello".to_string()));
        event.set_field("integer".to_string(), Dynamic::from(42i64));
        event.set_field("float".to_string(), Dynamic::from(2.5f64));
        event.set_field("bool_true".to_string(), Dynamic::from(true));
        event.set_field("bool_false".to_string(), Dynamic::from(false));

        let formatter = LogfmtFormatter::new();
        let result = formatter.format(&event);

        // Numbers and booleans should not be quoted
        assert!(result.contains("string=hello"));
        assert!(result.contains("integer=42"));
        assert!(result.contains("float=2.5"));
        assert!(result.contains("bool_true=true"));
        assert!(result.contains("bool_false=false"));
    }

    #[test]
    fn test_logfmt_formatter_empty_event() {
        let event = Event::default();
        let formatter = LogfmtFormatter::new();
        let result = formatter.format(&event);
        assert_eq!(result, "");
    }

    #[test]
    fn test_logfmt_formatter_key_sanitization() {
        let mut event = Event::default();
        // Test various problematic key characters
        event.set_field(
            "field with spaces".to_string(),
            Dynamic::from("value1".to_string()),
        );
        event.set_field(
            "field=with=equals".to_string(),
            Dynamic::from("value2".to_string()),
        );
        event.set_field(
            "field\twith\ttabs".to_string(),
            Dynamic::from("value3".to_string()),
        );
        event.set_field(
            "field\nwith\nnewlines".to_string(),
            Dynamic::from("value4".to_string()),
        );
        event.set_field(
            "field\rwith\rcarriage".to_string(),
            Dynamic::from("value5".to_string()),
        );
        event.set_field(
            "normal_field".to_string(),
            Dynamic::from("value6".to_string()),
        );
        event.set_field(
            "field-with-dashes".to_string(),
            Dynamic::from("value7".to_string()),
        );
        event.set_field(
            "field.with.dots".to_string(),
            Dynamic::from("value8".to_string()),
        );

        let formatter = LogfmtFormatter::new();
        let result = formatter.format(&event);

        // Keys should be sanitized by replacing problematic characters with underscores
        assert!(result.contains("field_with_spaces=value1"));
        assert!(result.contains("field_with_equals=value2"));
        assert!(result.contains("field_with_tabs=value3"));
        assert!(result.contains("field_with_newlines=value4"));
        assert!(result.contains("field_with_carriage=value5"));
        assert!(result.contains("normal_field=value6"));

        // Non-problematic characters should be preserved
        assert!(result.contains("field-with-dashes=value7"));
        assert!(result.contains("field.with.dots=value8"));

        // Ensure the result can be parsed by the logfmt parser
        let parser = crate::parsers::logfmt::LogfmtParser::new();
        let parsed = crate::pipeline::EventParser::parse(&parser, &result);
        assert!(
            parsed.is_ok(),
            "Sanitized logfmt output should be parseable: {}",
            result
        );

        let parsed_event = parsed.unwrap();
        // Verify that sanitized keys preserve the data
        assert_eq!(
            parsed_event
                .fields
                .get("field_with_spaces")
                .unwrap()
                .to_string(),
            "value1"
        );
        assert_eq!(
            parsed_event
                .fields
                .get("field_with_equals")
                .unwrap()
                .to_string(),
            "value2"
        );
        assert_eq!(
            parsed_event.fields.get("normal_field").unwrap().to_string(),
            "value6"
        );
    }

    #[test]
    fn test_sanitize_logfmt_key_function() {
        // Test the sanitize_logfmt_key function directly
        assert_eq!(sanitize_logfmt_key("normal_field"), "normal_field");
        assert_eq!(
            sanitize_logfmt_key("field with spaces"),
            "field_with_spaces"
        );
        assert_eq!(
            sanitize_logfmt_key("field=with=equals"),
            "field_with_equals"
        );
        assert_eq!(sanitize_logfmt_key("field\twith\ttabs"), "field_with_tabs");
        assert_eq!(
            sanitize_logfmt_key("field\nwith\nnewlines"),
            "field_with_newlines"
        );
        assert_eq!(
            sanitize_logfmt_key("field\rwith\rcarriage"),
            "field_with_carriage"
        );
        assert_eq!(
            sanitize_logfmt_key("field-with-dashes"),
            "field-with-dashes"
        );
        assert_eq!(sanitize_logfmt_key("field.with.dots"), "field.with.dots");
        assert_eq!(
            sanitize_logfmt_key("field_with_underscores"),
            "field_with_underscores"
        );
        assert_eq!(sanitize_logfmt_key(""), "");

        // Test edge cases
        assert_eq!(sanitize_logfmt_key("==="), "___");
        assert_eq!(sanitize_logfmt_key("   "), "___");
        assert_eq!(sanitize_logfmt_key(" = \t = \n = \r "), "_____________");
    }

    #[test]
    fn test_levelmap_formatter_emits_full_line() {
        let formatter = LevelmapFormatter::with_width(3);
        let ts = Utc.timestamp_millis_opt(0).unwrap();

        let mut event1 = Event {
            parsed_ts: Some(ts),
            ..Event::default()
        };
        event1.set_field("level".to_string(), Dynamic::from("info"));
        assert!(formatter.format(&event1).is_empty());

        let mut event2 = Event {
            parsed_ts: Some(ts),
            ..Event::default()
        };
        event2.set_field("level".to_string(), Dynamic::from("debug"));
        assert!(formatter.format(&event2).is_empty());

        let mut event3 = Event {
            parsed_ts: Some(ts),
            ..Event::default()
        };
        event3.set_field("level".to_string(), Dynamic::from("trace"));
        let line = formatter.format(&event3);
        assert_eq!(line, "1970-01-01T00:00:00.000Z idt");

        assert!(formatter.finish().is_none());

        let ts2 = Utc.timestamp_millis_opt(1_000).unwrap();
        let mut event4 = Event {
            parsed_ts: Some(ts2),
            ..Event::default()
        };
        event4.set_field("level".to_string(), Dynamic::from("warn"));
        assert!(formatter.format(&event4).is_empty());

        let trailing = formatter
            .finish()
            .expect("should flush trailing levelmap line");
        assert_eq!(trailing, "1970-01-01T00:00:01.000Z w");
    }

    #[test]
    fn test_levelmap_formatter_unknown_level() {
        let formatter = LevelmapFormatter::with_width(1);
        let ts = Utc.timestamp_millis_opt(0).unwrap();

        let event = Event {
            parsed_ts: Some(ts),
            ..Event::default()
        };

        let line = formatter.format(&event);
        assert_eq!(line, "1970-01-01T00:00:00.000Z ?");
    }

    #[test]
    fn test_hide_formatter() {
        let mut event = Event::default();
        event.set_field("level".to_string(), Dynamic::from("INFO".to_string()));
        event.set_field("msg".to_string(), Dynamic::from("Test message".to_string()));
        event.set_field("user".to_string(), Dynamic::from("alice".to_string()));

        let formatter = HideFormatter::new();
        let result = formatter.format(&event);
        assert_eq!(result, "");
    }

    #[test]
    fn test_hide_formatter_empty_event() {
        let event = Event::default();
        let formatter = HideFormatter::new();
        let result = formatter.format(&event);
        assert_eq!(result, "");
    }

    #[test]
    fn test_null_formatter_behavior() {
        // Null format uses HideFormatter, so test that it produces empty strings
        let mut event = Event::default();
        event.set_field("level".to_string(), Dynamic::from("ERROR".to_string()));
        event.set_field(
            "msg".to_string(),
            Dynamic::from("Critical error".to_string()),
        );

        let formatter = HideFormatter::new(); // Null format uses HideFormatter
        let result = formatter.format(&event);
        assert_eq!(result, ""); // Should be empty for null format
    }

    #[test]
    fn test_shared_escaping_utilities() {
        // Test escape_logfmt_string
        assert_eq!(escape_logfmt_string("simple"), "simple");
        assert_eq!(escape_logfmt_string("with\"quotes"), "with\\\"quotes");
        assert_eq!(escape_logfmt_string("with\nnewline"), "with\\nnewline");
        assert_eq!(escape_logfmt_string("with\ttab"), "with\\ttab");
        assert_eq!(escape_logfmt_string("with\\backslash"), "with\\\\backslash");

        // Test needs_logfmt_quoting
        assert!(!needs_logfmt_quoting("simple"));
        assert!(needs_logfmt_quoting("with spaces"));
        assert!(needs_logfmt_quoting(""));
        assert!(needs_logfmt_quoting("with=equals"));
        assert!(needs_logfmt_quoting("with\"quotes"));
        assert!(needs_logfmt_quoting("with\ttab"));

        // Test format_dynamic_value
        assert_eq!(
            format_dynamic_value(&Dynamic::from("test")),
            ("test".to_string(), true)
        );
        assert_eq!(
            format_dynamic_value(&Dynamic::from(42i64)),
            ("42".to_string(), false)
        );
        assert_eq!(
            format_dynamic_value(&Dynamic::from(true)),
            ("true".to_string(), false)
        );
    }

    #[test]
    fn test_csv_formatter_basic() {
        let keys = vec!["name".to_string(), "age".to_string(), "city".to_string()];
        let formatter = CsvFormatter::new(keys);

        let mut event = Event::default();
        event.set_field("name".to_string(), Dynamic::from("Alice".to_string()));
        event.set_field("age".to_string(), Dynamic::from(25i64));
        event.set_field("city".to_string(), Dynamic::from("New York".to_string()));

        let result = formatter.format(&event);

        // Should include header and data
        assert!(result.contains("name,age,city"));
        assert!(result.contains("Alice,25,New York"));
    }

    #[test]
    fn test_csv_formatter_with_quoting() {
        let keys = vec!["name".to_string(), "msg".to_string()];
        let formatter = CsvFormatter::new(keys);

        let mut event = Event::default();
        event.set_field("name".to_string(), Dynamic::from("Smith, John".to_string()));
        event.set_field(
            "msg".to_string(),
            Dynamic::from("He said \"hello\"".to_string()),
        );

        let result = formatter.format(&event);

        // Should properly quote values with commas and quotes
        assert!(result.contains("\"Smith, John\""));
        assert!(result.contains("\"He said \"\"hello\"\"\""));
    }

    #[test]
    fn test_tsv_formatter_basic() {
        let keys = vec!["name".to_string(), "age".to_string()];
        let formatter = CsvFormatter::new_tsv(keys);

        let mut event = Event::default();
        event.set_field("name".to_string(), Dynamic::from("Alice".to_string()));
        event.set_field("age".to_string(), Dynamic::from(25i64));

        let result = formatter.format(&event);

        // Should use tab separator
        assert!(result.contains("name\tage"));
        assert!(result.contains("Alice\t25"));
    }

    #[test]
    fn test_csv_formatter_no_header() {
        let keys = vec!["name".to_string(), "age".to_string()];
        let formatter = CsvFormatter::new_csv_no_header(keys);

        let mut event = Event::default();
        event.set_field("name".to_string(), Dynamic::from("Alice".to_string()));
        event.set_field("age".to_string(), Dynamic::from(25i64));

        let result = formatter.format(&event);

        // Should not include header
        assert!(!result.contains("name,age"));
        assert_eq!(result, "Alice,25");
    }

    #[test]
    fn test_csv_formatter_missing_fields() {
        let keys = vec!["name".to_string(), "age".to_string(), "city".to_string()];
        let formatter = CsvFormatter::new_csv_no_header(keys);

        let mut event = Event::default();
        event.set_field("name".to_string(), Dynamic::from("Alice".to_string()));
        // age is missing
        event.set_field("city".to_string(), Dynamic::from("Boston".to_string()));

        let result = formatter.format(&event);

        // Should have empty field for missing age
        assert_eq!(result, "Alice,,Boston");
    }

    #[test]
    fn test_csv_escaping_utilities() {
        // Test needs_csv_quoting
        assert!(!needs_csv_quoting("simple", ','));
        assert!(needs_csv_quoting("with,comma", ','));
        assert!(needs_csv_quoting("with\"quote", ','));
        assert!(needs_csv_quoting("with\nnewline", ','));
        assert!(needs_csv_quoting("", ','));
        assert!(needs_csv_quoting(" leading", ','));
        assert!(needs_csv_quoting("trailing ", ','));

        // Test with tab delimiter
        assert!(!needs_csv_quoting("with,comma", '\t'));
        assert!(needs_csv_quoting("with\ttab", '\t'));

        // Test escape_csv_value
        assert_eq!(escape_csv_value("simple", ','), "simple");
        assert_eq!(escape_csv_value("with,comma", ','), "\"with,comma\"");
        assert_eq!(escape_csv_value("with\"quote", ','), "\"with\"\"quote\"");
        assert_eq!(escape_csv_value("", ','), "\"\"");
    }

    #[test]
    fn test_default_formatter_wrapping_disabled() {
        let mut event = Event::default();
        event.set_field("level".to_string(), Dynamic::from("INFO".to_string()));
        event.set_field(
            "message".to_string(),
            Dynamic::from("This is a very long message that would normally wrap".to_string()),
        );
        event.set_field("user".to_string(), Dynamic::from("alice".to_string()));

        let formatter = DefaultFormatter::new_with_wrapping(
            false,
            false,
            false,
            crate::config::TimestampFormatConfig::default(),
            false, // wrapping disabled
            false,
            0, // No quiet mode
        );
        let result = formatter.format(&event);

        // Should be single line when wrapping is disabled
        assert!(!result.contains('\n'));
        assert!(result.contains("level='INFO'"));
        assert!(result.contains("message='This is a very long message that would normally wrap'"));
        assert!(result.contains("user='alice'"));
    }

    #[test]
    fn test_default_formatter_wrapping_enabled() {
        let mut event = Event::default();
        event.set_field("field1".to_string(), Dynamic::from("value1".to_string()));
        event.set_field("field2".to_string(), Dynamic::from("value2".to_string()));
        event.set_field(
            "very_long_field_name".to_string(),
            Dynamic::from(
                "a very long field value that will definitely cause wrapping".to_string(),
            ),
        );
        event.set_field("field4".to_string(), Dynamic::from("value4".to_string()));

        // Override terminal width for consistent testing
        let formatter = DefaultFormatter {
            colors: crate::colors::ColorScheme::new(false),
            level_keys: vec!["level"],
            brief: false,
            timestamp_formatting: crate::config::TimestampFormatConfig::default(),
            enable_wrapping: true,
            terminal_width: 50, // Small width to force wrapping
            pretty_nested: false,
            use_emoji: false,
            quiet_level: 0, // No quiet mode
        };

        let result = formatter.format(&event);

        // Should wrap when width is exceeded
        assert!(result.contains('\n'));
        assert!(result.contains("  ")); // Should have indentation

        // All fields should still be present
        assert!(result.contains("field1='value1'"));
        assert!(result.contains("field2='value2'"));
        assert!(result.contains(
            "very_long_field_name='a very long field value that will definitely cause wrapping'"
        ));
        assert!(result.contains("field4='value4'"));
    }

    #[test]
    fn test_default_formatter_wrapping_brief_mode() {
        let mut event = Event::default();
        event.set_field("field1".to_string(), Dynamic::from("short".to_string()));
        event.set_field(
            "field2".to_string(),
            Dynamic::from("this is a much longer value that should cause wrapping".to_string()),
        );
        event.set_field("field3".to_string(), Dynamic::from("end".to_string()));

        let formatter = DefaultFormatter {
            colors: crate::colors::ColorScheme::new(false),
            level_keys: vec![],
            brief: true,
            timestamp_formatting: crate::config::TimestampFormatConfig::default(),
            enable_wrapping: true,
            terminal_width: 30, // Very small width
            pretty_nested: false,
            use_emoji: false,
            quiet_level: 0, // No quiet mode
        };

        let result = formatter.format(&event);

        // Brief mode should still wrap properly
        assert!(result.contains('\n'));
        assert!(result.contains("  ")); // Should have indentation

        // In brief mode, only values are shown (no key= parts)
        assert!(result.contains("short"));
        assert!(result.contains("this is a much longer value that should cause wrapping"));
        assert!(result.contains("end"));
        assert!(!result.contains("field1="));
        assert!(!result.contains("field2="));
        assert!(!result.contains("field3="));
    }

    #[test]
    fn test_display_length_ignores_ansi_codes() {
        let formatter = DefaultFormatter::new_with_wrapping(
            false,
            false,
            false,
            crate::config::TimestampFormatConfig::default(),
            true,
            false,
            0, // No quiet mode
        );

        // Test string with ANSI color codes
        let colored_text = "\x1b[31mred text\x1b[0m";
        assert_eq!(formatter.display_length(colored_text), 8); // "red text" = 8 chars

        let plain_text = "red text";
        assert_eq!(formatter.display_length(plain_text), 8);

        // Empty string
        assert_eq!(formatter.display_length(""), 0);

        // Only ANSI codes
        assert_eq!(formatter.display_length("\x1b[31m\x1b[0m"), 0);
    }

    #[test]
    fn test_wrapping_preserves_field_boundaries() {
        let mut event = Event::default();
        event.set_field("a".to_string(), Dynamic::from("value".to_string()));
        event.set_field("b".to_string(), Dynamic::from("value".to_string()));
        event.set_field("c".to_string(), Dynamic::from("value".to_string()));

        let formatter = DefaultFormatter {
            colors: crate::colors::ColorScheme::new(false),
            level_keys: vec![],
            brief: false,
            timestamp_formatting: crate::config::TimestampFormatConfig::default(),
            enable_wrapping: true,
            terminal_width: 20, // Force wrapping
            pretty_nested: false,
            use_emoji: false,
            quiet_level: 0, // No quiet mode
        };

        let result = formatter.format(&event);

        // Should never break within a field, only between fields
        assert!(!result.contains("a='val\n  ue'")); // Would be bad
        assert!(result.contains("a='value'")); // Should be complete

        // Should have proper line structure
        let lines: Vec<&str> = result.split('\n').collect();
        assert!(lines.len() > 1); // Should have multiple lines

        // Continuation lines should be indented
        for (i, line) in lines.iter().enumerate() {
            if i > 0 && !line.is_empty() {
                assert!(
                    line.starts_with("  "),
                    "Line {} should be indented: '{}'",
                    i,
                    line
                );
            }
        }
    }

    #[test]
    fn test_default_formatter_new_constructor_enables_wrapping_by_default() {
        let mut event = Event::default();
        event.set_field("field1".to_string(), Dynamic::from("value1".to_string()));
        event.set_field(
            "very_long_field_name_that_exceeds_width".to_string(),
            Dynamic::from(
                "a very long field value that should definitely cause wrapping in most terminals"
                    .to_string(),
            ),
        );
        event.set_field("field3".to_string(), Dynamic::from("value3".to_string()));

        // Use the basic constructor (should enable wrapping by default now)
        let mut formatter = DefaultFormatter::new(
            false,
            false,
            false,
            crate::config::TimestampFormatConfig::default(),
            false,
            0, // No quiet mode
        );

        // Default constructor should have wrapping enabled
        assert!(formatter.enable_wrapping);

        // Force a small terminal width to make wrapping deterministic in tests
        formatter.terminal_width = 80;

        let result = formatter.format(&event);

        // Should wrap by default now
        assert!(
            result.contains('\n'),
            "Default constructor should enable wrapping"
        );
        assert!(
            result.contains("  "),
            "Should have indentation when wrapping"
        );

        // All fields should still be present
        assert!(result.contains("field1='value1'"));
        assert!(result.contains("very_long_field_name_that_exceeds_width="));
        assert!(result.contains("field3='value3'"));
    }

    #[test]
    fn test_gap_tracker_inserts_marker_for_large_delta() {
        let mut tracker = GapTracker::new(ChronoDuration::minutes(30), false);

        let first = Some(Utc.with_ymd_and_hms(2024, 2, 5, 11, 0, 0).unwrap());
        let second = Some(Utc.with_ymd_and_hms(2024, 2, 5, 13, 0, 0).unwrap());

        assert!(tracker.check(first).is_none());
        let marker = tracker.check(second).expect("marker line");
        assert!(marker.starts_with('_'));
        assert!(marker.ends_with('_'));
        assert!(marker.contains("time gap: 2:00:00"));
    }

    #[test]
    fn test_gap_tracker_skips_small_delta() {
        let mut tracker = GapTracker::new(ChronoDuration::hours(2), false);

        let first = Some(Utc.with_ymd_and_hms(2024, 2, 5, 11, 0, 0).unwrap());
        let second = Some(Utc.with_ymd_and_hms(2024, 2, 5, 12, 0, 0).unwrap());

        assert!(tracker.check(first).is_none());
        assert!(tracker.check(second).is_none());
    }

    #[test]
    fn test_gap_tracker_handles_missing_timestamp() {
        let mut tracker = GapTracker::new(ChronoDuration::minutes(45), false);

        assert!(tracker.check(None).is_none());

        let second = Some(Utc.with_ymd_and_hms(2024, 2, 5, 12, 0, 0).unwrap());
        assert!(tracker.check(second).is_none());

        let third = Some(Utc.with_ymd_and_hms(2024, 2, 5, 13, 0, 0).unwrap());
        let marker = tracker.check(third).expect("marker line");
        assert!(marker.contains("time gap: 1:00:00"));
        assert!(marker.starts_with('_'));
    }

    #[test]
    fn test_gap_tracker_handles_reverse_order() {
        let mut tracker = GapTracker::new(ChronoDuration::milliseconds(1), false);

        let first = Some(Utc.with_ymd_and_hms(2024, 2, 5, 11, 0, 0).unwrap());
        let earlier = Some(Utc.with_ymd_and_hms(2024, 2, 5, 10, 59, 59).unwrap());

        assert!(tracker.check(first).is_none());
        let marker = tracker.check(earlier).expect("marker for backwards jump");
        assert!(marker.contains("time gap"));
    }

    #[test]
    fn test_gap_tracker_colors_marker_when_enabled() {
        let mut tracker = GapTracker::new(ChronoDuration::minutes(30), true);

        let first = Some(Utc.with_ymd_and_hms(2024, 2, 5, 11, 0, 0).unwrap());
        let second = Some(Utc.with_ymd_and_hms(2024, 2, 5, 13, 0, 0).unwrap());

        assert!(tracker.check(first).is_none());
        let marker = tracker.check(second).expect("colored marker");
        assert!(marker.contains("\x1b[34m"));
        assert!(marker.contains("\x1b[0m"));
        assert!(marker.starts_with("\x1b[34m_"));
        let reset_index = marker.rfind("\x1b[0m").expect("reset sequence");
        assert!(marker[..reset_index].ends_with('_'));
        assert!(marker.contains("time gap: 2:00:00"));
    }

    #[test]
    fn test_gap_tracker_formats_fractional_microseconds_compactly() {
        let mut tracker = GapTracker::new(ChronoDuration::milliseconds(1), false);

        let first = Some(Utc.with_ymd_and_hms(2024, 2, 5, 11, 0, 0).unwrap());
        let second = first.map(|ts| ts + ChronoDuration::microseconds(1_230_000));

        assert!(tracker.check(first).is_none());
        let marker = tracker.check(second).expect("fractional marker");
        assert!(marker.contains("time gap: 0:00:01.23"));
    }
}