provenant-cli 1.0.11

Fast Rust scanner for licenses, copyrights, package metadata, SBOMs, and provenance data.
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
// SPDX-FileCopyrightText: nexB Inc. and others
// ScanCode is a trademark of nexB Inc.
// SPDX-FileCopyrightText: Provenant contributors
// SPDX-License-Identifier: Apache-2.0
// Derived from ScanCode Toolkit (Apache-2.0); modified. See NOTICE.

use super::binary_text::{
    extract_named_author_from_binary_line, has_binary_name_like_shape, has_excessive_at_noise,
    has_sufficient_alphabetic_content, is_binary_string_author_candidate, is_company_like_suffix,
};
use crate::copyright::{
    self, AuthorDetection, CopyrightDetection, HolderDetection, looks_like_source_code,
    prepare_text_line, refine_author, refine_copyright,
};
use crate::models::{Author, Copyright, FileInfoBuilder, Holder, LineNumber};
use regex::Regex;
use std::collections::HashSet;
use std::path::Path;
use std::sync::LazyLock;
use std::time::Duration;

pub(super) fn extract_copyright_information(
    file_info_builder: &mut FileInfoBuilder,
    path: &Path,
    text_content: &str,
    timeout_seconds: f64,
    from_binary_strings: bool,
) {
    let text_content = crate::utils::sourcemap::detection_text(path, text_content);
    let text_content = text_content.as_ref();

    if copyright::is_credits_file(path) {
        let author_detections = copyright::detect_credits_authors(text_content);
        if !author_detections.is_empty() {
            file_info_builder.authors(
                author_detections
                    .into_iter()
                    .map(|a| Author {
                        author: a.author,
                        start_line: a.start_line,
                        end_line: a.end_line,
                    })
                    .collect(),
            );
            return;
        }
    }

    let max_runtime = if timeout_seconds.is_finite() && timeout_seconds > 0.0 {
        Some(Duration::from_secs_f64(timeout_seconds))
    } else {
        None
    };

    let (copyrights, holders, authors) = copyright::detect_copyrights(text_content, max_runtime);
    let (copyrights, holders, authors) = if from_binary_strings {
        prune_binary_string_detections(text_content, copyrights, holders, authors)
    } else {
        (copyrights, holders, authors)
    };

    // Universal guard against binary garbage leaking into parties. Real copyright
    // and holder values are short and printable; a multi-kilobyte blob or a string
    // dense with replacement / non-printable bytes (e.g. a raw image or font byte
    // run) is never a legitimate notice, regardless of the detection source path.
    // The rendered copyright value is checked alongside the normalized one because
    // raw-text projection can re-expand a blob the normalized value had collapsed.
    let holders: Vec<HolderDetection> = holders
        .into_iter()
        .filter(|h| !is_binary_garbage_party_value(&h.holder))
        .collect();

    // Collect the file's lines once and reuse the slice for every detection's
    // raw-span rendering, instead of re-splitting the whole file per copyright,
    // holder, and author.
    let raw_lines: Vec<&str> = text_content.lines().collect();

    // Two distinct detections (e.g. `(c) 2012. Natural Earth` and the
    // stray-space variant `(c) 2012 . Natural Earth`) can render to the same
    // native value at the same span; collapse those exact duplicates so the file
    // does not report the same notice twice.
    let mut seen_copyrights = HashSet::new();
    file_info_builder.copyrights(
        copyrights
            .into_iter()
            .map(|c| Copyright {
                normalized_copyright: Some(c.copyright.clone()),
                copyright: render_raw_copyright_from_text(
                    text_content,
                    c.start_line,
                    c.end_line,
                    c.copyright.as_str(),
                ),
                start_line: c.start_line,
                end_line: c.end_line,
            })
            // The font-metadata-label check is applied to every copyright, not only
            // font paths: `License Description:` / `License Info URL:` are OpenType
            // name-table field labels and are never a legitimate copyright prefix in
            // real source, so rejecting them universally is safe and path-independent.
            .filter(|c| {
                let raw_span = render_raw_span(&raw_lines, c.start_line, c.end_line);
                !is_binary_garbage_party_value(&c.copyright)
                    && !is_font_metadata_label_copyright(&c.copyright)
                    && !detection_is_source_code(&c.copyright, &raw_span)
                    && !c
                        .normalized_copyright
                        .as_deref()
                        .is_some_and(is_binary_garbage_party_value)
                    && !c
                        .normalized_copyright
                        .as_deref()
                        .is_some_and(is_font_metadata_label_copyright)
            })
            .filter(|c| seen_copyrights.insert((c.copyright.clone(), c.start_line, c.end_line)))
            .collect::<Vec<Copyright>>(),
    );
    file_info_builder.holders(
        holders
            .into_iter()
            .filter(|h| {
                let raw_span = render_raw_span(&raw_lines, h.start_line, h.end_line);
                !detection_is_source_code(&h.holder, &raw_span)
            })
            .map(|h| Holder {
                holder: h.holder,
                start_line: h.start_line,
                end_line: h.end_line,
            })
            .collect::<Vec<Holder>>(),
    );
    let mut authors = authors;
    authors.extend(extract_patch_header_author_supplements(text_content));
    authors.extend(extract_comment_author_supplements(text_content));
    let mut seen_authors = HashSet::new();
    authors.retain(|author| {
        let raw_span = render_raw_span(&raw_lines, author.start_line, author.end_line);
        !is_binary_garbage_party_value(&author.author)
            && !looks_like_source_code(&author.author)
            && (!looks_like_source_code(&raw_span)
                || (has_author_contact_evidence(&author.author)
                    && raw_span_has_author_attribution(&raw_span))
                || raw_span_has_explicit_contactless_author_attribution(&raw_span)
                || (raw_span_has_author_attribution(&raw_span)
                    && span_is_in_pod_author_section(&raw_lines, author.start_line)))
            && seen_authors.insert((author.author.clone(), author.start_line, author.end_line))
    });

    file_info_builder.authors(
        authors
            .into_iter()
            .map(|a| Author {
                author: a.author,
                start_line: a.start_line,
                end_line: a.end_line,
            })
            .collect::<Vec<Author>>(),
    );
}

fn render_raw_copyright_from_text(
    text_content: &str,
    start_line: LineNumber,
    end_line: LineNumber,
    fallback: &str,
) -> String {
    let raw_lines: Vec<&str> = text_content.lines().collect();
    let start_index = start_line.get().saturating_sub(1);
    let end_index = end_line.get();
    let Some(span) = raw_lines.get(start_index..end_index) else {
        return fallback.to_string();
    };

    let rendered = span
        .iter()
        .map(|line| strip_common_comment_wrappers(line.trim()))
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join(" ");
    // Drop HTML/XML tags wrapping the notice (e.g. `<small>Copyright © 1999
    // Acme</small>`); the source-faithful projection otherwise carries the markup
    // into the value. Only edge tags are removed, so `©`, angle-bracket emails,
    // URLs, and `<year>` markers inside the notice are preserved.
    let rendered = inline_anchor_hrefs(&rendered);
    let rendered = strip_edge_html_tags(&rendered);
    // Normalize the HTML copyright entity to `(c)` so an `&copy;`-encoded notice
    // does not survive verbatim and split into a near-duplicate value. `(c)` is
    // used (rather than the `©` glyph) so the entity renders identically whether
    // it reaches the native field through the wrapper path — which re-normalizes
    // via `prepare_text_line` — or the plain projection path. Literal `©` glyphs
    // are left untouched and still preserved natively.
    let rendered = normalize_html_copyright_entity(&rendered);
    let rendered = rendered.split_whitespace().collect::<Vec<_>>().join(" ");
    // Collapse padding immediately inside a `<...>` pair so a source-spaced
    // contact such as `< florian.loitsch at inria dot fr >` renders as
    // `<florian.loitsch at inria dot fr>`, matching the unspaced `<email>` form
    // real notices normally use. Only balanced pairs are touched, so stray `<`
    // and `>` comparison operators are left alone.
    let rendered = collapse_angle_bracket_padding(&rendered);

    if rendered.is_empty() {
        fallback.to_string()
    } else if let Some(projected) = project_wrapped_copyright_value(&rendered, fallback) {
        projected
    } else if let Some(projected) = project_suspicious_native_copyright_value(&rendered) {
        projected
    } else {
        project_native_copyright_value(&rendered, fallback)
    }
}

/// Replace an anchor with an absolute attribution URL and its visible text.
///
/// Absolute URLs can identify the attributed party and are kept. Relative links
/// only navigate within the scanned document set (`dist.authors.html`, `#team`),
/// so they are markup scaffolding and contribute visible text only.
fn inline_anchor_hrefs(text: &str) -> String {
    // Quoted segments may hold a `>` (`<a title="a > b" href="...">`), so the
    // attribute run alternates quoted values with unquoted non-`>` text rather
    // than treating the first `>` as the tag end.
    static ANCHOR_TAG_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"(?is)<\s*(?P<close>/)?\s*a\b(?P<attrs>(?:"[^"]*"|'[^']*'|[^>"'])*)>"#)
            .expect("valid regex")
    });
    // Consuming each quoted value whole is what keeps a literal `href=` inside an
    // earlier attribute (`<a title="see href=elsewhere" href="real">`) from being
    // read as the anchor's own href.
    static ATTR_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r#"(?is)(?P<name>[A-Za-z_:][-A-Za-z0-9_:.]*)\s*=\s*(?:"(?P<dq>[^"]*)"|'(?P<sq>[^']*)'|(?P<bare>[^\s>]+))"#,
        )
        .expect("valid regex")
    });
    // Tidied only on values that carried an anchor, so every other native value
    // stays byte-identical.
    static SPACE_BEFORE_PUNCT_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"[ \t]+(?P<p>[,.;:)\]])").expect("valid regex"));
    static SPACE_AFTER_OPEN_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(?P<b>[(\[])[ \t]+").expect("valid regex"));
    static SPACE_RUN_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"[ \t]{2,}").expect("valid regex"));

    if !ANCHOR_TAG_RE.is_match(text) {
        return text.to_string();
    }

    let replaced = ANCHOR_TAG_RE.replace_all(text, |caps: &regex::Captures| {
        if caps.name("close").is_some() {
            return " ".to_string();
        }
        let attrs = caps.name("attrs").map(|m| m.as_str()).unwrap_or("");
        ATTR_RE
            .captures_iter(attrs)
            .find(|attr| {
                attr.name("name")
                    .is_some_and(|n| n.as_str().eq_ignore_ascii_case("href"))
            })
            .and_then(|attr| {
                attr.name("dq")
                    .or_else(|| attr.name("sq"))
                    .or_else(|| attr.name("bare"))
            })
            .filter(|url| is_absolute_attribution_href(url.as_str()))
            .map(|url| format!(" {} ", decode_html_entities(url.as_str())))
            .unwrap_or_else(|| " ".to_string())
    });

    let collapsed = SPACE_RUN_RE.replace_all(&replaced, " ");
    let tidied = SPACE_BEFORE_PUNCT_RE.replace_all(&collapsed, "$p");
    SPACE_AFTER_OPEN_RE
        .replace_all(&tidied, "$b")
        .trim()
        .to_string()
}

fn is_absolute_attribution_href(value: &str) -> bool {
    let value = value.trim();
    if value.starts_with("//") {
        return true;
    }
    let Some((scheme, _)) = value.split_once(':') else {
        return false;
    };
    matches!(
        scheme.to_ascii_lowercase().as_str(),
        "http" | "https" | "ftp" | "mailto"
    )
}

/// Decode the HTML entities an `href` can carry, so the emitted URL is the
/// anchor's real target (`?a=1&amp;b=2` and `?a=1&#38;b=2` both address
/// `?a=1&b=2`). One left-to-right pass, so a decoded `&` cannot combine with the
/// following text into a second entity.
fn decode_html_entities(value: &str) -> String {
    static ENTITY_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"(?i)&(?:#(?P<dec>[0-9]{1,7})|#x(?P<hex>[0-9a-f]{1,6})|(?P<name>amp|lt|gt|quot|apos));")
            .expect("valid regex")
    });

    if !value.contains('&') {
        return value.to_string();
    }
    ENTITY_RE
        .replace_all(value, |caps: &regex::Captures| {
            if let Some(name) = caps.name("name") {
                return match name.as_str().to_ascii_lowercase().as_str() {
                    "amp" => "&",
                    "lt" => "<",
                    "gt" => ">",
                    "quot" => "\"",
                    _ => "'",
                }
                .to_string();
            }
            let code = caps
                .name("dec")
                .and_then(|m| m.as_str().parse::<u32>().ok())
                .or_else(|| {
                    caps.name("hex")
                        .and_then(|m| u32::from_str_radix(m.as_str(), 16).ok())
                });
            match code.and_then(char::from_u32) {
                Some(ch) => ch.to_string(),
                // An unassigned code point is left as written rather than guessed at.
                None => caps[0].to_string(),
            }
        })
        .into_owned()
}

/// Strip presentational HTML tags from a source-faithful copyright value, e.g.
/// `<small>Copyright © 1999 <b>Acme</b></small>` → `Copyright © 1999 Acme`.
///
/// Only an allowlist of formatting tags is removed, matched
/// anywhere in the value (not just the ends) so nested wrappers cannot leave an
/// unbalanced interior tag behind. Quoted attribute values are consumed as part
/// of the tag, including values containing `>`. The allowlist is deliberately
/// narrow: it excludes elements such as `<label text="©...">`, whose notice can
/// live in an attribute, the semantic `<copyright>`/`<author>` wrappers handled
/// below, and angle-bracket emails/URLs/domains/`<year>` markers. The interior
/// visible text (including a literal `©`) is untouched.
fn strip_edge_html_tags(text: &str) -> String {
    static FORMATTING_TAG_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r#"(?ix)
            \s*<\s*/?\s*(?:small|span|b|i|em|strong|u|s|sub|sup|font|big|tt|code|pre|p|div|br|blockquote|q|mark|cite|abbr|samp|kbd|var|h[1-6]|li|ul|ol|td|th|tr|nav|header|footer|section|article)\b
            (?:"[^"]*"|'[^']*'|[^>"'])*
            >\s*
            "#,
        )
        .expect("valid regex")
    });
    if !text.contains('<') {
        return text.to_string();
    }
    FORMATTING_TAG_RE.replace_all(text, " ").trim().to_string()
}

/// Collapse whitespace immediately inside a balanced `<...>` pair, leaving the
/// inner text otherwise intact. `< a b >` becomes `<a b>`; unbalanced `<` / `>`
/// (comparison operators) are untouched because the pattern requires a closing
/// `>` with no intervening angle bracket.
fn collapse_angle_bracket_padding(text: &str) -> String {
    static ANGLE_PADDING_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"<[ \t]+([^<>]*?)[ \t]*>|<([^<>]*?)[ \t]+>").expect("valid regex")
    });
    if !text.contains('<') {
        return text.to_string();
    }
    ANGLE_PADDING_RE
        .replace_all(text, |caps: &regex::Captures| {
            let inner = caps
                .get(1)
                .or_else(|| caps.get(2))
                .map(|m| m.as_str())
                .unwrap_or("");
            format!("<{inner}>")
        })
        .into_owned()
}

/// Render the raw source span backing a detection so it can be tested for
/// source-code shape. Holder and author detections only carry a refined value
/// (`Region`, `Author`), which can look like an ordinary name; the underlying
/// source line (`vk::CmdCopyImage(..., &copyRegion);`,
/// `Author.objects.create(...)`) is what reveals it as code.
///
/// `raw_lines` is the file split into lines once by the caller, so this stays
/// O(span length) per detection rather than re-splitting the whole file.
fn render_raw_span(raw_lines: &[&str], start_line: LineNumber, end_line: LineNumber) -> String {
    let start_index = start_line.get().saturating_sub(1);
    let end_index = end_line.get();
    let Some(span) = raw_lines.get(start_index..end_index) else {
        return String::new();
    };

    span.iter()
        .map(|line| strip_common_comment_wrappers(line.trim()))
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Return true when a detection's refined value or its backing source span is
/// obviously source code, so it should be dropped from output.
fn detection_is_source_code(value: &str, raw_span: &str) -> bool {
    looks_like_source_code(value) || looks_like_source_code(raw_span)
}

pub(super) fn has_author_contact_evidence(author: &str) -> bool {
    if author.contains('@') {
        return true;
    }
    let lower = author.to_ascii_lowercase();
    lower.contains(" at ") && lower.contains(" dot ")
}

fn raw_span_has_author_attribution(raw_span: &str) -> bool {
    static BY_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)\bby\b").unwrap());
    BY_RE.is_match(raw_span)
}

fn raw_span_has_explicit_contactless_author_attribution(raw_span: &str) -> bool {
    static EXPLICIT_ATTRIBUTION_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?i)(?:\b(?:rewritten\s+by|(?:is|are)\s+(?:currently\s+|now\s+)?maintained\s+by|as\s+authored\s+by\s+me,|(?:documentation|code|implementation|work|text|material)\b[^\r\n]{0,80}?\b(?:taken|copied|derived|adapted|borrowed)\s+from\b[^\r\n]{1,120}?\s+by)\b|[.;]\s*(?:adapted|authored|configured|contributed|created|developed|edited|implemented|improved|modified|ported|revised|updated|written)\s+by\b)",
        )
        .expect("valid explicit contactless author attribution regex")
    });
    EXPLICIT_ATTRIBUTION_RE.is_match(raw_span)
}

fn span_is_in_pod_author_section(raw_lines: &[&str], start_line: LineNumber) -> bool {
    static POD_HEADING_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(?i)^=head\d+\b").expect("valid POD heading regex"));
    let start_index = start_line.get().saturating_sub(1).min(raw_lines.len());
    raw_lines[..start_index]
        .iter()
        .rev()
        .take(512)
        .find_map(|line| {
            let trimmed = line.trim();
            if trimmed.eq_ignore_ascii_case("=cut") {
                Some(false)
            } else if POD_HEADING_RE.is_match(trimmed) {
                Some(copyright::is_pod_author_heading(trimmed))
            } else {
                None
            }
        })
        == Some(true)
}

fn project_wrapped_copyright_value(rendered: &str, fallback: &str) -> Option<String> {
    static VALUE_LEGALCOPYRIGHT_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r#"(?ix)
            ^VALUE\s+"LegalCopyright"\s*,\s*"(?P<value>[^"]+)"
            (?:\s+"\\0")?\s*$
            "#,
        )
        .expect("valid LegalCopyright wrapper regex")
    });
    static ASSIGNMENT_COPYRIGHT_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r#"(?ix)
            ^(?:PRODUCT_COPYRIGHT|INFOPLIST_KEY_NSHumanReadableCopyright)
            \s*=\s*(?P<value>.+?)\s*;?\s*$
            "#,
        )
        .expect("valid assignment copyright wrapper regex")
    });
    static APPLICATION_LEGALESE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"(?ix)^applicationLegalese\s*:\s*(?P<value>.+?)\s*,?\s*$"#)
            .expect("valid applicationLegalese wrapper regex")
    });
    static MARKUP_TEXT_COPYRIGHT_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r#"(?ix)
            \btext\s*=\s*(?:"(?P<dq>[^"]+)"|'(?P<sq>[^']+)')
            "#,
        )
        .expect("valid markup text copyright wrapper regex")
    });
    // MSBuild project metadata element: `<Copyright>Acme © 2024</Copyright>`.
    static XML_COPYRIGHT_ELEMENT_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"(?ix)^<copyright>\s*(?P<value>[^<]+?)\s*</copyright>$"#)
            .expect("valid xml copyright element wrapper regex")
    });
    // C# assembly attribute: `[assembly: AssemblyCopyright("Copyright © 2024")]`.
    static ASSEMBLY_COPYRIGHT_ATTR_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r#"(?ix)
            ^\[\s*assembly\s*:\s*AssemblyCopyright\s*\(\s*
            "(?P<value>[^"]+)"
            \s*\)\s*\]$
            "#,
        )
        .expect("valid assembly copyright attribute wrapper regex")
    });

    let extracted = if let Some(captures) = VALUE_LEGALCOPYRIGHT_RE.captures(rendered) {
        captures
            .name("value")
            .map(|m| m.as_str().trim().to_string())
    } else if let Some(captures) = ASSIGNMENT_COPYRIGHT_RE.captures(rendered) {
        captures
            .name("value")
            .map(|m| m.as_str().trim().trim_matches(&['\'', '"'][..]).to_string())
    } else if let Some(captures) = APPLICATION_LEGALESE_RE.captures(rendered) {
        captures
            .name("value")
            .map(|m| m.as_str().trim().trim_matches(&['\'', '"'][..]).to_string())
    } else if let Some(captures) = MARKUP_TEXT_COPYRIGHT_RE.captures(rendered) {
        captures
            .name("dq")
            .or_else(|| captures.name("sq"))
            .map(|m| m.as_str().trim().to_string())
    } else if let Some(captures) = XML_COPYRIGHT_ELEMENT_RE.captures(rendered) {
        captures
            .name("value")
            .map(|m| m.as_str().trim().to_string())
    } else if let Some(captures) = ASSEMBLY_COPYRIGHT_ATTR_RE.captures(rendered) {
        captures
            .name("value")
            .map(|m| m.as_str().trim().to_string())
    } else {
        project_static_notice_literal(rendered, fallback)
    }?;

    let projected = prepare_text_line(&extracted)
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    Some(projected)
}

/// Extract the single static string literal from a declaration or assignment
/// when that literal independently refines to the detected notice. This covers
/// language-neutral metadata constants without treating generated templates,
/// concatenations, function calls, or arbitrary quoted prose as notices.
fn project_static_notice_literal(rendered: &str, fallback: &str) -> Option<String> {
    let rendered = rendered.trim().strip_suffix(';').unwrap_or(rendered.trim());
    let (prefix, value) = rendered.split_once('=')?;
    let prefix = prefix.trim();
    if prefix.is_empty()
        || prefix.ends_with(['!', '<', '>'])
        || value.contains('=')
        || prefix.contains(['(', ')', '{', '}', '?'])
        || !prefix
            .chars()
            .any(|ch| ch.is_ascii_alphabetic() || ch == '_')
    {
        return None;
    }

    let value = value.trim();
    let quote = value.chars().next().filter(|ch| matches!(ch, '\'' | '"'))?;
    let literal = value.strip_prefix(quote)?.strip_suffix(quote)?.trim();
    if literal.contains(quote) {
        return None;
    }
    let prepared = prepare_text_line(literal);
    let fallback_prepared = prepare_text_line(fallback);
    let prepared_lower = prepared.to_ascii_lowercase();
    let fallback_lower = fallback_prepared.to_ascii_lowercase();
    let same_notice = prepared_lower == fallback_lower
        || fallback_lower
            .strip_prefix("copyright ")
            .is_some_and(|without_marker| without_marker == prepared_lower)
        || refine_copyright(&prepared).is_some_and(|refined| {
            refine_copyright(&fallback_prepared).as_deref() == Some(refined.as_str())
        });
    same_notice.then(|| literal.to_string())
}

fn project_native_copyright_value(rendered: &str, fallback: &str) -> String {
    let rendered = rendered.trim();
    let fallback = fallback.trim();
    if rendered.is_empty() || fallback.is_empty() {
        return fallback.to_string();
    }

    let rendered_lower = rendered.to_ascii_lowercase();
    let fallback_lower = fallback.to_ascii_lowercase();
    let Some(start) = rendered_lower.find(&fallback_lower) else {
        // The normalized notice differs from the source only in how the
        // copyright sign is written — the refiner emits `(c)` while the source
        // carries a literal `©` (or vice versa). Relocate the notice
        // sign-insensitively and project the source-faithful raw slice, so the
        // leading/trailing prose the refiner already trimmed is not re-attached
        // by falling back to the whole raw line.
        if let Some((s, len)) = locate_ignoring_copyright_sign(&rendered_lower, &fallback_lower) {
            let base = rendered[s..s + len].trim().to_string();
            let native_suffix = rendered[s + len..].trim();
            return join_native_suffix(&base, native_suffix);
        }
        if refine_copyright(rendered).as_deref() == Some(fallback) {
            return preserve_native_suffix_for_semantic_match(rendered, fallback);
        }
        // The normalized notice was not found verbatim (e.g. punctuation differs)
        // and the span does not refine to it. A faithful raw projection stays
        // close in length to the normalized value; a span dramatically longer is
        // the notice embedded in a run-on blob — common in font name-table records
        // that pack a whole licence onto one line — so prefer the trustworthy
        // normalized value rather than emitting the blob.
        if rendered.len() > fallback.len().saturating_mul(2) + 64 {
            return fallback.to_string();
        }
        return rendered.to_string();
    };
    let end = start + fallback.len();
    let suffix = rendered[end..].trim();
    join_native_suffix(fallback, suffix)
}

/// Append a source-faithful trailing suffix to a projected copyright `base`,
/// keeping only the suffix shapes `normalize_native_suffix` sanctions (bare
/// punctuation, an `All rights reserved` tail, a confidentiality note). Any
/// other trailing text — ordinary prose the refiner already trimmed — is
/// dropped, so `base` is returned unchanged.
fn join_native_suffix(base: &str, suffix: &str) -> String {
    let Some(native_suffix) = normalize_native_suffix(suffix) else {
        return base.to_string();
    };
    if native_suffix.is_empty() {
        base.to_string()
    } else if native_suffix
        .chars()
        .next()
        .is_some_and(|ch| matches!(ch, '.' | ',' | ';' | ':'))
    {
        format!("{base}{native_suffix}")
    } else {
        format!("{base} {native_suffix}")
    }
}

/// Locate `fallback_lower` inside `rendered_lower` when the two differ only in
/// how the copyright sign is spelled — the refiner emits `(c)` while the source
/// may carry a literal `©` (or the reverse). Returns the byte offset and length
/// of the match **within `rendered_lower`** (whose offsets align with the
/// original mixed-case `rendered`, since ASCII case folding and the `©` glyph
/// are byte-length preserving), so the caller can slice the source-faithful
/// span. Returns `None` when no sign substitution locates the notice.
fn locate_ignoring_copyright_sign(
    rendered_lower: &str,
    fallback_lower: &str,
) -> Option<(usize, usize)> {
    for candidate in [
        fallback_lower.replace("(c)", "\u{00a9}"),
        fallback_lower.replace('\u{00a9}', "(c)"),
    ] {
        if candidate != fallback_lower
            && let Some(index) = rendered_lower.find(&candidate)
        {
            return Some((index, candidate.len()));
        }
    }
    None
}

fn preserve_native_suffix_for_semantic_match(rendered: &str, fallback: &str) -> String {
    let lower = rendered.to_ascii_lowercase();
    if lower.contains("all rights reserved") {
        let sep = if fallback.ends_with(['.', ',', ';', ':']) {
            ""
        } else {
            "."
        };
        return format!("{fallback}{sep} All rights reserved.");
    }

    fallback.to_string()
}

fn project_suspicious_native_copyright_value(rendered: &str) -> Option<String> {
    let lower = rendered.to_ascii_lowercase();
    let looks_suspicious = lower.ends_with(" or")
        || lower.contains(" and is licensed under ")
        || lower.contains(" are derived from ")
        || lower.contains(" it is hereby released to the")
        || lower.contains(", et al")
        || lower.contains(" cest ")
        || lower.contains(" ce?st ")
        || (lower.contains(':') && lower.contains(" edt "))
        || (lower.contains(':') && lower.contains(" cest"));
    if !looks_suspicious {
        return None;
    }

    let prepared = prepare_text_line(rendered);
    let refined = refine_copyright(&prepared)?;
    (refined != rendered.trim()).then_some(refined)
}

fn normalize_native_suffix(suffix: &str) -> Option<String> {
    static CONFIDENTIALITY_SUFFIX_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?ix)
            ^[.,;:]?\s*
            confidential
            (?:
                [\s,;:.\-]+information
              | [\s,;:.\-]+proprietary
              | [\s,;:.\-]+and[\s,;:.\-]+proprietary
            )
            \.?
            $
            ",
        )
        .expect("valid confidentiality suffix regex")
    });

    if suffix.is_empty() {
        return Some(String::new());
    }

    let normalized = suffix.split_whitespace().collect::<Vec<_>>().join(" ");
    let trimmed = normalized.trim();
    if trimmed.is_empty() {
        return Some(String::new());
    }

    let lower = trimmed.to_ascii_lowercase();
    let punctuation_only = trimmed
        .chars()
        .all(|ch| matches!(ch, '.' | ',' | ';' | ':'));
    if punctuation_only {
        return Some(trimmed.to_string());
    }

    let all_rights_variants = [
        "all rights reserved",
        ". all rights reserved",
        ", all rights reserved",
        "; all rights reserved",
        ": all rights reserved",
        "all rights reserved.",
        ". all rights reserved.",
        ", all rights reserved.",
        "; all rights reserved.",
        ": all rights reserved.",
    ];
    if all_rights_variants.contains(&lower.as_str()) {
        return Some(trimmed.to_string());
    }

    if CONFIDENTIALITY_SUFFIX_RE.is_match(trimmed) {
        return Some(trimmed.to_string());
    }

    None
}

/// Normalize the HTML copyright entity (named and numeric forms) to `(c)` so an
/// `&copy;`-encoded notice does not leak the raw entity text into the native
/// value. `(c)` keeps the rendering identical across the wrapper path (which
/// re-normalizes through `prepare_text_line`) and the plain projection path.
fn normalize_html_copyright_entity(text: &str) -> std::borrow::Cow<'_, str> {
    static COPYRIGHT_ENTITY_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"(?i)&(?:copy|#0*169|#x0*a9);").expect("valid copyright entity regex")
    });
    COPYRIGHT_ENTITY_RE.replace_all(text, "(c)")
}

/// Strip one leading run of a single-character line-comment marker: `%`
/// (Erlang, Matlab, TeX), `;` (Lisp, assembly, ini), `!` (Fortran), or `-` as
/// the pair `--` (Ada, Haskell, Lua, SQL, VHDL).
///
/// Only the marker the line actually opens on is stripped, and only across its
/// own repeated run (`%%`, `;;;`, `----`). That is what a wrapped notice needs —
/// every continuation line repeats the marker, so an unstripped one survives
/// into the middle of the value — while leaving punctuation that belongs to the
/// notice alone: in `* -- nickg at modp dot com` the `*` is scaffolding but the
/// `--` is the notice's own separator, so this pass declines the line and the
/// caller's loop removes the `*` only.
///
/// A lone leading `-` is a bullet or a date range rather than a comment, and
/// `-->` closes an XML comment, so both are left intact.
fn strip_leading_comment_marker_run(line: &str) -> &str {
    const RUN_MARKERS: [char; 4] = ['%', ';', '!', '-'];

    let Some(marker) = line.chars().next().filter(|c| RUN_MARKERS.contains(c)) else {
        return line;
    };
    let run = line.len() - line.trim_start_matches(marker).len();
    if marker == '-' && (run < 2 || line[run..].starts_with('>')) {
        return line;
    }
    line[run..].trim_start()
}

/// Strip the comment scaffolding off one raw source line so the native
/// projection carries the notice text alone.
///
/// The stripped set covers the comment markers Provenant actually meets in
/// scanned trees: the C/C++ and doc variants, block openers, XML, `*`
/// continuations, and `#` handled by the loop below, plus the single-character
/// markers handled once up front by [`strip_leading_comment_marker_run`].
///
/// Word-shaped markers (`REM`, `dnl`) and the VB `'` are deliberately absent: a
/// notice can legitimately open on a quote or an all-caps acronym holder, so
/// stripping those would eat notice text rather than scaffolding.
fn strip_common_comment_wrappers(line: &str) -> String {
    let mut trimmed = strip_leading_comment_marker_run(line.trim());

    loop {
        let next = trimmed
            .strip_prefix("///")
            .or_else(|| trimmed.strip_prefix("//!"))
            .or_else(|| trimmed.strip_prefix("//"))
            .or_else(|| trimmed.strip_prefix("/*"))
            .or_else(|| trimmed.strip_prefix("<!--"))
            .or_else(|| trimmed.strip_prefix('*'))
            .or_else(|| trimmed.strip_prefix('#'))
            .map(str::trim_start);
        let Some(next) = next else {
            break;
        };
        if next == trimmed {
            break;
        }
        trimmed = next;
    }

    trimmed = trimmed.trim_end();
    if let Some(stripped) = trimmed.strip_suffix("*/") {
        trimmed = stripped.trim_end();
    }
    if let Some(stripped) = trimmed.strip_suffix("-->") {
        trimmed = stripped.trim_end();
    }

    trimmed.to_string()
}

fn prune_binary_string_detections(
    text_content: &str,
    copyrights: Vec<CopyrightDetection>,
    holders: Vec<HolderDetection>,
    authors: Vec<AuthorDetection>,
) -> (
    Vec<CopyrightDetection>,
    Vec<HolderDetection>,
    Vec<AuthorDetection>,
) {
    let kept_copyrights: Vec<CopyrightDetection> = copyrights
        .into_iter()
        .filter(|c| is_binary_string_copyright_candidate(&c.copyright))
        .collect();

    let kept_holders: Vec<HolderDetection> = holders
        .into_iter()
        .filter(|holder| {
            kept_copyrights.iter().any(|copyright| {
                ranges_overlap(
                    holder.start_line,
                    holder.end_line,
                    copyright.start_line,
                    copyright.end_line,
                )
            })
        })
        .collect();

    let kept_authors = authors
        .into_iter()
        .filter(|author| is_binary_string_author_candidate(&author.author))
        .chain(extract_binary_string_author_supplements(text_content))
        .filter({
            let mut seen = HashSet::new();
            move |author| seen.insert(author.author.clone())
        })
        .collect();

    (kept_copyrights, kept_holders, kept_authors)
}

fn ranges_overlap(
    a_start: LineNumber,
    a_end: LineNumber,
    b_start: LineNumber,
    b_end: LineNumber,
) -> bool {
    a_start <= b_end && b_start <= a_end
}

/// Hard reject for party values (copyright / holder / author) that are obviously
/// scraped binary content rather than a human-authored notice. This is a last-line
/// correctness guard applied on every emit path: a legitimate notice is short and
/// printable, so a very long value or one dense with replacement / non-printable
/// bytes can be dropped outright without risking real source-file detections.
fn is_binary_garbage_party_value(text: &str) -> bool {
    // Longest realistic notices (multi-holder lines with URLs) stay well under
    // this bound; a value beyond it is a binary blob, not a notice.
    const MAX_PARTY_VALUE_BYTES: usize = 1_000;
    // Replacement chars come from lossy decoding of non-UTF-8 binary runs.
    const MAX_REPLACEMENT_RATIO: f64 = 0.02;
    // Non-printable controls (excluding ordinary whitespace) never appear in a
    // genuine notice but pepper binary scrapes.
    const MAX_CONTROL_RATIO: f64 = 0.02;

    let trimmed = text.trim();
    if trimmed.is_empty() {
        return false;
    }

    if trimmed.len() > MAX_PARTY_VALUE_BYTES {
        return true;
    }

    let total = trimmed.chars().count();
    let replacement = trimmed.chars().filter(|&ch| ch == '\u{FFFD}').count();
    if replacement as f64 / total as f64 > MAX_REPLACEMENT_RATIO {
        return true;
    }

    let control = trimmed
        .chars()
        .filter(|ch| ch.is_control() && !ch.is_whitespace())
        .count();
    if control as f64 / total as f64 > MAX_CONTROL_RATIO {
        return true;
    }

    false
}

/// Reject copyright values that are actually font name-table metadata lines wrapped
/// with their field label (e.g. `License Description: ...`). The license/URL text
/// of a font may embed a copyright notice, but the labeled wrapper line is metadata,
/// not a copyright statement, and license detection already owns that text.
fn is_font_metadata_label_copyright(text: &str) -> bool {
    const FONT_METADATA_LABELS: &[&str] = &["License Description:", "License Info URL:"];
    let trimmed = text.trim_start();
    // Compare on bytes so a multi-byte UTF-8 char at the slice boundary cannot panic;
    // the labels are pure ASCII, so a byte-level case-insensitive prefix is exact.
    FONT_METADATA_LABELS.iter().any(|label| {
        trimmed
            .as_bytes()
            .get(..label.len())
            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(label.as_bytes()))
    })
}

fn is_binary_string_copyright_candidate(text: &str) -> bool {
    if text
        .chars()
        .any(|ch| ch.is_control() && !ch.is_whitespace())
    {
        return false;
    }

    if contains_year(text) {
        return true;
    }

    let trimmed = text.trim();
    let lower = trimmed.to_ascii_lowercase();
    let tail = if let Some(tail) = lower.strip_prefix("copyright") {
        tail.trim()
    } else {
        lower.trim()
    };
    let original_tail = if lower.starts_with("copyright") {
        trimmed["copyright".len()..].trim()
    } else {
        trimmed
    };

    if tail.is_empty() || !has_sufficient_alphabetic_content(tail) || has_excessive_at_noise(tail) {
        return false;
    }

    if !contains_year(text) && has_suspicious_binary_digit_noise(original_tail) {
        return false;
    }

    let alpha_tokens: Vec<&str> = tail
        .split_whitespace()
        .filter(|token| token.chars().any(|c| c.is_alphabetic()))
        .collect();

    if alpha_tokens.len() <= 1 {
        return has_explicit_copyright_marker(text)
            && alpha_tokens.iter().any(|token| {
                is_company_like_suffix(token.trim_matches(|c: char| !c.is_alphanumeric()))
            });
    }

    if !has_explicit_copyright_marker(text) {
        return false;
    }

    if original_tail.chars().any(|ch| ch.is_ascii_digit()) {
        return has_plausible_digit_bearing_holder(original_tail);
    }

    has_binary_name_like_shape(original_tail)
}

fn extract_binary_string_author_supplements(text_content: &str) -> Vec<AuthorDetection> {
    let mut authors = Vec::new();

    for (line_index, line) in text_content.lines().enumerate() {
        if let Some(author) = extract_named_author_from_binary_line(line) {
            authors.push(AuthorDetection {
                author,
                start_line: LineNumber::from_0_indexed(line_index),
                end_line: LineNumber::from_0_indexed(line_index),
            });
        }
    }

    authors
}

fn has_suspicious_binary_digit_noise(text: &str) -> bool {
    let tokens: Vec<&str> = text
        .split_whitespace()
        .filter(|token| !token.is_empty())
        .collect();
    if tokens.is_empty() {
        return false;
    }

    let digit_tokens: Vec<&str> = tokens
        .iter()
        .copied()
        .filter(|token| token.chars().any(|ch| ch.is_ascii_digit()))
        .collect();
    if digit_tokens.is_empty() {
        return false;
    }

    let weak_digit_tokens = digit_tokens
        .iter()
        .filter(|token| token.chars().filter(|ch| ch.is_ascii_alphabetic()).count() < 2)
        .count();
    let has_symbolic_token = tokens.iter().any(|token| {
        token.chars().any(|ch| {
            !ch.is_ascii_alphanumeric()
                && !matches!(ch, '.' | '\'' | '&' | '-' | '_' | ',' | '(' | ')')
        })
    });

    (has_symbolic_token && weak_digit_tokens > 0)
        || (digit_tokens.len() >= 2 && weak_digit_tokens == digit_tokens.len())
}

fn has_plausible_digit_bearing_holder(text: &str) -> bool {
    let tokens: Vec<&str> = text
        .split_whitespace()
        .filter(|token| token.chars().any(|ch| ch.is_ascii_alphabetic()))
        .collect();
    if tokens.is_empty() {
        return false;
    }

    let has_company_suffix = tokens
        .iter()
        .any(|token| is_company_like_suffix(token.trim_matches(|ch: char| !ch.is_alphanumeric())));
    let uppercase_like = tokens
        .iter()
        .filter(|token| {
            token
                .chars()
                .find(|ch| ch.is_ascii_alphabetic())
                .is_some_and(|ch| ch.is_ascii_uppercase())
        })
        .count();
    let strong_digit_token = tokens.iter().any(|token| {
        token.chars().any(|ch| ch.is_ascii_digit())
            && token.chars().filter(|ch| ch.is_ascii_alphabetic()).count() >= 2
    });

    strong_digit_token && (has_company_suffix || uppercase_like >= 1)
}

fn extract_patch_header_author_supplements(text_content: &str) -> Vec<AuthorDetection> {
    static PATCH_AUTHOR_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?i)^(?:from:|patch by|signed-off-by:|co-developed-by:|authored-by:)\s+(?P<author>[^<\n]+<[^>]+>)\s*$",
        )
        .expect("valid patch header author regex")
    });

    text_content
        .lines()
        .enumerate()
        .filter_map(|(line_index, line)| {
            let captures = PATCH_AUTHOR_RE.captures(line.trim())?;
            let author = captures.name("author")?.as_str().trim();
            let author = refine_author(author)?;
            Some(AuthorDetection {
                author,
                start_line: LineNumber::from_0_indexed(line_index),
                end_line: LineNumber::from_0_indexed(line_index),
            })
        })
        .collect()
}

fn extract_comment_author_supplements(text_content: &str) -> Vec<AuthorDetection> {
    static COMMENT_AUTHOR_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?i)\b(?:written|edited|modified|updated|originally)\s+by\s+(?P<author>[^<\n]+<\s*(?:[^>\s]+@[^>\s]+|https?://[^>\s]+|[^>\n]*\bat\b[^>\n]*)\s*>)\s*\.?$|^(?:[#;/*!\-\s]+)?(?:[^<\n]*?\bby\s+(?P<author2>[^<\n]+<\s*(?:[^>\s]+@[^>\s]+|https?://[^>\s]+|[^>\n]*\bat\b[^>\n]*)\s*>))\s*\.?$|^(?:[#;/*!\-\s]+)?author:\s*(?P<author3>[^<\n]+<\s*(?:[^>\s]+@[^>\s]+|https?://[^>\s]+|[^>\n]*\bat\b[^>\n]*)\s*>)\s*\.?$",
        )
        .expect("valid comment author regex")
    });
    static COMMENT_PAREN_CONTACT_AUTHOR_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?i)\b(?:written|edited|modified|updated|originally)\s+by\s+(?P<name>[^()\n]+?)\s*\(\s*(?P<contact>(?:[^)\s]+@[^)\s]+|https?://[^)\s]+))\s*\)\s*\.?$|^(?:[#;/*!\-\s]+)?(?:[^()\n]*?\bby\s+(?P<name2>[^()\n]+?)\s*\(\s*(?P<contact2>(?:[^)\s]+@[^)\s]+|https?://[^)\s]+))\s*\))\s*\.?$",
        )
        .expect("valid parenthesized contact author regex")
    });
    static DOCKER_MAINTAINER_LABEL_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"(?i)^label\s+maintainer\s*=\s*[\"']?(?P<author>[^\"'\n]+<[^>]+>)[\"']?\s*$"#)
            .expect("valid docker maintainer label regex")
    });
    static EMAIL_PAREN_NAME_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"(?i)(?P<email>[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63})\s*\((?P<name>[^)]+)\)")
            .expect("valid email paren name regex")
    });

    let mut authors = Vec::new();

    for (line_index, line) in text_content.lines().enumerate() {
        let trimmed = line.trim();
        let normalized = normalize_comment_author_line(trimmed);
        let line_number = LineNumber::from_0_indexed(line_index);
        let is_comment_like = looks_like_comment_author_source_line(trimmed);

        if is_comment_like
            && let Some(captures) = COMMENT_AUTHOR_RE.captures(&normalized)
            && let Some(author) = captures
                .name("author")
                .or_else(|| captures.name("author2"))
                .or_else(|| captures.name("author3"))
                .map(|m| m.as_str().trim())
            && let Some(author) = refine_author(&normalize_comment_author_candidate(author))
        {
            authors.push(AuthorDetection {
                author,
                start_line: line_number,
                end_line: line_number,
            });
        }

        if is_comment_like
            && let Some(captures) = COMMENT_PAREN_CONTACT_AUTHOR_RE.captures(&normalized)
        {
            let name = captures
                .name("name")
                .or_else(|| captures.name("name2"))
                .map(|m| m.as_str().trim());
            let contact = captures
                .name("contact")
                .or_else(|| captures.name("contact2"))
                .map(|m| m.as_str().trim());

            if let (Some(name), Some(contact)) = (name, contact) {
                let author = normalize_parenthesized_contact_author(name, contact);
                let Some(author) = refine_author(&author) else {
                    continue;
                };
                authors.push(AuthorDetection {
                    author,
                    start_line: line_number,
                    end_line: line_number,
                });
            }
        }

        if let Some(captures) = DOCKER_MAINTAINER_LABEL_RE.captures(trimmed)
            && let Some(author) = captures.name("author").map(|m| m.as_str().trim())
            && let Some(author) = refine_author(author)
        {
            authors.push(AuthorDetection {
                author,
                start_line: line_number,
                end_line: line_number,
            });
        }

        if !is_comment_like {
            continue;
        }

        for captures in EMAIL_PAREN_NAME_RE.captures_iter(trimmed) {
            let Some(email) = captures.name("email").map(|m| m.as_str().trim()) else {
                continue;
            };
            let Some(name) = captures.name("name").map(|m| m.as_str().trim()) else {
                continue;
            };
            if name.is_empty() {
                continue;
            }
            let author = format!("{name} <{email}>");
            let Some(author) = refine_author(&author) else {
                continue;
            };
            authors.push(AuthorDetection {
                author,
                start_line: line_number,
                end_line: line_number,
            });
        }
    }

    authors
}

fn looks_like_comment_author_source_line(line: &str) -> bool {
    let trimmed = line.trim_start();
    trimmed.starts_with('#')
        || trimmed.starts_with("//")
        || trimmed.starts_with("/*")
        || trimmed.starts_with('*')
        || trimmed.starts_with(';')
        || trimmed.starts_with("--")
        || trimmed.starts_with("<!--")
}

fn normalize_comment_author_line(line: &str) -> String {
    line.trim()
        .trim_start_matches("<!--")
        .trim_start()
        .trim_end_matches("*/")
        .trim_end_matches("-->")
        .trim()
        .to_string()
}

fn normalize_comment_author_candidate(author: &str) -> String {
    static ANGLE_URL_AUTHOR_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^(?P<name>[^<>]+?)\s*<\s*(?P<url>https?://[^>\s]+)\s*>\s*$")
            .expect("valid angle url author regex")
    });

    let trimmed = author.trim().trim_end_matches('.').trim();
    if let Some(captures) = ANGLE_URL_AUTHOR_RE.captures(trimmed) {
        let name = captures
            .name("name")
            .map(|m| m.as_str().trim())
            .unwrap_or(trimmed);
        let url = captures
            .name("url")
            .map(|m| m.as_str().trim_end_matches('/'))
            .unwrap_or(trimmed);
        return format!("{name} ({url})");
    }

    trimmed.to_string()
}

fn normalize_parenthesized_contact_author(name: &str, contact: &str) -> String {
    let normalized_name = name.trim().trim_end_matches('.').trim();
    let normalized_contact = if contact.starts_with("http://") || contact.starts_with("https://") {
        contact.trim_end_matches('/')
    } else {
        contact.trim()
    };
    format!("{normalized_name} ({normalized_contact})")
}

fn has_explicit_copyright_marker(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();
    lower.contains("(c)") || lower.contains('©') || lower.contains("copr")
}

fn contains_year(text: &str) -> bool {
    let bytes = text.as_bytes();
    bytes.windows(4).any(|window| {
        window.iter().all(|b| b.is_ascii_digit())
            && matches!(window[0], b'1' | b'2')
            && matches!(window[1], b'9' | b'0')
    })
}

#[cfg(test)]
#[path = "copyright_test.rs"]
mod tests;