provenant-cli 0.0.31

Rust-based ScanCode-compatible scanner for licenses, package metadata, SBOMs, and provenance data.
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
// SPDX-FileCopyrightText: Provenant contributors
// SPDX-License-Identifier: Apache-2.0

//! Parse .LICENSE and .RULE files.
//!
//! This module provides two-stage loading:
//! 1. Loader-stage: Parse files into `LoadedRule` and `LoadedLicense`
//! 2. Build-stage: Convert to runtime `Rule` and `License` (deprecated filtering, etc.)
//!
//! The loader-stage functions (`parse_rule_to_loaded`, `parse_license_to_loaded`,
//! `load_loaded_rules_from_directory`, `load_loaded_licenses_from_directory`) return
//! all entries including deprecated ones. Deprecated filtering is a build-stage concern.

use crate::license_detection::index::{loaded_license_to_license, loaded_rule_to_rule};
use crate::license_detection::models::{License, LoadedLicense, LoadedRule, Rule};
use anyhow::{Context, Result, anyhow};
use log::warn;
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::sync::LazyLock;

static FM_BOUNDARY: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)^-{3,}\s*$").expect("Invalid frontmatter regex"));

fn deserialize_yes_no_bool<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize, Serialize)]
    #[serde(untagged)]
    enum YesNoOrBool {
        String(String),
        Bool(bool),
    }

    match YesNoOrBool::deserialize(deserializer)? {
        YesNoOrBool::Bool(b) => Ok(Some(b)),
        YesNoOrBool::String(s) => {
            let lower = s.to_lowercase();
            if lower == "yes" || lower == "true" || lower == "1" {
                Ok(Some(true))
            } else if lower == "no" || lower == "false" || lower == "0" {
                Ok(Some(false))
            } else {
                Ok(None)
            }
        }
    }
}

trait ParseNumber {
    fn as_u8(&self) -> Option<u8>;
}

impl ParseNumber for yaml_serde::Number {
    fn as_u8(&self) -> Option<u8> {
        self.as_i64()
            .and_then(|n| u8::try_from(n).ok())
            .or_else(|| {
                self.as_f64().and_then(|f| {
                    if f >= 0.0 && f <= f64::from(u8::MAX) {
                        // truncation toward zero is intentional (e.g. 90.5 → 90)
                        #[allow(clippy::cast_sign_loss)]
                        Some(f as u8)
                    } else {
                        None
                    }
                })
            })
    }
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct LicenseFrontmatter {
    #[serde(default)]
    key: Option<String>,

    #[serde(default)]
    short_name: Option<String>,

    #[serde(default)]
    name: Option<String>,

    #[serde(default)]
    category: Option<String>,

    #[serde(default)]
    owner: Option<String>,

    #[serde(default)]
    homepage_url: Option<String>,

    #[serde(default)]
    notes: Option<String>,

    #[serde(default)]
    spdx_license_key: Option<String>,

    #[serde(default)]
    other_spdx_license_keys: Option<Vec<String>>,

    #[serde(default)]
    osi_license_key: Option<String>,

    #[serde(default)]
    text_urls: Option<Vec<String>>,

    #[serde(default)]
    osi_url: Option<String>,

    #[serde(default)]
    faq_url: Option<String>,

    #[serde(default)]
    other_urls: Option<Vec<String>>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_deprecated: Option<bool>,

    #[serde(default)]
    replaced_by: Option<Vec<String>>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_exception: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_unknown: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_generic: Option<bool>,

    #[serde(default)]
    minimum_coverage: Option<yaml_serde::Number>,

    #[serde(default)]
    standard_notice: Option<String>,

    #[serde(default)]
    ignorable_copyrights: Option<Vec<String>>,

    #[serde(default)]
    ignorable_holders: Option<Vec<String>>,

    #[serde(default)]
    ignorable_authors: Option<Vec<String>>,

    #[serde(default)]
    ignorable_urls: Option<Vec<String>>,

    #[serde(default)]
    ignorable_emails: Option<Vec<String>>,
}

/// Parsed rule file content, split into frontmatter and text.
struct ParsedRuleFile {
    yaml_content: String,
    text_content: String,
    has_stored_minimum_coverage: bool,
}

/// Parsed license file content, split into frontmatter and text.
struct ParsedLicenseFile {
    yaml_content: String,
    text_content: String,
}

/// Parse file content into frontmatter and text sections.
///
/// Returns `ParsedRuleFile` with yaml_content, text_content, and metadata.
/// The `path` parameter is used for error messages only.
fn parse_file_content(content: &str, path: &Path) -> Result<ParsedRuleFile> {
    if content.len() < 6 {
        return Err(anyhow!("File content too short: {}", path.display()));
    }

    let parts: Vec<&str> = FM_BOUNDARY.splitn(content, 3).collect();

    if parts.len() < 3 {
        let trimmed = content.trim();
        if trimmed.is_empty() {
            return Err(anyhow!(
                "File is empty or has no content: {}",
                path.display()
            ));
        }
        return Err(anyhow!("File missing delimiter '---': {}", path.display()));
    }

    let yaml_content = parts
        .get(1)
        .ok_or_else(|| anyhow!("Missing YAML frontmatter in {}", path.display()))?
        .to_string();
    let text_content = parts
        .get(2)
        .ok_or_else(|| {
            anyhow!(
                "Missing text content after frontmatter in {}",
                path.display()
            )
        })?
        .trim_start_matches('\n')
        .trim()
        .to_string();

    let frontmatter_value: yaml_serde::Value =
        yaml_serde::from_str(&yaml_content).map_err(|e| {
            anyhow!(
                "Failed to parse frontmatter YAML in {}: {}\nContent was:\n{}",
                path.display(),
                e,
                yaml_content
            )
        })?;

    let has_stored_minimum_coverage = frontmatter_value.as_mapping().is_some_and(|mapping| {
        mapping.contains_key(yaml_serde::Value::String("minimum_coverage".to_string()))
    });

    Ok(ParsedRuleFile {
        yaml_content,
        text_content,
        has_stored_minimum_coverage,
    })
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct RuleFrontmatter {
    #[serde(default)]
    license_expression: Option<String>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_license_text: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_license_notice: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_license_reference: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_license_tag: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_license_intro: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_license_clue: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_false_positive: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_required_phrase: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    skip_for_required_phrase_generation: Option<bool>,

    #[serde(default)]
    relevance: Option<yaml_serde::Number>,

    #[serde(default)]
    minimum_coverage: Option<yaml_serde::Number>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_continuous: Option<bool>,

    #[serde(default, deserialize_with = "deserialize_yes_no_bool")]
    is_deprecated: Option<bool>,

    #[serde(default)]
    referenced_filenames: Option<Vec<String>>,

    #[serde(default)]
    replaced_by: Option<Vec<String>>,

    #[serde(default)]
    ignorable_urls: Option<Vec<String>>,

    #[serde(default)]
    ignorable_emails: Option<Vec<String>>,

    #[serde(default)]
    notes: Option<String>,

    #[serde(default)]
    ignorable_copyrights: Option<Vec<String>>,

    #[serde(default)]
    ignorable_holders: Option<Vec<String>>,

    #[serde(default)]
    ignorable_authors: Option<Vec<String>>,

    #[serde(default)]
    language: Option<String>,
}

fn parse_rule_source_to_loaded(
    identifier: &str,
    content: &str,
    source_path: &Path,
) -> Result<LoadedRule> {
    let identifier = LoadedRule::derive_identifier(
        source_path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(identifier),
    );

    let parsed = parse_file_content(content, source_path)?;

    if parsed.text_content.is_empty() {
        return Err(anyhow!(
            "Rule file has empty text content: {}",
            source_path.display()
        ));
    }

    let fm: RuleFrontmatter = yaml_serde::from_str(&parsed.yaml_content).map_err(|e| {
        anyhow!(
            "Failed to parse rule frontmatter YAML in {}: {}\nContent was:\n{}",
            source_path.display(),
            e,
            parsed.yaml_content
        )
    })?;

    let is_false_positive = fm.is_false_positive.unwrap_or(false);

    let rule_kind = LoadedRule::derive_rule_kind(
        fm.is_license_text.unwrap_or(false),
        fm.is_license_notice.unwrap_or(false),
        fm.is_license_reference.unwrap_or(false),
        fm.is_license_tag.unwrap_or(false),
        fm.is_license_intro.unwrap_or(false),
        fm.is_license_clue.unwrap_or(false),
    )
    .map_err(|e| {
        anyhow!(
            "Rule file has invalid rule-kind flags: {}: {}",
            source_path.display(),
            e
        )
    })?;

    LoadedRule::validate_rule_kind_flags(rule_kind, is_false_positive).map_err(|e| {
        anyhow!(
            "Rule file has invalid flags: {}: {}",
            source_path.display(),
            e
        )
    })?;

    let license_expression = LoadedRule::normalize_license_expression(
        fm.license_expression.as_deref(),
        is_false_positive,
    )
    .map_err(|e| {
        anyhow!(
            "Rule file has invalid license_expression: {}: {}",
            source_path.display(),
            e
        )
    })?;

    let relevance = fm.relevance.and_then(|n| n.as_u8());

    let minimum_coverage = fm.minimum_coverage.and_then(|n| n.as_u8());

    Ok(LoadedRule {
        identifier,
        license_expression,
        text: parsed.text_content,
        rule_kind,
        is_false_positive,
        is_required_phrase: fm.is_required_phrase.unwrap_or(false),
        skip_for_required_phrase_generation: fm
            .skip_for_required_phrase_generation
            .unwrap_or(false),
        relevance,
        minimum_coverage,
        has_stored_minimum_coverage: parsed.has_stored_minimum_coverage,
        is_continuous: fm.is_continuous.unwrap_or(false),
        referenced_filenames: LoadedRule::normalize_optional_list(
            fm.referenced_filenames.as_deref(),
        ),
        ignorable_urls: LoadedRule::normalize_optional_list(fm.ignorable_urls.as_deref()),
        ignorable_emails: LoadedRule::normalize_optional_list(fm.ignorable_emails.as_deref()),
        ignorable_copyrights: LoadedRule::normalize_optional_list(
            fm.ignorable_copyrights.as_deref(),
        ),
        ignorable_holders: LoadedRule::normalize_optional_list(fm.ignorable_holders.as_deref()),
        ignorable_authors: LoadedRule::normalize_optional_list(fm.ignorable_authors.as_deref()),
        language: LoadedRule::normalize_optional_string(fm.language.as_deref()),
        notes: LoadedRule::normalize_optional_string(fm.notes.as_deref()),
        is_deprecated: fm.is_deprecated.unwrap_or(false),
        replaced_by: fm.replaced_by.unwrap_or_default(),
    })
}

/// Parse a .RULE file into a `LoadedRule` (loader-stage).
///
/// This function parses the file and returns a `LoadedRule` with normalized data.
/// Deprecated entries are included - filtering is a build-stage concern.
pub fn parse_rule_to_loaded(path: &Path) -> Result<LoadedRule> {
    let content = fs::read_to_string(path)
        .with_context(|| format!("Failed to read rule file: {}", path.display()))?;
    parse_rule_source_to_loaded(
        path.file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown.RULE"),
        &content,
        path,
    )
}

/// Parse a rule from in-memory ScanCode-style `.RULE` content.
pub fn parse_rule_str_to_loaded(identifier: &str, content: &str) -> Result<LoadedRule> {
    let synthetic_path = Path::new(identifier);
    parse_rule_source_to_loaded(identifier, content, synthetic_path)
}

fn parse_license_source_to_loaded(
    filename: &str,
    content: &str,
    source_path: &Path,
) -> Result<LoadedLicense> {
    let key = LoadedLicense::derive_key(Path::new(filename))?;

    let parsed = parse_license_file_content(content, source_path)?;

    let fm: LicenseFrontmatter = yaml_serde::from_str(&parsed.yaml_content).map_err(|e| {
        anyhow!(
            "Failed to parse license frontmatter YAML in {}: {}\nContent was:\n{}",
            source_path.display(),
            e,
            parsed.yaml_content
        )
    })?;

    LoadedLicense::validate_key_match(&key, fm.key.as_deref()).map_err(|e| {
        anyhow!(
            "License file has key mismatch: {}: {}",
            source_path.display(),
            e
        )
    })?;

    let is_deprecated = fm.is_deprecated.unwrap_or(false);
    let is_unknown = fm.is_unknown.unwrap_or(false);
    let is_generic = fm.is_generic.unwrap_or(false);

    LoadedLicense::validate_text_content(
        &parsed.text_content,
        is_deprecated,
        is_unknown,
        is_generic,
    )
    .map_err(|e| {
        anyhow!(
            "License file has invalid content: {}: {}",
            source_path.display(),
            e
        )
    })?;

    let name = LoadedLicense::derive_name(fm.name.as_deref(), fm.short_name.as_deref(), &key);

    let reference_urls = LoadedLicense::merge_reference_urls(
        fm.text_urls.as_deref(),
        fm.other_urls.as_deref(),
        fm.osi_url.as_deref(),
        fm.faq_url.as_deref(),
        fm.homepage_url.as_deref(),
    );

    let minimum_coverage = fm.minimum_coverage.and_then(|n| n.as_u8());

    Ok(LoadedLicense {
        key,
        short_name: LoadedLicense::normalize_optional_string(fm.short_name.as_deref()),
        name,
        language: Some("en".to_string()),
        spdx_license_key: LoadedLicense::normalize_optional_string(fm.spdx_license_key.as_deref()),
        other_spdx_license_keys: fm.other_spdx_license_keys.unwrap_or_default(),
        category: LoadedLicense::normalize_optional_string(fm.category.as_deref()),
        owner: LoadedLicense::normalize_optional_string(fm.owner.as_deref()),
        homepage_url: LoadedLicense::normalize_optional_string(fm.homepage_url.as_deref()),
        text: parsed.text_content,
        reference_urls,
        osi_license_key: LoadedLicense::normalize_optional_string(fm.osi_license_key.as_deref()),
        text_urls: LoadedLicense::normalize_optional_list(fm.text_urls.as_deref())
            .unwrap_or_default(),
        osi_url: LoadedLicense::normalize_optional_string(fm.osi_url.as_deref()),
        faq_url: LoadedLicense::normalize_optional_string(fm.faq_url.as_deref()),
        other_urls: LoadedLicense::normalize_optional_list(fm.other_urls.as_deref())
            .unwrap_or_default(),
        notes: LoadedLicense::normalize_optional_string(fm.notes.as_deref()),
        is_deprecated,
        is_exception: fm.is_exception.unwrap_or(false),
        is_unknown,
        is_generic,
        replaced_by: fm.replaced_by.unwrap_or_default(),
        minimum_coverage,
        standard_notice: LoadedLicense::normalize_optional_string(fm.standard_notice.as_deref()),
        ignorable_copyrights: LoadedLicense::normalize_optional_list(
            fm.ignorable_copyrights.as_deref(),
        ),
        ignorable_holders: LoadedLicense::normalize_optional_list(fm.ignorable_holders.as_deref()),
        ignorable_authors: LoadedLicense::normalize_optional_list(fm.ignorable_authors.as_deref()),
        ignorable_urls: LoadedLicense::normalize_optional_list(fm.ignorable_urls.as_deref()),
        ignorable_emails: LoadedLicense::normalize_optional_list(fm.ignorable_emails.as_deref()),
    })
}

/// Parse a .LICENSE file into a `LoadedLicense` (loader-stage).
///
/// This function parses the file and returns a `LoadedLicense` with normalized data.
/// Deprecated entries are included - filtering is a build-stage concern.
pub fn parse_license_to_loaded(path: &Path) -> Result<LoadedLicense> {
    let content = fs::read_to_string(path)
        .with_context(|| format!("Failed to read license file: {}", path.display()))?;
    parse_license_source_to_loaded(
        path.file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown.LICENSE"),
        &content,
        path,
    )
}

/// Parse a license from in-memory ScanCode-style `.LICENSE` content.
pub fn parse_license_str_to_loaded(filename: &str, content: &str) -> Result<LoadedLicense> {
    let synthetic_path = Path::new(filename);
    parse_license_source_to_loaded(filename, content, synthetic_path)
}

/// Parse license file content into frontmatter and text sections.
///
/// The `path` parameter is used for error messages only.
fn parse_license_file_content(content: &str, path: &Path) -> Result<ParsedLicenseFile> {
    if content.len() < 6 {
        return Err(anyhow!(
            "License file content too short: {}",
            path.display()
        ));
    }

    let parts: Vec<&str> = FM_BOUNDARY.splitn(content, 3).collect();

    if parts.len() < 3 {
        let trimmed = content.trim();
        if trimmed.is_empty() {
            return Err(anyhow!(
                "License file is empty or has no content: {}",
                path.display()
            ));
        }
        return Err(anyhow!(
            "License file missing delimiter '---': {}",
            path.display()
        ));
    }

    let yaml_content = parts
        .get(1)
        .ok_or_else(|| anyhow!("Missing YAML frontmatter in {}", path.display()))?
        .to_string();
    let text_content = parts
        .get(2)
        .ok_or_else(|| {
            anyhow!(
                "Missing text content after frontmatter in {}",
                path.display()
            )
        })?
        .trim_start_matches('\n')
        .trim()
        .to_string();

    Ok(ParsedLicenseFile {
        yaml_content,
        text_content,
    })
}

/// Load all .RULE files from a directory into `LoadedRule` values (loader-stage).
///
/// This function loads ALL rules, including deprecated ones.
/// Deprecated filtering is a build-stage concern.
///
/// # Arguments
/// * `dir` - Directory containing .RULE files
///
/// # Returns
/// * `Ok(Vec<LoadedRule>)` - All loaded rules (including deprecated)
/// * `Err(...)` - Directory read error
pub fn load_loaded_rules_from_directory(dir: &Path) -> Result<Vec<LoadedRule>> {
    let mut rules = Vec::new();

    let entries = fs::read_dir(dir)
        .with_context(|| format!("Failed to read rules directory: {}", dir.display()))?;

    for entry in entries {
        let entry = entry
            .with_context(|| format!("Failed to read directory entry in: {}", dir.display()))?;
        let path = entry.path();

        if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("RULE") {
            match parse_rule_to_loaded(&path) {
                Ok(rule) => rules.push(rule),
                Err(e) => {
                    warn!("Failed to parse rule file {}: {}", path.display(), e);
                }
            }
        }
    }

    Ok(rules)
}

/// Load all .LICENSE files from a directory into `LoadedLicense` values (loader-stage).
///
/// This function loads ALL licenses, including deprecated ones.
/// Deprecated filtering is a build-stage concern.
///
/// # Arguments
/// * `dir` - Directory containing .LICENSE files
///
/// # Returns
/// * `Ok(Vec<LoadedLicense>)` - All loaded licenses (including deprecated)
/// * `Err(...)` - Directory read error
pub fn load_loaded_licenses_from_directory(dir: &Path) -> Result<Vec<LoadedLicense>> {
    let mut licenses = Vec::new();

    let entries = fs::read_dir(dir)
        .with_context(|| format!("Failed to read licenses directory: {}", dir.display()))?;

    for entry in entries {
        let entry = entry
            .with_context(|| format!("Failed to read directory entry in: {}", dir.display()))?;
        let path = entry.path();

        if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("LICENSE") {
            match parse_license_to_loaded(&path) {
                Ok(license) => licenses.push(license),
                Err(e) => {
                    warn!("Failed to parse license file {}: {}", path.display(), e);
                }
            }
        }
    }

    Ok(licenses)
}

/// Validate loaded rules for common issues.
///
/// Checks for:
/// 1. Duplicate rule texts (warns if found)
/// 2. Empty license expressions for non-false-positive rules (warns if found)
///
/// Corresponds to Python:
/// - `models.py:validate()` for license expression validation
/// - `index.py:_add_rules()` for duplicate detection via hash
///
/// Kept for backward compatibility with `load_rules_from_directory`.
#[allow(dead_code)]
fn validate_rules(rules: &[Rule]) {
    let mut seen_texts: HashSet<&str> = HashSet::new();
    let mut duplicate_count = 0;

    for rule in rules {
        if !seen_texts.insert(&rule.text) {
            warn!(
                "Duplicate rule text found for license_expression: {}",
                rule.license_expression
            );
            duplicate_count += 1;
        }

        if !rule.is_false_positive && rule.license_expression.trim().is_empty() {
            warn!("Rule has empty license_expression but is not marked as false_positive");
        }
    }

    if duplicate_count > 0 {
        warn!(
            "Found {} duplicate rule text(s) during rule validation",
            duplicate_count
        );
    }
}

/// Load all .RULE files from a directory into `Rule` values (backward-compatible).
///
/// This function loads rules and applies deprecated filtering during loading.
/// For the two-stage pipeline, prefer `load_loaded_rules_from_directory` and
/// `build_index_from_loaded`.
///
/// Kept for backward compatibility and testing despite not being used in production code.
/// The new pipeline uses the two-stage loading process instead.
#[allow(dead_code)]
pub fn load_rules_from_directory(dir: &Path, with_deprecated: bool) -> Result<Vec<Rule>> {
    let loaded = load_loaded_rules_from_directory(dir)?;
    let rules: Vec<Rule> = loaded
        .into_iter()
        .filter(|r| with_deprecated || !r.is_deprecated)
        .map(loaded_rule_to_rule)
        .collect();
    validate_rules(&rules);
    Ok(rules)
}

/// Load all .LICENSE files from a directory into `License` values (backward-compatible).
///
/// This function loads licenses and applies deprecated filtering during loading.
/// For the two-stage pipeline, prefer `load_loaded_licenses_from_directory` and
/// `build_index_from_loaded`.
///
/// Kept for backward compatibility and testing despite not being used in production code.
/// The new pipeline uses the two-stage loading process instead.
#[allow(dead_code)]
pub fn load_licenses_from_directory(dir: &Path, with_deprecated: bool) -> Result<Vec<License>> {
    let loaded = load_loaded_licenses_from_directory(dir)?;
    let licenses: Vec<License> = loaded
        .into_iter()
        .filter(|l| with_deprecated || !l.is_deprecated)
        .map(loaded_license_to_license)
        .collect();
    Ok(licenses)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::fs;
    use tempfile::tempdir;

    pub fn parse_rule_file(path: &Path) -> Result<Rule> {
        let loaded = parse_rule_to_loaded(path)?;
        Ok(loaded_rule_to_rule(loaded))
    }

    #[test]
    fn test_parse_number_as_u8() {
        let num_int: yaml_serde::Number = yaml_serde::from_str("100").unwrap();
        assert_eq!(num_int.as_u8(), Some(100));

        let num_out_of_range: yaml_serde::Number = yaml_serde::from_str("500").unwrap();
        assert_eq!(num_out_of_range.as_u8(), None);

        let num_float: yaml_serde::Number = yaml_serde::from_str("90.5").unwrap();
        assert_eq!(num_float.as_u8(), Some(90));
    }

    #[test]
    fn test_parse_simple_license_file() {
        let dir = tempdir().unwrap();
        let license_path = dir.path().join("mit.LICENSE");
        fs::write(
            &license_path,
            r#"---
key: mit
short_name: MIT License
name: MIT License
category: Permissive
spdx_license_key: MIT
---
MIT License text here"#,
        )
        .unwrap();

        let license = parse_license_to_loaded(&license_path)
            .map(loaded_license_to_license)
            .unwrap();
        assert_eq!(license.key, "mit");
        assert_eq!(license.name, "MIT License");
        assert!(license.text.contains("MIT License text"));
    }

    #[test]
    fn test_parse_simple_rule_file() {
        let dir = tempdir().unwrap();
        let rule_path = dir.path().join("mit_1.RULE");
        fs::write(
            &rule_path,
            r#"---
license_expression: mit
is_license_reference: yes
relevance: 90
referenced_filenames:
    - MIT.txt
---
MIT.txt"#,
        )
        .unwrap();

        let rule = parse_rule_file(&rule_path).unwrap();
        assert_eq!(rule.license_expression, "mit");
        assert_eq!(rule.text, "MIT.txt");
        assert!(rule.is_license_reference());
        assert_eq!(rule.relevance, 90);
    }

    #[test]
    fn test_deserialize_yes_no_bool() {
        let dir = tempdir().unwrap();
        let rule_path = dir.path().join("test.RULE");

        fs::write(
            &rule_path,
            r#"---
license_expression: mit
is_license_notice: yes
is_license_tag: no
---
MIT License"#,
        )
        .unwrap();

        let rule = parse_rule_file(&rule_path).unwrap();
        assert!(rule.is_license_notice());
        assert!(!rule.is_license_tag());
    }

    #[test]
    fn test_load_licenses_from_directory() {
        let dir = tempdir().unwrap();

        fs::write(
            dir.path().join("test.LICENSE"),
            r#"---
key: test
name: Test License
spdx_license_key: TEST
category: Permissive
---
Test license text here"#,
        )
        .unwrap();

        let licenses = load_licenses_from_directory(dir.path(), false).unwrap();
        assert_eq!(licenses.len(), 1);

        let license = &licenses[0];
        assert_eq!(license.key, "test");
        assert_eq!(license.name, "Test License");
        assert_eq!(license.spdx_license_key, Some("TEST".to_string()));
        assert!(!license.text.is_empty());
    }

    #[test]
    fn test_load_rules_from_directory() {
        let dir = tempdir().unwrap();

        fs::write(
            dir.path().join("test_1.RULE"),
            r#"---
license_expression: test
is_license_reference: yes
relevance: 85
referenced_filenames:
    - TEST.txt
---
TEST.txt"#,
        )
        .unwrap();

        let rules = load_rules_from_directory(dir.path(), false).unwrap();
        assert_eq!(rules.len(), 1);

        let rule = &rules[0];
        assert_eq!(rule.license_expression, "test");
        assert!(rule.is_license_reference());
        assert_eq!(rule.relevance, 85);
    }

    #[test]
    fn test_validate_rules_detects_duplicates() {
        let rules = vec![
            Rule {
                identifier: "mit.LICENSE".to_string(),
                license_expression: "mit".to_string(),
                text: "MIT License".to_string(),
                tokens: vec![],
                rule_kind: crate::license_detection::models::RuleKind::Text,
                is_false_positive: false,
                is_required_phrase: false,
                is_from_license: false,
                relevance: 100,
                minimum_coverage: None,
                has_stored_minimum_coverage: false,
                is_continuous: false,
                required_phrase_spans: vec![],
                stopwords_by_pos: HashMap::new(),
                referenced_filenames: None,
                ignorable_urls: None,
                ignorable_emails: None,
                ignorable_copyrights: None,
                ignorable_holders: None,
                ignorable_authors: None,
                language: None,
                notes: None,
                length_unique: 0,
                high_length_unique: 0,
                high_length: 0,
                min_matched_length: 0,
                min_high_matched_length: 0,
                min_matched_length_unique: 0,
                min_high_matched_length_unique: 0,
                is_small: false,
                is_tiny: false,
                starts_with_license: false,
                ends_with_license: false,
                is_deprecated: false,
                spdx_license_key: None,
                other_spdx_license_keys: vec![],
            },
            Rule {
                identifier: "apache-2.0.LICENSE".to_string(),
                license_expression: "apache-2.0".to_string(),
                text: "MIT License".to_string(),
                tokens: vec![],
                rule_kind: crate::license_detection::models::RuleKind::Text,
                is_false_positive: false,
                is_required_phrase: false,
                is_from_license: false,
                relevance: 100,
                minimum_coverage: None,
                has_stored_minimum_coverage: false,
                is_continuous: false,
                required_phrase_spans: vec![],
                stopwords_by_pos: HashMap::new(),
                referenced_filenames: None,
                ignorable_urls: None,
                ignorable_emails: None,
                ignorable_copyrights: None,
                ignorable_holders: None,
                ignorable_authors: None,
                language: None,
                notes: None,
                length_unique: 0,
                high_length_unique: 0,
                high_length: 0,
                min_matched_length: 0,
                min_high_matched_length: 0,
                min_matched_length_unique: 0,
                min_high_matched_length_unique: 0,
                is_small: false,
                is_tiny: false,
                starts_with_license: false,
                ends_with_license: false,
                is_deprecated: false,
                spdx_license_key: None,
                other_spdx_license_keys: vec![],
            },
        ];

        validate_rules(&rules);
    }

    #[test]
    fn test_validate_rules_accepts_false_positive_without_expression() {
        let rules = vec![Rule {
            identifier: "fp.RULE".to_string(),
            license_expression: "".to_string(),
            text: "Some text".to_string(),
            tokens: vec![],
            rule_kind: crate::license_detection::models::RuleKind::None,
            is_false_positive: true,
            is_required_phrase: false,
            is_from_license: false,
            relevance: 100,
            minimum_coverage: None,
            has_stored_minimum_coverage: false,
            is_continuous: false,
            required_phrase_spans: vec![],
            stopwords_by_pos: HashMap::new(),
            referenced_filenames: None,
            ignorable_urls: None,
            ignorable_emails: None,
            ignorable_copyrights: None,
            ignorable_holders: None,
            ignorable_authors: None,
            language: None,
            notes: Some("False positive for common pattern".to_string()),
            length_unique: 0,
            high_length_unique: 0,
            high_length: 0,
            min_matched_length: 0,
            min_high_matched_length: 0,
            min_matched_length_unique: 0,
            min_high_matched_length_unique: 0,
            is_small: false,
            is_tiny: false,
            starts_with_license: false,
            ends_with_license: false,
            is_deprecated: false,
            spdx_license_key: None,
            other_spdx_license_keys: vec![],
        }];

        validate_rules(&rules);
    }

    #[test]
    fn test_validate_rules_no_duplicates() {
        let rules = vec![
            Rule {
                identifier: "mit.LICENSE".to_string(),
                license_expression: "mit".to_string(),
                text: "MIT License".to_string(),
                tokens: vec![],
                rule_kind: crate::license_detection::models::RuleKind::Text,
                is_false_positive: false,
                is_required_phrase: false,
                is_from_license: false,
                relevance: 100,
                minimum_coverage: None,
                has_stored_minimum_coverage: false,
                is_continuous: false,
                required_phrase_spans: vec![],
                stopwords_by_pos: HashMap::new(),
                referenced_filenames: None,
                ignorable_urls: None,
                ignorable_emails: None,
                ignorable_copyrights: None,
                ignorable_holders: None,
                ignorable_authors: None,
                language: None,
                notes: None,
                length_unique: 0,
                high_length_unique: 0,
                high_length: 0,
                min_matched_length: 0,
                min_high_matched_length: 0,
                min_matched_length_unique: 0,
                min_high_matched_length_unique: 0,
                is_small: false,
                is_tiny: false,
                starts_with_license: false,
                ends_with_license: false,
                is_deprecated: false,
                spdx_license_key: None,
                other_spdx_license_keys: vec![],
            },
            Rule {
                identifier: "apache-2.0.LICENSE".to_string(),
                license_expression: "apache-2.0".to_string(),
                text: "Apache License".to_string(),
                tokens: vec![],
                rule_kind: crate::license_detection::models::RuleKind::Text,
                is_false_positive: false,
                is_required_phrase: false,
                is_from_license: false,
                relevance: 100,
                minimum_coverage: None,
                has_stored_minimum_coverage: false,
                is_continuous: false,
                required_phrase_spans: vec![],
                stopwords_by_pos: HashMap::new(),
                referenced_filenames: None,
                ignorable_urls: None,
                ignorable_emails: None,
                ignorable_copyrights: None,
                ignorable_holders: None,
                ignorable_authors: None,
                language: None,
                notes: None,
                length_unique: 0,
                high_length_unique: 0,
                high_length: 0,
                min_matched_length: 0,
                min_high_matched_length: 0,
                min_matched_length_unique: 0,
                min_high_matched_length_unique: 0,
                is_small: false,
                is_tiny: false,
                starts_with_license: false,
                ends_with_license: false,
                is_deprecated: false,
                spdx_license_key: None,
                other_spdx_license_keys: vec![],
            },
        ];

        validate_rules(&rules);
    }

    #[test]
    fn test_load_licenses_filters_deprecated_by_default() {
        let dir = tempdir().unwrap();

        fs::write(
            dir.path().join("active.LICENSE"),
            r#"---
key: active
name: Active License
---
Active license text"#,
        )
        .unwrap();

        fs::write(
            dir.path().join("deprecated.LICENSE"),
            r#"---
key: deprecated
name: Deprecated License
is_deprecated: yes
---
Deprecated license text"#,
        )
        .unwrap();

        let licenses_without = load_licenses_from_directory(dir.path(), false).unwrap();
        assert_eq!(licenses_without.len(), 1);
        assert_eq!(licenses_without[0].key, "active");

        let licenses_with = load_licenses_from_directory(dir.path(), true).unwrap();
        assert_eq!(licenses_with.len(), 2);
    }

    #[test]
    fn test_load_rules_filters_deprecated_by_default() {
        let dir = tempdir().unwrap();

        fs::write(
            dir.path().join("active.RULE"),
            r#"---
license_expression: active
is_license_notice: yes
---
Active rule text"#,
        )
        .unwrap();

        fs::write(
            dir.path().join("deprecated.RULE"),
            r#"---
license_expression: deprecated
is_license_notice: yes
is_deprecated: yes
---
Deprecated rule text"#,
        )
        .unwrap();

        let rules_without = load_rules_from_directory(dir.path(), false).unwrap();
        assert_eq!(rules_without.len(), 1);
        assert_eq!(rules_without[0].license_expression, "active");

        let rules_with = load_rules_from_directory(dir.path(), true).unwrap();
        assert_eq!(rules_with.len(), 2);
    }

    #[test]
    fn test_parse_rule_to_loaded() {
        let dir = tempdir().unwrap();
        let rule_path = dir.path().join("mit_1.RULE");
        fs::write(
            &rule_path,
            r#"---
license_expression: mit
is_license_reference: yes
relevance: 90
referenced_filenames:
    - MIT.txt
---
MIT.txt"#,
        )
        .unwrap();

        let loaded = parse_rule_to_loaded(&rule_path).unwrap();
        assert_eq!(loaded.identifier, "mit_1.RULE");
        assert_eq!(loaded.license_expression, "mit");
        assert_eq!(loaded.text, "MIT.txt");
        assert_eq!(
            loaded.rule_kind,
            crate::license_detection::models::RuleKind::Reference
        );
        assert_eq!(loaded.relevance, Some(90));
        assert_eq!(
            loaded.referenced_filenames,
            Some(vec!["MIT.txt".to_string()])
        );
        assert!(!loaded.is_deprecated);
    }

    #[test]
    fn test_parse_license_to_loaded() {
        let dir = tempdir().unwrap();
        let license_path = dir.path().join("mit.LICENSE");
        fs::write(
            &license_path,
            r#"---
key: mit
short_name: MIT License
name: MIT License
category: Permissive
spdx_license_key: MIT
---
MIT License text here"#,
        )
        .unwrap();

        let loaded = parse_license_to_loaded(&license_path).unwrap();
        assert_eq!(loaded.key, "mit");
        assert_eq!(loaded.name, "MIT License");
        assert!(loaded.text.contains("MIT License text"));
        assert_eq!(loaded.spdx_license_key, Some("MIT".to_string()));
    }

    #[test]
    fn test_load_loaded_rules_from_directory_includes_deprecated() {
        let dir = tempdir().unwrap();

        fs::write(
            dir.path().join("active.RULE"),
            r#"---
license_expression: active
is_license_notice: yes
---
Active rule text"#,
        )
        .unwrap();

        fs::write(
            dir.path().join("deprecated.RULE"),
            r#"---
license_expression: deprecated
is_license_notice: yes
is_deprecated: yes
---
Deprecated rule text"#,
        )
        .unwrap();

        let loaded_rules = load_loaded_rules_from_directory(dir.path()).unwrap();
        assert_eq!(loaded_rules.len(), 2);

        let active = loaded_rules
            .iter()
            .find(|r| r.license_expression == "active")
            .unwrap();
        assert!(!active.is_deprecated);

        let deprecated = loaded_rules
            .iter()
            .find(|r| r.license_expression == "deprecated")
            .unwrap();
        assert!(deprecated.is_deprecated);
    }

    #[test]
    fn test_load_loaded_licenses_from_directory_includes_deprecated() {
        let dir = tempdir().unwrap();

        fs::write(
            dir.path().join("active.LICENSE"),
            r#"---
key: active
name: Active License
---
Active license text"#,
        )
        .unwrap();

        fs::write(
            dir.path().join("deprecated.LICENSE"),
            r#"---
key: deprecated
name: Deprecated License
is_deprecated: yes
---
Deprecated license text"#,
        )
        .unwrap();

        let loaded_licenses = load_loaded_licenses_from_directory(dir.path()).unwrap();
        assert_eq!(loaded_licenses.len(), 2);

        let active = loaded_licenses.iter().find(|l| l.key == "active").unwrap();
        assert!(!active.is_deprecated);

        let deprecated = loaded_licenses
            .iter()
            .find(|l| l.key == "deprecated")
            .unwrap();
        assert!(deprecated.is_deprecated);
    }
}