freeswitch-log-parser 0.11.0

Parser for FreeSWITCH log files — handles compressed .xz files, multi-line dumps, truncated buffers, and stateful UUID/timestamp tracking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
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
use std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::fmt::Write as _;
use std::hash::{Hash, Hasher};
use std::io::{self, Write};

use aho_corasick::{AhoCorasick, AhoCorasickBuilder};

use freeswitch_log_parser::{
    find_uuids, normalize_entry_timestamp, truncate_at_char_boundary, Block, LogLevel, MessageKind,
};

use crate::dialstring::{dial_string_of, print_dial_string};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorMode {
    Always,
    Never,
}

const RESET: &str = "\x1b[0m";
const RED: &str = "\x1b[31m";
const GREEN: &str = "\x1b[32m";
const YELLOW: &str = "\x1b[33m";
const MAGENTA: &str = "\x1b[35m";
const CYAN: &str = "\x1b[36m";
const DIM: &str = "\x1b[2m";
const DIM_YELLOW: &str = "\x1b[33;2m";
const DIM_GREEN: &str = "\x1b[32;2m";
const BRIGHT_GREEN: &str = "\x1b[92m";

fn hsl_to_rgb(h: f64, s: f64, l: f64) -> (u8, u8, u8) {
    let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
    let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
    let m = l - c / 2.0;
    let (r, g, b) = match h as u32 {
        0..=59 => (c, x, 0.0),
        60..=119 => (x, c, 0.0),
        120..=179 => (0.0, c, x),
        180..=239 => (0.0, x, c),
        240..=299 => (x, 0.0, c),
        _ => (c, 0.0, x),
    };
    (
        ((r + m) * 255.0) as u8,
        ((g + m) * 255.0) as u8,
        ((b + m) * 255.0) as u8,
    )
}

/// Stable per-UUID truecolor so each call is visually distinct across entries.
fn uuid_truecolor(uuid: &str) -> (u8, u8, u8) {
    let mut hasher = DefaultHasher::new();
    uuid.hash(&mut hasher);
    let hue = (hasher.finish() % 360) as f64;
    hsl_to_rgb(hue, 0.30, 0.82)
}

/// Split `Dialplan: <channel> <data>` into the part every line of the block
/// repeats and the part that differs. The channel never contains a space, so the
/// one after it ends the prefix.
fn split_dialplan_line(msg: &str) -> Option<(&str, &str)> {
    let tag = ["Dialplan: ", "Chatplan: "]
        .into_iter()
        .find(|t| msg.starts_with(t))?;
    let (_channel, data) = msg[tag.len()..].split_once(' ')?;
    Some((&msg[..msg.len() - data.len() - 1], data))
}

/// Drop what a continuation line repeats from the entry that owns it: its own
/// UUID, and the `Dialplan:`/`Chatplan:` channel the header already names. Every
/// line of a dialplan block carries both, which buries the verdict past column 90
/// where nothing lines up.
fn strip_repeated_prefix<'a>(line: &'a str, uuid: &str) -> &'a str {
    let rest = line
        .strip_prefix(uuid)
        .and_then(|r| r.strip_prefix(' '))
        .unwrap_or(line);
    split_dialplan_line(rest).map_or(rest, |(_, data)| data)
}

fn write_uuid(out: &mut String, uuid: &str) {
    let (r, g, b) = uuid_truecolor(uuid);
    write!(out, "\x1b[38;2;{r};{g};{b}m{uuid}{RESET}").expect("writing to a String cannot fail");
}

/// Paint UUIDs embedded in `text` with the same per-UUID color the UUID column
/// uses, so a peer leg named mid-message is recognizable at a glance. `resume`
/// restores the caller's color after each match.
fn colorize_uuids<'a>(text: &'a str, resume: &str) -> Cow<'a, str> {
    let mut hits = find_uuids(text).peekable();
    if hits.peek().is_none() {
        return Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len() + 64);
    let mut last = 0;
    for (start, uuid) in hits {
        out.push_str(&text[last..start]);
        write_uuid(&mut out, uuid);
        out.push_str(resume);
        last = start + uuid.len();
    }
    out.push_str(&text[last..]);
    Cow::Owned(out)
}

/// Paint a dialplan condition's verdict, the one thing worth spotting in a wall
/// of `Regex (PASS|FAIL)` continuation lines.
fn colorize_pass_fail<'a>(text: &'a str, resume: &str) -> Cow<'a, str> {
    if !text.contains("(PASS)") && !text.contains("(FAIL)") {
        return Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len() + 32);
    let mut rest = text;
    while let Some((idx, verdict, color)) = rest
        .find("(PASS)")
        .map(|i| (i, "(PASS)", BRIGHT_GREEN))
        .into_iter()
        .chain(rest.find("(FAIL)").map(|i| (i, "(FAIL)", RED)))
        .min_by_key(|(i, _, _)| *i)
    {
        out.push_str(&rest[..idx]);
        out.push_str(color);
        out.push_str(verdict);
        out.push_str(RESET);
        out.push_str(resume);
        rest = &rest[idx + verdict.len()..];
    }
    out.push_str(rest);
    Cow::Owned(out)
}

fn level_color(level: Option<LogLevel>) -> &'static str {
    match level {
        Some(LogLevel::Err | LogLevel::Crit | LogLevel::Alert) => RED,
        Some(LogLevel::Warning) => MAGENTA,
        Some(LogLevel::Info) => GREEN,
        Some(LogLevel::Notice) => CYAN,
        Some(LogLevel::Debug) => YELLOW,
        Some(LogLevel::Console) => GREEN,
        None => "",
    }
}

pub struct EntryPrinter {
    pub color: ColorMode,
    pub show_blocks: bool,
    pub show_session: bool,
    pub show_filename: bool,
    pub show_line_numbers: bool,
}

impl EntryPrinter {
    pub fn print_entry(
        &self,
        w: &mut dyn Write,
        entry: &freeswitch_log_parser::LogEntry,
        session: Option<&freeswitch_log_parser::SessionSnapshot>,
        filename: Option<&str>,
    ) -> io::Result<()> {
        let level = entry
            .level
            .map(|l| l.to_string())
            .unwrap_or_else(|| "-".to_string());
        let time = if entry.timestamp.len() >= 11 {
            &entry.timestamp[11..]
        } else {
            &entry.timestamp
        };

        let use_color = self.color == ColorMode::Always;
        let lc = if use_color {
            level_color(entry.level)
        } else {
            ""
        };
        let reset = if use_color { RESET } else { "" };
        let dim = if use_color { DIM } else { "" };

        // Markers carry no time, level or UUID, so the entry columns would all be
        // empty. A rule reads as what it is: a break between files or days.
        if matches!(
            entry.message_kind,
            MessageKind::FileChange | MessageKind::DateChange
        ) {
            return writeln!(w, "{dim}── {}{reset}", entry.message);
        }

        let uuid = if entry.uuid.is_empty() {
            format!("{dim}-{reset}")
        } else if use_color {
            let mut s = String::new();
            write_uuid(&mut s, &entry.uuid);
            s
        } else {
            entry.uuid.clone()
        };

        // Continuation lines print inline only when nothing else carries the
        // entry's content; a typed block or a bare count already does.
        let inline = !entry.attached.is_empty()
            && ((self.show_blocks && entry.block.is_none()) || entry.attached.len() == 1);

        // With a body to head, the channel goes on the header alone and its data
        // joins the body — otherwise the header would be the one line carrying
        // both, and the block would not read as a column.
        let (head, head_data) = match inline
            .then(|| split_dialplan_line(&entry.message))
            .flatten()
        {
            Some((channel, data)) => (channel, Some(data)),
            None => (entry.message.as_str(), None),
        };

        let msg = if use_color {
            colorize_uuids(head, lc)
        } else {
            Cow::Borrowed(head)
        };

        if let Some(fname) = filename.filter(|_| self.show_filename) {
            write!(w, "{dim}{fname}{reset} ")?;
        }

        if self.show_line_numbers {
            write!(w, "{lc}L{line:>6} ", line = entry.line_number)?;
        }

        // Time and level share the level color: a run of one severity reads as a
        // single band down the left edge. The line kind is Layer 1's business —
        // `[{mkind}]` is what a reader of a call actually wants there.
        writeln!(
            w,
            "{lc}{time:>15} {level:>7}{reset} {uuid} {lc}[{mkind}]{reset} {lc}{msg}{reset}",
            mkind = entry.message_kind,
        )?;

        if self.show_blocks {
            if let Some(block) = &entry.block {
                self.print_block(w, block, use_color)?;
            }
            if let Some(args) = dial_string_of(&entry.message_kind) {
                let (lbl, val) = if use_color { (CYAN, DIM) } else { ("", "") };
                print_dial_string(w, args, lbl, val, reset)?;
            }
        }

        if self.show_session {
            if let Some(session) = session {
                self.print_session(w, session, use_color)?;
            }
        }

        for warning in &entry.warnings {
            let wc = if use_color { MAGENTA } else { "" };
            writeln!(w, "{wc}    WARN {warning}{reset}")?;
        }

        if !entry.attached.is_empty() {
            let dim_s = if use_color { DIM } else { "" };
            // Continuation lines the parser did not fold into a typed block are
            // the entry's only content — dialplan regex verdicts, EXECUTE traces.
            // Collapsing those to a count leaves nothing readable behind.
            if inline {
                for line in head_data.into_iter().chain(&entry.attached) {
                    let line = strip_repeated_prefix(line, &entry.uuid);
                    let rendered = if use_color {
                        // Chained through Cow so a line neither pass touches —
                        // the common case — is never copied.
                        match colorize_uuids(line, dim_s) {
                            Cow::Borrowed(s) => colorize_pass_fail(s, dim_s),
                            Cow::Owned(s) => match colorize_pass_fail(&s, dim_s) {
                                Cow::Borrowed(_) => Cow::Owned(s),
                                Cow::Owned(both) => Cow::Owned(both),
                            },
                        }
                    } else {
                        Cow::Borrowed(line)
                    };
                    writeln!(w, "{dim_s}         {rendered}{reset}")?;
                }
            } else if !(self.show_blocks && entry.block.is_some()) {
                // A block already printed above is these same lines, parsed —
                // counting them again says nothing the reader cannot see.
                writeln!(
                    w,
                    "{dim_s}         ({} attached lines){reset}",
                    entry.attached.len()
                )?;
            }
        }

        Ok(())
    }

    /// The codec list, then the streams held or carrying no payload type.
    #[cfg(feature = "sdp")]
    fn sdp_summary_lines(block: &Block) -> Vec<String> {
        use freeswitch_types::sdp::SdpCodecEntry;

        let Some(Ok(codecs)) = block.sdp_codecs() else {
            return Vec::new();
        };
        let mut parts: Vec<String> = codecs
            .entries()
            .map(|e| match e {
                SdpCodecEntry::Rtp(c) => {
                    let mut s = format!("{}/{}", c.name(), c.clock_rate());
                    if let Some(ch) = c.channels() {
                        if ch > 1 {
                            s.push_str(&format!("/{ch}"));
                        }
                    }
                    s
                }
                _ => "T.38".to_string(),
            })
            .collect();
        for payload in codecs.non_codec_payloads() {
            parts.push(payload.to_string());
        }
        for u in codecs.unmapped() {
            parts.push(format!("pt{}?", u.payload_type));
        }

        // A port-0 section keeps its codecs but reaches no codec string, so it is
        // absent from the list above; naming it is how a held stream stays visible.
        let quiet: Vec<String> = codecs
            .sections()
            .iter()
            .filter_map(|s| {
                if s.port() == 0 {
                    Some(format!("held m={} port 0", s.media_type()))
                } else if s.entries().is_empty() && s.unmapped().is_empty() {
                    Some(format!("skipped m={}/{}", s.media_type(), s.proto()))
                } else {
                    None
                }
            })
            .collect();

        let mut lines = Vec::new();
        if !parts.is_empty() {
            lines.push(parts.join(", "));
        }
        if !quiet.is_empty() {
            lines.push(quiet.join(", "));
        }
        lines
    }

    fn print_block(&self, w: &mut dyn Write, block: &Block, use_color: bool) -> io::Result<()> {
        let bc = if use_color { DIM_GREEN } else { "" };
        let sc = if use_color { BRIGHT_GREEN } else { "" };
        let reset = if use_color { RESET } else { "" };

        match block {
            Block::ChannelData { fields, variables } => {
                for (name, value) in fields {
                    writeln!(w, "{bc}         field  {name}: {value}{reset}")?;
                }
                for (name, value) in variables {
                    writeln!(w, "{bc}         var    {name}: {value}{reset}")?;
                }
            }
            Block::Sdp { direction, body } => {
                writeln!(
                    w,
                    "{sc}         sdp    {direction} ({} lines){reset}",
                    body.len()
                )?;
                #[cfg(feature = "sdp")]
                for summary in Self::sdp_summary_lines(block) {
                    writeln!(w, "{sc}         sdp    {summary}{reset}")?;
                }
                for line in body {
                    writeln!(w, "{sc}         sdp    {line}{reset}")?;
                }
            }
            Block::CodecNegotiation {
                media,
                comparisons,
                matched,
                near_matched,
            } => {
                let cc = if use_color { DIM_YELLOW } else { "" };
                writeln!(
                    w,
                    "{cc}         codec  {media}: {} comparisons, {} matched, {} near{reset}",
                    comparisons.len(),
                    matched.len(),
                    near_matched.len(),
                )?;
                for (offered, local) in comparisons {
                    writeln!(w, "{cc}         codec  {offered}  vs  {local}{reset}")?;
                }
                for c in matched {
                    writeln!(w, "{cc}         codec  MATCH {c}{reset}")?;
                }
                for c in near_matched {
                    writeln!(w, "{cc}         codec  NEAR  {c}{reset}")?;
                }
            }
            _ => {
                writeln!(w, "{bc}         block  {block:?}{reset}")?;
            }
        }
        Ok(())
    }

    fn print_session(
        &self,
        w: &mut dyn Write,
        session: &freeswitch_log_parser::SessionSnapshot,
        use_color: bool,
    ) -> io::Result<()> {
        let dim = if use_color { DIM } else { "" };
        let reset = if use_color { RESET } else { "" };
        let mut parts = Vec::new();
        if let Some(ctx) = &session.dialplan_context {
            parts.push(format!("ctx={ctx}"));
        }
        if let Some(d) = &session.initial_destination {
            parts.push(format!("dest={d}"));
        }
        if let Some(state) = &session.channel_state {
            parts.push(format!("state={state}"));
        }
        if let Some(name) = &session.channel_name {
            parts.push(format!("ch={name}"));
        }
        if let Some(conf) = &session.conference {
            parts.push(format!("conf={}", conf.name));
            if let Some(id) = conf.member_id {
                parts.push(format!("member={id}"));
            }
        }
        if !parts.is_empty() {
            writeln!(w, "{dim}         session {}{reset}", parts.join(" "))?;
        }
        Ok(())
    }

    pub fn print_stats(
        &self,
        w: &mut dyn Write,
        stats: &freeswitch_log_parser::ParseStats,
        entry_count: u64,
        session_count: usize,
    ) -> io::Result<()> {
        writeln!(
            w,
            "{entry_count} entries, {} lines, {} unclassified, {session_count} sessions",
            stats.lines_processed, stats.lines_unclassified,
        )
    }

    pub fn print_unclassified(
        &self,
        w: &mut dyn Write,
        stats: &freeswitch_log_parser::ParseStats,
    ) -> io::Result<()> {
        if stats.unclassified_lines.is_empty() {
            return Ok(());
        }
        writeln!(w)?;
        writeln!(w, "unclassified lines:")?;
        for u in &stats.unclassified_lines {
            writeln!(
                w,
                "  L{}: {:?}{}",
                u.line_number,
                u.reason,
                u.data
                    .as_ref()
                    .map(|d| format!(" | {}", truncate_at_char_boundary(d, 100)))
                    .unwrap_or_default(),
            )?;
        }
        Ok(())
    }
}

/// Build a case-insensitive multi-needle matcher. One automaton scans a haystack
/// once for every needle, so a `--related` pass carrying hundreds of discovered
/// leg UUIDs costs the same per entry as a single `-u`.
fn build_matcher(needles: &[String]) -> io::Result<Option<AhoCorasick>> {
    if needles.is_empty() {
        return Ok(None);
    }
    AhoCorasickBuilder::new()
        .ascii_case_insensitive(true)
        .build(needles)
        .map(Some)
        .map_err(|e| {
            io::Error::other(format!(
                "cannot build a matcher for {} pattern(s): {e}",
                needles.len()
            ))
        })
}

/// Construction parameters for [`FilterConfig::new`]. `Default` lets call sites
/// name only the fields they set, rather than pass nine positionals where two
/// transposed `Option<String>`s would compile and silently invert a date range.
#[derive(Default)]
pub struct FilterParams {
    pub uuid: Vec<String>,
    pub uuid_strict: bool,
    pub match_blocks: bool,
    pub min_level: Option<LogLevel>,
    pub category: Vec<String>,
    pub fgrep: Option<String>,
    pub grep: Option<regex::Regex>,
    pub codec: Vec<String>,
    pub from_ts: Option<String>,
    pub until_ts: Option<String>,
}

/// The wider scope that would have admitted an entry the filter rejected on a
/// scope boundary alone. Ordered as the buckets are tried, and exclusive: an
/// entry lands in at most one, so the counts sum to what the wider run shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Hidden {
    /// The pattern is in the channel-UUID column, which pattern search skips.
    PatternInUuid,
    /// The pattern is in an attached block line, reachable with `--match-blocks`.
    PatternInBlocks,
    /// A `-u` needle is in the message or an attached line, not the UUID column.
    UuidInBody,
}

pub enum Verdict {
    Match,
    Hidden(Hidden),
    Reject,
}

#[derive(Clone, Default)]
pub struct FilterConfig {
    uuid_ac: Option<AhoCorasick>,
    /// The `-u` needles behind `uuid_ac`, kept so a suggested command can be
    /// checked against what is already in effect.
    uuid_needles: Vec<String>,
    /// Restrict UUID matching to `entry.uuid` (output pass) vs. also scanning
    /// message and attached lines (discovery pass).
    pub uuid_strict: bool,
    /// Extend fgrep/grep matching into attached/block lines, not just the message.
    pub match_blocks: bool,
    pub min_level: Option<LogLevel>,
    /// Message-kind labels; an entry matches if it carries any of them.
    pub category: Vec<String>,
    fgrep_ac: Option<AhoCorasick>,
    fgrep_needle: Option<String>,
    pub grep: Option<regex::Regex>,
    /// `grep` recompiled case-insensitively. The UUID-column probe advertises
    /// `-u`, which is case-insensitive, so probing with the case-sensitive regex
    /// would report zero for an uppercase-hex pattern against a lowercase log —
    /// the case most in need of the count.
    grep_ci: Option<regex::Regex>,
    /// Codec names, lowercased; an entry matches if its negotiation or SDP
    /// block names any of them.
    pub codec: Vec<String>,
    pub from_ts: Option<String>,
    pub until_ts: Option<String>,
}

/// Recompile a pattern with the case-insensitivity `-u` matching has, keeping
/// any inline flags the operator wrote.
fn case_insensitive(re: &regex::Regex) -> io::Result<regex::Regex> {
    regex::RegexBuilder::new(re.as_str())
        .case_insensitive(true)
        .build()
        .map_err(|e| io::Error::other(format!("cannot build a case-insensitive probe: {e}")))
}

impl FilterConfig {
    pub fn new(p: FilterParams) -> io::Result<Self> {
        Ok(FilterConfig {
            uuid_ac: build_matcher(&p.uuid)?,
            uuid_needles: p.uuid,
            uuid_strict: p.uuid_strict,
            match_blocks: p.match_blocks,
            min_level: p.min_level,
            category: p.category,
            fgrep_ac: build_matcher(p.fgrep.as_slice())?,
            fgrep_needle: p.fgrep,
            grep_ci: p.grep.as_ref().map(case_insensitive).transpose()?,
            grep: p.grep,
            codec: p.codec.iter().map(|c| c.to_lowercase()).collect(),
            from_ts: p.from_ts,
            until_ts: p.until_ts,
        })
    }

    pub fn set_uuids(&mut self, needles: &[String]) -> io::Result<()> {
        self.uuid_ac = build_matcher(needles)?;
        self.uuid_needles = needles.to_vec();
        Ok(())
    }

    pub fn set_fgrep(&mut self, needle: &str) -> io::Result<()> {
        self.fgrep_ac = build_matcher(std::slice::from_ref(&needle.to_string()))?;
        self.fgrep_needle = Some(needle.to_string());
        Ok(())
    }

    pub fn uuid_needle_count(&self) -> usize {
        self.uuid_needles.len()
    }

    /// A UUID named anywhere in the pattern, so a `PatternInUuid` report can name
    /// the command instead of only the flag — `--grep 'Hangup on <uuid>'` is the
    /// case that matters. `None` when the pattern names none, or when that UUID
    /// is already a `-u` needle and the suggestion would change nothing.
    pub fn suggested_uuid(&self) -> Option<&str> {
        let sources = self
            .fgrep_needle
            .as_deref()
            .into_iter()
            .chain(self.grep.as_ref().map(|re| re.as_str()));
        let uuid = sources.flat_map(find_uuids).map(|(_, u)| u).next()?;
        let known = self
            .uuid_needles
            .iter()
            .any(|n| n.eq_ignore_ascii_case(uuid));
        (!known).then_some(uuid)
    }

    /// A copy suited to peer-UUID discovery: category cleared (the seed term may
    /// surface under any message kind), UUID matching loosened to message bodies
    /// and attached lines so the seed is found wherever it appears.
    pub fn for_discovery(&self) -> FilterConfig {
        FilterConfig {
            uuid_strict: false,
            match_blocks: true,
            category: Vec::new(),
            ..self.clone()
        }
    }

    /// Whether the entry's media blocks name one of the wanted codecs.
    fn codec_matches(&self, entry: &freeswitch_log_parser::LogEntry) -> bool {
        let wanted = |name: &str| {
            let name = name.to_lowercase();
            self.codec.iter().any(|c| name.contains(c.as_str()))
        };
        match &entry.block {
            Some(Block::CodecNegotiation {
                comparisons,
                matched,
                near_matched,
                ..
            }) => {
                comparisons
                    .iter()
                    .any(|(o, l)| wanted(&o.name) || wanted(&l.name))
                    || matched.iter().chain(near_matched).any(|c| wanted(&c.name))
            }
            #[cfg(feature = "sdp")]
            Some(block @ Block::Sdp { .. }) => match block.sdp_codecs() {
                // Every section, not the negotiable ones: an offer on a stream the
                // peer then held is exactly what this flag is used to find.
                Some(Ok(codecs)) => {
                    codecs
                        .sections()
                        .iter()
                        .flat_map(|s| s.entries())
                        .any(|e| match e {
                            freeswitch_types::sdp::SdpCodecEntry::Rtp(c) => wanted(c.name()),
                            _ => false,
                        })
                }
                // A body that will not parse cannot claim a codec either way.
                _ => false,
            },
            _ => false,
        }
    }

    fn level_ok(&self, entry: &freeswitch_log_parser::LogEntry) -> bool {
        match (self.min_level, entry.level) {
            (Some(min), Some(level)) => level >= min,
            _ => true,
        }
    }

    fn category_ok(&self, entry: &freeswitch_log_parser::LogEntry) -> bool {
        self.category.is_empty()
            || self
                .category
                .iter()
                .any(|c| entry.message_kind.label() == c.as_str())
    }

    fn codec_ok(&self, entry: &freeswitch_log_parser::LogEntry) -> bool {
        self.codec.is_empty() || self.codec_matches(entry)
    }

    fn window_ok(&self, entry: &freeswitch_log_parser::LogEntry) -> bool {
        if (self.from_ts.is_none() && self.until_ts.is_none()) || entry.timestamp.is_empty() {
            return true;
        }
        let entry_ts = normalize_entry_timestamp(&entry.timestamp);
        if let Some(ref from) = self.from_ts {
            if entry_ts.as_str() < from.as_str() {
                return false;
            }
        }
        if let Some(ref until) = self.until_ts {
            if entry_ts.as_str() > until.as_str() {
                return false;
            }
        }
        true
    }

    /// `body` widens the UUID needles past `entry.uuid` into the message and
    /// attached lines — the scope `--related`'s discovery pass runs at.
    fn uuid_ok_scoped(&self, entry: &freeswitch_log_parser::LogEntry, body: bool) -> bool {
        match self.uuid_ac {
            None => true,
            Some(ref ac) => {
                ac.is_match(entry.uuid.as_bytes())
                    || (body
                        && (ac.is_match(entry.message.as_bytes())
                            || entry.attached.iter().any(|l| ac.is_match(l.as_bytes()))))
            }
        }
    }

    /// `--fgrep` and `--grep` are conjuncts, so the scope is parameterised once
    /// for both: widening that only one of them reaches admits nothing.
    fn pattern_ok_scoped(&self, entry: &freeswitch_log_parser::LogEntry, blocks: bool) -> bool {
        if let Some(ref ac) = self.fgrep_ac {
            let hit = ac.is_match(entry.message.as_bytes())
                || (blocks && entry.attached.iter().any(|l| ac.is_match(l.as_bytes())));
            if !hit {
                return false;
            }
        }
        if let Some(ref re) = self.grep {
            let hit = re.is_match(&entry.message)
                || (blocks && entry.attached.iter().any(|l| re.is_match(l)));
            if !hit {
                return false;
            }
        }
        true
    }

    /// Everything but the two scoped predicates: what a wider *scope* cannot
    /// bring back.
    fn others_ok(&self, entry: &freeswitch_log_parser::LogEntry) -> bool {
        self.level_ok(entry)
            && self.category_ok(entry)
            && self.codec_ok(entry)
            && self.window_ok(entry)
    }

    /// Whether the pattern sits in the channel-UUID column, asked with the
    /// semantics of the `-u` this would advertise rather than the pattern's own.
    fn pattern_in_uuid_column(&self, entry: &freeswitch_log_parser::LogEntry) -> bool {
        if let Some(ref ac) = self.fgrep_ac {
            if !ac.is_match(entry.uuid.as_bytes()) {
                return false;
            }
        }
        match self.grep_ci {
            Some(ref re) => re.is_match(&entry.uuid),
            None => true,
        }
    }

    pub fn matches(&self, entry: &freeswitch_log_parser::LogEntry) -> bool {
        self.others_ok(entry)
            && self.uuid_ok_scoped(entry, !self.uuid_strict)
            && self.pattern_ok_scoped(entry, self.match_blocks)
    }

    /// Classify an entry in one pass, so a rejection that turned only on a scope
    /// boundary can be counted under the flag that widens to it. Only entries
    /// every other predicate accepted are bucketed: a `--level` or date-window
    /// rejection is not something a wider scope would reveal, and pointing at a
    /// flag that cannot admit the entry is the silence this exists to end.
    ///
    /// An entry failing both scoped predicates is left unbucketed — no single
    /// flag brings it back — which is also what keeps the buckets exclusive.
    pub fn verdict(&self, entry: &freeswitch_log_parser::LogEntry) -> Verdict {
        if !self.others_ok(entry) {
            return Verdict::Reject;
        }
        let uuid_ok = self.uuid_ok_scoped(entry, !self.uuid_strict);
        let pattern_ok = self.pattern_ok_scoped(entry, self.match_blocks);
        match (uuid_ok, pattern_ok) {
            (true, true) => Verdict::Match,
            (true, false) => {
                if self.pattern_in_uuid_column(entry) {
                    Verdict::Hidden(Hidden::PatternInUuid)
                } else if !self.match_blocks && self.pattern_ok_scoped(entry, true) {
                    Verdict::Hidden(Hidden::PatternInBlocks)
                } else {
                    Verdict::Reject
                }
            }
            (false, true) => {
                if self.uuid_strict && self.uuid_ok_scoped(entry, true) {
                    Verdict::Hidden(Hidden::UuidInBody)
                } else {
                    Verdict::Reject
                }
            }
            (false, false) => Verdict::Reject,
        }
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use freeswitch_log_parser::{AttachedLines, LineKind, LogEntry, MessageKind};

    fn entry(uuid: &str, message: &str, attached: &[&str]) -> LogEntry {
        let mut a = AttachedLines::new();
        for l in attached {
            a.push(l);
        }
        LogEntry {
            uuid: uuid.to_string(),
            timestamp: String::new(),
            level: None,
            idle_pct: None,
            source: None,
            message: message.to_string(),
            kind: LineKind::Full,
            message_kind: MessageKind::General,
            block: None,
            attached: a,
            line_number: 0,
            warnings: Vec::new(),
        }
    }

    const PEER: &str = "11111111-2222-3333-4444-555555555555";

    fn printer(color: ColorMode, show_blocks: bool) -> EntryPrinter {
        EntryPrinter {
            color,
            show_blocks,
            show_session: false,
            show_filename: false,
            show_line_numbers: false,
        }
    }

    fn render(printer: &EntryPrinter, entry: &LogEntry) -> String {
        let mut out: Vec<u8> = Vec::new();
        printer.print_entry(&mut out, entry, None, None).unwrap();
        String::from_utf8(out).unwrap()
    }

    #[test]
    fn attached_lines_inline_under_blocks() {
        let e = entry(
            "u",
            "Dialplan: parsing",
            &["Regex (PASS) x =~ /y/", "Action set"],
        );
        let out = render(&printer(ColorMode::Never, true), &e);
        assert!(out.contains("Regex (PASS) x =~ /y/"), "{out}");
        assert!(out.contains("Action set"), "{out}");
        assert!(!out.contains("attached lines"), "{out}");
    }

    const CHAN: &str = "sofia/internal/1262@pbx.example.test:5062";

    #[test]
    fn the_channel_heads_the_block_and_every_body_line_is_data() {
        let uuid = "9865d278-537b-4d4a-af91-f836729f78f2";
        let e = entry(
            uuid,
            &format!("Dialplan: {CHAN} parsing [default->unloop] continue=false"),
            &[format!("{uuid} Dialplan: {CHAN} Regex (PASS) [unloop] break=on-false").as_str()],
        );
        let out = render(&printer(ColorMode::Never, true), &e);
        let lines: Vec<&str> = out.lines().collect();

        assert!(lines[0].ends_with(&format!("Dialplan: {CHAN}")), "{out}");
        assert_eq!(lines[1].trim(), "parsing [default->unloop] continue=false");
        assert_eq!(lines[2].trim(), "Regex (PASS) [unloop] break=on-false");
    }

    #[test]
    fn a_dialplan_line_with_no_body_keeps_its_data() {
        // Splitting a lone line would put its data on a continuation row of its own.
        let e = entry(
            "u",
            &format!("Dialplan: {CHAN} Absolute Condition [global]"),
            &[],
        );
        let out = render(&printer(ColorMode::Never, true), &e);
        assert!(
            out.trim_end().ends_with("Absolute Condition [global]"),
            "{out}"
        );
    }

    #[test]
    fn a_foreign_uuid_in_a_body_line_survives() {
        // Only the entry's own UUID is redundant; any other one is a real value.
        let e = entry(
            "u",
            &format!("Dialplan: {CHAN} parsing [a->b] continue=true"),
            &[format!("u Dialplan: {CHAN} Regex (FAIL) ${{hdr}}({PEER}) =~ /^$/").as_str()],
        );
        let out = render(&printer(ColorMode::Never, true), &e);
        assert!(out.contains(PEER), "{out}");
        assert!(!out.contains(&format!("Dialplan: {CHAN} Regex")), "{out}");
    }

    #[test]
    fn a_non_dialplan_continuation_only_loses_its_uuid() {
        let e = entry(
            "u",
            "msg",
            &["u EXECUTE [depth=0] sofia/internal/1001 bridge(sofia/gateway/gw/5551234)"],
        );
        let out = render(&printer(ColorMode::Never, false), &e);
        assert!(
            out.contains(
                "  EXECUTE [depth=0] sofia/internal/1001 bridge(sofia/gateway/gw/5551234)"
            ),
            "{out}"
        );
    }

    #[test]
    fn attached_lines_collapse_without_blocks() {
        let e = entry("u", "Dialplan: parsing", &["one", "two"]);
        let out = render(&printer(ColorMode::Never, false), &e);
        assert!(out.contains("(2 attached lines)"), "{out}");
    }

    #[test]
    fn lone_attached_line_always_inline() {
        let e = entry("u", "msg", &["the only continuation"]);
        let out = render(&printer(ColorMode::Never, false), &e);
        assert!(out.contains("the only continuation"), "{out}");
    }

    fn channel_data_entry() -> LogEntry {
        let mut e = entry(
            "u",
            "CHANNEL_DATA:",
            &["Channel-Name: [x]", "variable_a: [b]"],
        );
        e.block = Some(Block::ChannelData {
            fields: vec![("Channel-Name".into(), "x".into())],
            variables: vec![("variable_a".into(), "b".into())],
        });
        e
    }

    #[test]
    fn an_expanded_block_does_not_also_count_its_raw_lines() {
        let out = render(&printer(ColorMode::Never, true), &channel_data_entry());
        assert!(out.contains("field  Channel-Name: x"), "{out}");
        assert!(!out.contains("attached lines"), "{out}");
    }

    #[test]
    fn without_blocks_the_count_is_the_only_signal() {
        let out = render(&printer(ColorMode::Never, false), &channel_data_entry());
        assert!(out.contains("(2 attached lines)"), "{out}");
    }

    #[test]
    fn a_marker_prints_as_a_rule_not_empty_columns() {
        let mut e = entry("", "freeswitch.log.1.xz", &[]);
        e.message_kind = MessageKind::FileChange;
        let out = render(&printer(ColorMode::Never, true), &e);
        assert_eq!(out, "── freeswitch.log.1.xz\n");
    }

    #[test]
    fn embedded_uuid_gets_its_own_color() {
        let e = entry("aaaa", &format!("Peer UUID: {PEER}"), &[]);
        let out = render(&printer(ColorMode::Always, false), &e);
        let (r, g, b) = uuid_truecolor(PEER);
        assert!(
            out.contains(&format!("\x1b[38;2;{r};{g};{b}m{PEER}")),
            "{out}"
        );
    }

    #[test]
    fn embedded_uuid_left_alone_without_color() {
        let e = entry("aaaa", &format!("Peer UUID: {PEER}"), &[]);
        let out = render(&printer(ColorMode::Never, false), &e);
        assert!(out.contains(&format!("Peer UUID: {PEER}")), "{out}");
        assert!(!out.contains("\x1b["), "{out}");
    }

    #[test]
    fn pass_and_fail_are_colored_in_attached_lines() {
        let e = entry(
            "u",
            "Dialplan: parsing",
            &["Regex (PASS) a", "Regex (FAIL) b"],
        );
        let out = render(&printer(ColorMode::Always, true), &e);
        assert!(
            out.contains(&format!("{BRIGHT_GREEN}(PASS){RESET}")),
            "{out}"
        );
        assert!(out.contains(&format!("{RED}(FAIL){RESET}")), "{out}");
    }

    #[test]
    fn long_variable_values_are_not_truncated() {
        let long = "x".repeat(500);
        let mut e = entry("u", "CHANNEL_DATA:", &[]);
        e.block = Some(Block::ChannelData {
            fields: Vec::new(),
            variables: vec![("variable_sip_multipart".to_string(), long.clone())],
        });
        let out = render(&printer(ColorMode::Never, true), &e);
        assert!(out.contains(&long), "{out}");
        assert!(!out.contains("..."), "{out}");
    }

    pub fn filter(p: FilterParams) -> FilterConfig {
        FilterConfig::new(FilterParams {
            uuid_strict: true,
            ..p
        })
        .unwrap()
    }

    #[test]
    fn uuid_or_matches_any_needle() {
        let f = filter(FilterParams {
            uuid: vec!["aaaa".into(), "bbbb".into()],
            ..Default::default()
        });
        assert!(f.matches(&entry("xx-bbbb-yy", "msg", &[])));
        assert!(f.matches(&entry("aaaa-0000", "msg", &[])));
        assert!(!f.matches(&entry("cccc-0000", "msg", &[])));
    }

    #[test]
    fn uuid_match_is_case_insensitive() {
        let f = filter(FilterParams {
            uuid: vec!["AAAABBBB".into()],
            ..Default::default()
        });
        assert!(f.matches(&entry("aaaabbbb-2222-3333-4444-555555555555", "msg", &[])));
    }

    #[test]
    fn uuid_strict_ignores_message_body() {
        let mut f = filter(FilterParams {
            uuid: vec!["dead".into()],
            ..Default::default()
        });
        // strict: only the uuid field counts, not the message text
        assert!(!f.matches(&entry("0000", "peer dead leg", &[])));
        f.uuid_strict = false;
        assert!(f.matches(&entry("0000", "peer dead leg", &[])));
    }

    #[test]
    fn fgrep_into_blocks_only_with_match_blocks() {
        let mut f = filter(FilterParams {
            fgrep: Some("m=audio".into()),
            ..Default::default()
        });
        let e = entry("u", "Remote SDP:", &["v=0", "m=audio 5004 RTP/AVP 0"]);
        assert!(!f.matches(&e));
        f.match_blocks = true;
        assert!(f.matches(&e));
    }

    #[test]
    fn fgrep_is_case_insensitive() {
        let f = filter(FilterParams {
            fgrep: Some("RECEIVING INVITE".into()),
            ..Default::default()
        });
        assert!(f.matches(&entry("u", "receiving invite from 192.0.2.1", &[])));
    }

    #[test]
    fn category_matches_any_of_several() {
        let f = filter(FilterParams {
            category: vec!["execute".into(), "dialplan".into()],
            ..Default::default()
        });
        let mut e = entry("u", "msg", &[]);
        e.message_kind = MessageKind::Dialplan {
            channel: "sofia/internal/1001".to_string(),
            detail: "parsing".to_string(),
        };
        assert!(f.matches(&e));
        e.message_kind = MessageKind::General;
        assert!(!f.matches(&e));
    }

    #[test]
    fn for_discovery_clears_category_and_loosens() {
        let f = filter(FilterParams {
            category: vec!["execute".into()],
            uuid: vec!["seed".into()],
            ..Default::default()
        });
        let d = f.for_discovery();
        assert!(d.category.is_empty());
        assert!(!d.uuid_strict);
        assert!(d.match_blocks);
        // seed found in message body survives discovery despite category mismatch
        assert!(d.matches(&entry("0000", "found seed here", &[])));
    }

    fn codec_entry(names: &[&str], matched: &[&str]) -> LogEntry {
        let offer = |name: &str| {
            freeswitch_log_parser::CodecOffer::parse(
                freeswitch_log_parser::CodecMedia::Audio,
                &format!("{name}:0:8000:20:64000:1"),
            )
            .expect("token parses")
        };
        let mut e = entry("u", "Audio Codec Compare", &[]);
        e.block = Some(Block::CodecNegotiation {
            media: freeswitch_log_parser::CodecMedia::Audio,
            comparisons: names.iter().map(|n| (offer(n), offer("PCMU"))).collect(),
            matched: matched.iter().map(|n| offer(n)).collect(),
            near_matched: Vec::new(),
        });
        e
    }

    #[test]
    fn codec_filter_matches_offers_and_matches() {
        let f = filter(FilterParams {
            codec: vec!["opus".into()],
            ..Default::default()
        });
        assert!(f.matches(&codec_entry(&["opus"], &[])), "a remote offer");
        assert!(f.matches(&codec_entry(&["G722"], &["opus"])), "the winner");
        assert!(!f.matches(&codec_entry(&["G722"], &["G722"])));
    }

    #[test]
    fn codec_filter_is_case_insensitive() {
        let f = filter(FilterParams {
            codec: vec!["OPUS".into()],
            ..Default::default()
        });
        assert!(f.matches(&codec_entry(&["opus"], &[])));
    }

    /// A live audio stream, a held video one, and a stream carrying no payload type.
    #[cfg(feature = "sdp")]
    fn sdp_entry() -> LogEntry {
        let body = [
            "v=0",
            "o=- 1 1 IN IP4 192.0.2.10",
            "s=-",
            "c=IN IP4 192.0.2.10",
            "t=0 0",
            "m=audio 30000 RTP/AVP 0 101",
            "a=rtpmap:0 PCMU/8000",
            "a=rtpmap:101 telephone-event/8000",
            "a=fmtp:101 0-16",
            "m=video 0 RTP/AVP 99",
            "a=rtpmap:99 H264/90000",
            "m=application 5000 UDP/DTLS/SCTP webrtc-datachannel",
        ];
        let mut e = entry("u", "Remote SDP:", &[]);
        e.block = Some(Block::Sdp {
            direction: freeswitch_log_parser::SdpDirection::Remote,
            body: body.iter().map(|l| l.to_string()).collect(),
        });
        e
    }

    #[cfg(feature = "sdp")]
    #[test]
    fn sdp_summary_names_the_streams_that_carry_no_codec() {
        let out = render(&printer(ColorMode::Never, true), &sdp_entry());
        assert!(
            out.contains("PCMU/8000, 101 telephone-event/8000 0-16"),
            "{out}"
        );
        assert!(
            out.contains("held m=video port 0, skipped m=application/UDP/DTLS/SCTP"),
            "{out}"
        );
    }

    #[cfg(feature = "sdp")]
    #[test]
    fn codec_filter_matches_an_offer_on_a_held_stream() {
        let f = filter(FilterParams {
            codec: vec!["h264".into()],
            ..Default::default()
        });
        assert!(f.matches(&sdp_entry()));
    }

    #[test]
    fn codec_filter_ignores_entries_without_media_blocks() {
        let f = filter(FilterParams {
            codec: vec!["opus".into()],
            ..Default::default()
        });
        assert!(!f.matches(&entry("u", "opus appears only in the text", &[])));
    }

    const CALL: &str = "aaaaaaaa-1111-1111-1111-111111111111";

    fn hidden(f: &FilterConfig, e: &LogEntry) -> Option<Hidden> {
        match f.verdict(e) {
            Verdict::Hidden(h) => Some(h),
            _ => None,
        }
    }

    fn grep(pattern: &str) -> Option<regex::Regex> {
        Some(regex::Regex::new(pattern).expect("test pattern compiles"))
    }

    #[test]
    fn a_pattern_in_the_uuid_column_is_counted() {
        let f = filter(FilterParams {
            grep: grep(CALL),
            ..Default::default()
        });
        assert_eq!(
            hidden(&f, &entry(CALL, "Activating RTCP", &[])),
            Some(Hidden::PatternInUuid)
        );
    }

    #[test]
    fn the_uuid_column_probe_ignores_case() {
        let f = filter(FilterParams {
            grep: grep(&CALL.to_uppercase()),
            ..Default::default()
        });
        assert_eq!(
            hidden(&f, &entry(CALL, "Activating RTCP", &[])),
            Some(Hidden::PatternInUuid)
        );
    }

    #[test]
    fn a_pattern_in_an_attached_line_is_counted_until_match_blocks() {
        let mut f = filter(FilterParams {
            fgrep: Some("m=audio".into()),
            ..Default::default()
        });
        let e = entry("u", "Remote SDP:", &["v=0", "m=audio 5004 RTP/AVP 0"]);
        assert_eq!(hidden(&f, &e), Some(Hidden::PatternInBlocks));
        f.match_blocks = true;
        assert_eq!(hidden(&f, &e), None, "the flag is already in effect");
    }

    #[test]
    fn the_uuid_column_wins_over_the_attached_bucket() {
        let f = filter(FilterParams {
            fgrep: Some(CALL.into()),
            ..Default::default()
        });
        // An attached line naming the channel's own UUID is the common shape;
        // overlapping buckets would count it twice.
        let e = entry(CALL, "CHANNEL_DATA:", &[&format!("Unique-ID: [{CALL}]")]);
        assert_eq!(hidden(&f, &e), Some(Hidden::PatternInUuid));
    }

    #[test]
    fn a_rejection_on_another_predicate_advertises_nothing() {
        let f = filter(FilterParams {
            grep: grep(CALL),
            min_level: Some(LogLevel::Err),
            ..Default::default()
        });
        let mut e = entry(CALL, "Activating RTCP", &[]);
        e.level = Some(LogLevel::Debug);
        assert_eq!(hidden(&f, &e), None);
    }

    #[test]
    fn conjunct_patterns_widen_together_or_not_at_all() {
        let f = filter(FilterParams {
            fgrep: Some("hangup".into()),
            grep: grep(CALL),
            ..Default::default()
        });
        // Only --grep reaches the UUID column, so no single scope admits this.
        assert_eq!(hidden(&f, &entry(CALL, "Activating RTCP", &[])), None);
    }

    #[test]
    fn a_uuid_named_in_the_body_is_counted() {
        let f = filter(FilterParams {
            uuid: vec![CALL.into()],
            ..Default::default()
        });
        assert_eq!(
            hidden(&f, &entry("bbbb", &format!("Bridging to {CALL}"), &[])),
            Some(Hidden::UuidInBody)
        );
        assert_eq!(hidden(&f, &entry("bbbb", "unrelated", &[])), None);
    }

    #[test]
    fn a_uuid_inside_a_pattern_names_the_command() {
        let f = filter(FilterParams {
            grep: grep(&format!("Hangup on {CALL}")),
            ..Default::default()
        });
        assert_eq!(f.suggested_uuid(), Some(CALL));
    }

    #[test]
    fn no_command_for_a_uuid_already_being_filtered_on() {
        let f = filter(FilterParams {
            uuid: vec![CALL.to_uppercase()],
            fgrep: Some(CALL.into()),
            ..Default::default()
        });
        assert_eq!(f.suggested_uuid(), None);
        let plain = filter(FilterParams {
            fgrep: Some("receiving invite".into()),
            ..Default::default()
        });
        assert_eq!(plain.suggested_uuid(), None, "no uuid in the pattern");
    }
}