feluda 1.12.0

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

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use std::sync::OnceLock;
use std::time::Duration;
use toml::Value as TomlValue;

use crate::cache;
use crate::cli;
use crate::config;
use crate::debug::{log, log_debug, log_error, FeludaResult, LogLevel};

static GITHUB_TOKEN: OnceLock<Option<String>> = OnceLock::new();

/// Set the GitHub API token for authenticated requests
pub fn set_github_token(token: Option<String>) {
    let _ = GITHUB_TOKEN.set(token);
}

/// Get the GitHub API token if set
fn get_github_token() -> Option<&'static str> {
    GITHUB_TOKEN.get().and_then(|t| t.as_deref())
}

/// License compatibility enum
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LicenseCompatibility {
    Compatible,
    Incompatible,
    Unknown,
}

impl std::fmt::Display for LicenseCompatibility {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Compatible => write!(f, "Compatible"),
            Self::Incompatible => write!(f, "Incompatible"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Structure for deserializing license compatibility matrix from TOML
#[derive(Deserialize, Debug, Clone)]
struct LicenseCompatibilityMatrix {
    #[serde(rename = "MIT")]
    mit: Option<LicenseEntry>,
    #[serde(rename = "Apache-2_0")]
    apache_2_0: Option<LicenseEntry>,
    #[serde(rename = "GPL-3_0")]
    gpl_3_0: Option<LicenseEntry>,
    #[serde(rename = "GPL-2_0")]
    gpl_2_0: Option<LicenseEntry>,
    #[serde(rename = "AGPL-3_0")]
    agpl_3_0: Option<LicenseEntry>,
    #[serde(rename = "LGPL-3_0")]
    lgpl_3_0: Option<LicenseEntry>,
    #[serde(rename = "LGPL-2_1")]
    lgpl_2_1: Option<LicenseEntry>,
    #[serde(rename = "MPL-2_0")]
    mpl_2_0: Option<LicenseEntry>,
    #[serde(rename = "BSD-3-Clause")]
    bsd_3_clause: Option<LicenseEntry>,
    #[serde(rename = "BSD-2-Clause")]
    bsd_2_clause: Option<LicenseEntry>,
    #[serde(rename = "ISC")]
    isc: Option<LicenseEntry>,
    #[serde(rename = "_0BSD")]
    bsd_0: Option<LicenseEntry>,
    #[serde(rename = "Unlicense")]
    unlicense: Option<LicenseEntry>,
    #[serde(rename = "WTFPL")]
    wtfpl: Option<LicenseEntry>,
}

#[derive(Deserialize, Debug, Clone)]
struct LicenseEntry {
    compatible_with: Vec<String>,
}

/// Static cache for the compatibility matrix
#[cfg(not(test))]
static COMPATIBILITY_MATRIX: OnceLock<HashMap<String, Vec<String>>> = OnceLock::new();

/// OSI license status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OsiStatus {
    Approved,
    NotApproved,
    Unknown,
}

impl std::fmt::Display for OsiStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Approved => write!(f, "approved"),
            Self::NotApproved => write!(f, "not-approved"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

/// OSI license information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OsiLicenseInfo {
    pub id: String,
    pub name: String,
    pub status: OsiStatus,
}

/// License Info of dependencies
#[derive(Serialize, Debug, Clone)]
pub struct LicenseInfo {
    pub name: String,                        // The name of the software or library
    pub version: String,                     // The version of the software or library
    pub license: Option<String>, // An optional field that contains the license type (e.g., MIT, Apache 2.0)
    pub is_restrictive: bool,    // A boolean indicating whether the license is restrictive or not
    pub compatibility: LicenseCompatibility, // Compatibility with project license
    pub osi_status: OsiStatus,   // OSI approval status
}

impl LicenseInfo {
    pub fn get_license(&self) -> String {
        match &self.license {
            Some(license_name) => String::from(license_name),
            None => String::from("No License"),
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn version(&self) -> &str {
        &self.version
    }

    pub fn is_restrictive(&self) -> &bool {
        &self.is_restrictive
    }

    pub fn compatibility(&self) -> &LicenseCompatibility {
        &self.compatibility
    }

    pub fn osi_status(&self) -> &OsiStatus {
        &self.osi_status
    }

    #[allow(dead_code)]
    pub fn osi_info(&self) -> Option<OsiLicenseInfo> {
        self.license.as_ref().map(|license| OsiLicenseInfo {
            id: license.clone(),
            name: license.clone(),
            status: self.osi_status,
        })
    }
}

/// License Info structure for GitHub API data
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct License {
    pub title: String,            // The full name of the license
    pub spdx_id: String,          // The SPDX identifier for the license
    pub permissions: Vec<String>, // A list of permissions granted by the license
    pub conditions: Vec<String>,  // A list of conditions that must be met under the license
    pub limitations: Vec<String>, // A list of limitations imposed by the license
}

/// Fetch license data from GitHub's official Licenses API
/// Attempts to load from cache first, falls back to GitHub API if cache miss or stale
pub fn fetch_licenses_from_github() -> FeludaResult<HashMap<String, License>> {
    log(LogLevel::Info, "Fetching licenses from GitHub Licenses API");

    match cache::load_github_licenses_from_cache() {
        Ok(Some(cached_licenses)) => {
            log(
                LogLevel::Info,
                &format!("Using cached licenses ({})", cached_licenses.len()),
            );
            return Ok(cached_licenses);
        }
        Ok(None) => {
            log(LogLevel::Info, "Cache miss or stale, fetching from GitHub");
        }
        Err(e) => {
            log(
                LogLevel::Warn,
                &format!("Cache read error: {e}, fetching from GitHub"),
            );
        }
    }

    let licenses_map = cli::with_spinner("Fetching licenses from GitHub API", |indicator| {
        let rt = match tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
        {
            Ok(rt) => rt,
            Err(err) => {
                log_error("Failed to create tokio runtime", &err);
                return HashMap::new();
            }
        };

        rt.block_on(fetch_licenses_concurrent(indicator))
    });

    if !licenses_map.is_empty() {
        if let Err(e) = cache::save_github_licenses_to_cache(&licenses_map) {
            log(LogLevel::Warn, &format!("Failed to save cache: {e}"));
        }
    } else {
        log(
            LogLevel::Warn,
            "No licenses fetched from GitHub API, cache not saved",
        );
    }

    Ok(licenses_map)
}

/// Async helper function for concurrent license fetching with rate limiting
async fn fetch_licenses_concurrent(
    indicator: &crate::cli::LoadingIndicator,
) -> HashMap<String, License> {
    let mut licenses_map = HashMap::new();

    // Create async HTTP client with optional authentication
    let mut client_builder = reqwest::Client::builder()
        .user_agent("feluda-license-checker/1.0")
        .timeout(Duration::from_secs(30));

    if let Some(token) = get_github_token() {
        log(
            LogLevel::Info,
            "Using authenticated GitHub API requests (higher rate limits)",
        );
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::AUTHORIZATION,
            format!("Bearer {token}")
                .parse()
                .expect("Invalid token format"),
        );
        client_builder = client_builder.default_headers(headers);
    }

    let client = match client_builder.build() {
        Ok(client) => client,
        Err(err) => {
            log_error("Failed to create HTTP client", &err);
            return licenses_map;
        }
    };

    indicator.update_progress("fetching license list");

    // First, get the list of available licenses
    let licenses_list_url = "https://api.github.com/licenses";
    let response = match client.get(licenses_list_url).send().await {
        Ok(response) => response,
        Err(err) => {
            log_error("Failed to fetch licenses list from GitHub API", &err);
            return licenses_map;
        }
    };

    if !response.status().is_success() {
        log(
            LogLevel::Error,
            &format!("GitHub API returned error status: {}", response.status()),
        );
        return licenses_map;
    }

    let licenses_list: Vec<serde_json::Value> = match response.json().await {
        Ok(list) => list,
        Err(err) => {
            log_error("Failed to parse licenses list JSON", &err);
            return licenses_map;
        }
    };

    let total_licenses = licenses_list.len();
    indicator.update_progress(&format!("found {total_licenses} licenses"));

    let client = Arc::new(client);

    let license_keys: Vec<String> = licenses_list
        .iter()
        .filter_map(|license_info| {
            license_info
                .get("key")
                .and_then(|k| k.as_str())
                .map(|s| s.to_string())
        })
        .collect();

    // H2 multiplexes all requests over a single connection; no throttling needed for ~13 licenses
    let mut join_set = tokio::task::JoinSet::new();

    for license_key in license_keys {
        let client = Arc::clone(&client);

        join_set.spawn(async move {
            log(
                LogLevel::Info,
                &format!("Fetching detailed license info: {license_key}"),
            );

            let license_url = format!("https://api.github.com/licenses/{license_key}");

            match client.get(&license_url).send().await {
                Ok(license_response) => {
                    if license_response.status().is_success() {
                        match license_response.json::<serde_json::Value>().await {
                            Ok(license_data) => {
                                // Extract the license information we need
                                let title = license_data
                                    .get("name")
                                    .and_then(|n| n.as_str())
                                    .unwrap_or(&license_key)
                                    .to_string();

                                let spdx_id = license_data
                                    .get("spdx_id")
                                    .and_then(|s| s.as_str())
                                    .unwrap_or(&license_key)
                                    .to_string();

                                let permissions = license_data
                                    .get("permissions")
                                    .and_then(|p| p.as_array())
                                    .map(|arr| {
                                        arr.iter()
                                            .filter_map(|v| v.as_str())
                                            .map(String::from)
                                            .collect()
                                    })
                                    .unwrap_or_default();

                                let conditions = license_data
                                    .get("conditions")
                                    .and_then(|c| c.as_array())
                                    .map(|arr| {
                                        arr.iter()
                                            .filter_map(|v| v.as_str())
                                            .map(String::from)
                                            .collect()
                                    })
                                    .unwrap_or_default();

                                let limitations = license_data
                                    .get("limitations")
                                    .and_then(|l| l.as_array())
                                    .map(|arr| {
                                        arr.iter()
                                            .filter_map(|v| v.as_str())
                                            .map(String::from)
                                            .collect()
                                    })
                                    .unwrap_or_default();

                                let license = License {
                                    title,
                                    spdx_id,
                                    permissions,
                                    conditions,
                                    limitations,
                                };

                                // Use the SPDX ID as the key for consistency
                                let key_to_use = license_data
                                    .get("spdx_id")
                                    .and_then(|s| s.as_str())
                                    .unwrap_or(&license_key);

                                log(
                                    LogLevel::Info,
                                    &format!("Successfully processed license: {key_to_use}"),
                                );

                                Some((key_to_use.to_string(), license))
                            }
                            Err(err) => {
                                log_error(
                                    &format!("Failed to parse license JSON for {license_key}"),
                                    &err,
                                );
                                None
                            }
                        }
                    } else {
                        log(
                            LogLevel::Error,
                            &format!(
                                "Failed to fetch license {}: HTTP {}",
                                license_key,
                                license_response.status()
                            ),
                        );
                        None
                    }
                }
                Err(err) => {
                    log_error(
                        &format!("Failed to fetch license details for {license_key}"),
                        &err,
                    );
                    None
                }
            }
        });
    }

    let mut license_count = 0;
    while let Some(result) = join_set.join_next().await {
        match result {
            Ok(Some((key, license))) => {
                licenses_map.insert(key, license);
                license_count += 1;
            }
            Ok(None) => {}
            Err(e) => log(
                LogLevel::Error,
                &format!("License fetch task panicked: {e}"),
            ),
        }
        indicator.update_progress(&format!("fetched {license_count}/{total_licenses}"));
    }

    log(
        LogLevel::Info,
        &format!("Fetched {license_count} licenses from GitHub API"),
    );

    licenses_map
}

/// Static cache for OSI approved licenses
#[cfg(not(test))]
static OSI_LICENSES: OnceLock<HashMap<String, OsiStatus>> = OnceLock::new();

/// Fetch OSI approved licenses from official API (single request, no async needed)
pub fn fetch_osi_licenses() -> FeludaResult<HashMap<String, OsiStatus>> {
    log(LogLevel::Info, "Fetching OSI approved licenses");

    let osi_map = cli::with_spinner("Fetching OSI approved licenses", |indicator| {
        let client = match reqwest::blocking::Client::builder()
            .user_agent("feluda-license-checker/1.0")
            .timeout(Duration::from_secs(30))
            .build()
        {
            Ok(client) => client,
            Err(err) => {
                log_error("Failed to create HTTP client", &err);
                return HashMap::new();
            }
        };

        indicator.update_progress("fetching OSI licenses");

        let response = match client.get("https://api.opensource.org/licenses/").send() {
            Ok(response) => response,
            Err(err) => {
                log_error("Failed to fetch OSI licenses from API", &err);
                return HashMap::new();
            }
        };

        if !response.status().is_success() {
            log(
                LogLevel::Error,
                &format!("OSI API returned error status: {}", response.status()),
            );
            return HashMap::new();
        }

        let osi_licenses: Vec<serde_json::Value> = match response.json() {
            Ok(licenses) => licenses,
            Err(err) => {
                log_error("Failed to parse OSI licenses JSON", &err);
                return HashMap::new();
            }
        };

        let total_licenses = osi_licenses.len();
        indicator.update_progress(&format!("found {total_licenses} OSI licenses"));

        let mut osi_map = HashMap::new();
        for license_data in osi_licenses {
            if let Some(id) = license_data.get("id").and_then(|id| id.as_str()) {
                osi_map.insert(id.to_string(), OsiStatus::Approved);
            }
        }

        indicator.update_progress(&format!("processed {total_licenses} OSI licenses"));
        log(
            LogLevel::Info,
            &format!("Fetched {total_licenses} OSI approved licenses"),
        );

        osi_map
    });

    Ok(osi_map)
}

/// Get the OSI licenses map, loading it if not already cached
fn get_osi_licenses() -> &'static HashMap<String, OsiStatus> {
    #[cfg(not(test))]
    {
        OSI_LICENSES.get_or_init(|| {
            fetch_osi_licenses().unwrap_or_else(|e| {
                log(LogLevel::Warn, &format!("Failed to load OSI licenses: {e}"));
                log(LogLevel::Warn, "Continuing without OSI license information");
                HashMap::new()
            })
        })
    }

    #[cfg(test)]
    {
        use std::cell::RefCell;
        thread_local! {
            static OSI_MAP: RefCell<Option<HashMap<String, OsiStatus>>> = const { RefCell::new(None) };
        }

        OSI_MAP.with(|m| {
            let mut map = m.borrow_mut();
            if map.is_none() {
                match fetch_osi_licenses() {
                    Ok(loaded_map) => {
                        *map = Some(loaded_map);
                    }
                    Err(_) => {
                        *map = Some(HashMap::new());
                    }
                }
            }

            // Leak the memory to get a static reference (only for tests)
            let leaked: &'static HashMap<String, OsiStatus> =
                Box::leak(Box::new(map.as_ref().unwrap().clone()));
            leaked
        })
    }
}

/// Check OSI approval status for a license
pub fn get_osi_status(license_id: &str) -> OsiStatus {
    let normalized_id = normalize_license_id(license_id);
    let osi_licenses = get_osi_licenses();

    // Check for exact match first
    if let Some(status) = osi_licenses.get(&normalized_id) {
        return *status;
    }

    // Check for original license ID
    if let Some(status) = osi_licenses.get(license_id) {
        return *status;
    }

    // For well-known licenses, we can provide static mappings as fallback
    match normalized_id.as_str() {
        "MIT" | "Apache-2.0" | "BSD-3-Clause" | "BSD-2-Clause" | "GPL-3.0" | "GPL-2.0"
        | "LGPL-3.0" | "LGPL-2.1" | "MPL-2.0" | "ISC" | "0BSD" => OsiStatus::Approved,
        "No License" => OsiStatus::NotApproved,
        _ => OsiStatus::Unknown,
    }
}

/// Check if a license is considered restrictive based on configuration and known licenses
pub fn is_license_restrictive(
    license: &Option<String>,
    known_licenses: &HashMap<String, License>,
    strict: bool,
) -> bool {
    log(
        LogLevel::Info,
        &format!("Checking if license is restrictive: {license:?} (strict={strict})"),
    );

    let config = match config::load_config() {
        Ok(cfg) => {
            log(LogLevel::Info, "Successfully loaded configuration");
            cfg
        }
        Err(e) => {
            log_error("Error loading configuration", &e);
            log(LogLevel::Warn, "Using default configuration");
            config::FeludaConfig::default()
        }
    };

    if license.as_deref() == Some("No License") {
        log(
            LogLevel::Warn,
            "No license specified, considering as restrictive",
        );
        return true;
    }

    if let Some(license_str) = license {
        log_debug(
            "Checking against known licenses",
            &known_licenses.keys().collect::<Vec<_>>(),
        );

        if let Some(license_data) = known_licenses.get(license_str) {
            log_debug("Found license data", license_data);

            let conditions = if strict {
                vec![
                    "source-disclosure",
                    "network-use-disclosure",
                    "disclose-source",
                    "same-license",
                ]
            } else {
                vec!["source-disclosure", "network-use-disclosure"]
            };

            let is_restrictive = conditions
                .iter()
                .any(|&condition| license_data.conditions.contains(&condition.to_string()));

            if is_restrictive {
                log(
                    LogLevel::Warn,
                    &format!("License {license_str} is restrictive due to conditions"),
                );
            } else {
                log(
                    LogLevel::Info,
                    &format!("License {license_str} is not restrictive"),
                );
            }

            return is_restrictive;
        } else {
            let is_restrictive = config
                .licenses
                .restrictive
                .iter()
                .any(|restrictive_license| license_str.contains(restrictive_license));

            if is_restrictive {
                log(
                    LogLevel::Warn,
                    &format!("License {license_str} matches restrictive pattern in config"),
                );
            } else if strict && license_str.contains("Unknown") {
                log(
                    LogLevel::Warn,
                    &format!(
                        "License {license_str} is unknown in strict mode, considering restrictive"
                    ),
                );
                return true;
            } else {
                log(
                    LogLevel::Info,
                    &format!("License {license_str} does not match any restrictive pattern"),
                );
            }

            return is_restrictive;
        }
    }

    if strict {
        log(
            LogLevel::Warn,
            "No license information available in strict mode, considering restrictive",
        );
        return true;
    }

    log(LogLevel::Warn, "No license information available");
    false
}

/// Check if a license should be ignored from analysis
///
/// Returns true if the license is in the ignore list configured in `.feluda.toml`
/// or via `FELUDA_LICENSES_IGNORE` environment variable.
pub fn is_license_ignored(license: Option<&str>) -> bool {
    log(
        LogLevel::Info,
        &format!("Checking if license should be ignored: {license:?}"),
    );

    let config = match config::load_config() {
        Ok(cfg) => {
            log(LogLevel::Info, "Successfully loaded configuration");
            cfg
        }
        Err(e) => {
            log_error("Error loading configuration", &e);
            log(LogLevel::Warn, "Using default configuration");
            config::FeludaConfig::default()
        }
    };

    if let Some(license_str) = license {
        let is_ignored = config
            .licenses
            .ignore
            .iter()
            .any(|ignore_license| license_str.contains(ignore_license));

        if is_ignored {
            log(
                LogLevel::Info,
                &format!("License {license_str} matches ignore pattern in config"),
            );
        } else {
            log(
                LogLevel::Info,
                &format!("License {license_str} does not match any ignore pattern"),
            );
        }

        return is_ignored;
    }

    log(LogLevel::Info, "No license specified, not ignoring");
    false
}

/// This is the default configuration
const EMBEDDED_LICENSE_COMPATIBILITY_TOML: &str =
    include_str!("../config/license_compatibility.toml");

/// Load license compatibility matrix from external TOML file if available
/// Looks for the file in the following order:
/// 1. .feluda/license_compatibility.toml (user-specific config directory)
/// 2. Embedded configuration
fn load_compatibility_matrix() -> FeludaResult<HashMap<String, Vec<String>>> {
    log(
        LogLevel::Info,
        "Loading license compatibility matrix from TOML file",
    );

    // Only check for user-specific config in .feluda directory
    let config_paths = vec![Path::new(".feluda/license_compatibility.toml").to_path_buf()];

    let mut config_content = None;
    let mut used_path = None;

    for path in &config_paths {
        if path.exists() {
            log(
                LogLevel::Info,
                &format!("Found license compatibility config at: {}", path.display()),
            );
            match fs::read_to_string(path) {
                Ok(content) => {
                    config_content = Some(content);
                    used_path = Some(path);
                    break;
                }
                Err(e) => {
                    log(
                        LogLevel::Warn,
                        &format!("Failed to read {}: {}", path.display(), e),
                    );
                    continue;
                }
            }
        }
    }

    // Use embedded configuration as fallback if no external file is found
    let config_content = match config_content {
        Some(content) => content,
        None => {
            log(
                LogLevel::Info,
                "No external license compatibility config found, using embedded configuration",
            );
            EMBEDDED_LICENSE_COMPATIBILITY_TOML.to_string()
        }
    };

    let matrix: LicenseCompatibilityMatrix = toml::from_str(&config_content).map_err(|e| {
        let source = match &used_path {
            Some(path) => format!("external config file ({})", path.display()),
            None => "embedded configuration".to_string(),
        };
        log(
            LogLevel::Error,
            &format!("Failed to parse license compatibility {source}: {e}"),
        );
        std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())
    })?;

    // Convert TOML structure to HashMap
    let entries = [
        ("MIT", &matrix.mit),
        ("Apache-2.0", &matrix.apache_2_0),
        ("GPL-3.0", &matrix.gpl_3_0),
        ("GPL-2.0", &matrix.gpl_2_0),
        ("AGPL-3.0", &matrix.agpl_3_0),
        ("LGPL-3.0", &matrix.lgpl_3_0),
        ("LGPL-2.1", &matrix.lgpl_2_1),
        ("MPL-2.0", &matrix.mpl_2_0),
        ("BSD-3-Clause", &matrix.bsd_3_clause),
        ("BSD-2-Clause", &matrix.bsd_2_clause),
        ("ISC", &matrix.isc),
        ("0BSD", &matrix.bsd_0),
        ("Unlicense", &matrix.unlicense),
        ("WTFPL", &matrix.wtfpl),
    ];

    let result: HashMap<String, Vec<String>> = entries
        .iter()
        .filter_map(|(key, option_entry)| {
            option_entry
                .as_ref()
                .map(|entry| (key.to_string(), entry.compatible_with.clone()))
        })
        .collect();

    log(
        LogLevel::Info,
        &format!("Loaded {} license compatibility entries", result.len()),
    );
    Ok(result)
}

/// Get the compatibility matrix, loading it if not already cached
fn get_compatibility_matrix() -> &'static HashMap<String, Vec<String>> {
    #[cfg(not(test))]
    {
        COMPATIBILITY_MATRIX.get_or_init(|| {
            load_compatibility_matrix().unwrap_or_else(|e| {
                log(LogLevel::Error, &format!("Failed to load license compatibility matrix: {e}"));
                log(LogLevel::Error, "This is a critical error. The application cannot function without license compatibility data.");
                std::process::exit(1);
            })
        })
    }

    #[cfg(test)]
    {
        // For tests, use a thread-local storage to avoid the OnceLock static initialization issue
        use std::cell::RefCell;
        thread_local! {
            static MATRIX: RefCell<Option<HashMap<String, Vec<String>>>> = const { RefCell::new(None) };
        }

        // This is a hack to return a static reference from thread-local storage
        // We leak the memory in tests, which is acceptable for testing
        MATRIX.with(|m| {
            let mut matrix = m.borrow_mut();
            if matrix.is_none() {
                match load_compatibility_matrix() {
                    Ok(loaded_matrix) => {
                        *matrix = Some(loaded_matrix);
                    }
                    Err(e) => {
                        panic!(
                            "License compatibility configuration file not found during testing: {e}"
                        );
                    }
                }
            }

            // Leak the memory to get a static reference (only for tests)
            let leaked: &'static HashMap<String, Vec<String>> =
                Box::leak(Box::new(matrix.as_ref().unwrap().clone()));
            leaked
        })
    }
}

/// Check if a license is compatible with the base project license
pub fn is_license_compatible(
    dependency_license: &str,
    project_license: &str,
    strict: bool,
) -> LicenseCompatibility {
    log(
        LogLevel::Info,
        &format!(
            "Checking if dependency license {dependency_license} is compatible with project license {project_license} (strict={strict})"
        ),
    );

    let compatibility_matrix = get_compatibility_matrix();
    let norm_dependency_license = normalize_license_id(dependency_license);
    let norm_project_license = normalize_license_id(project_license);

    log(
        LogLevel::Info,
        &format!(
            "Normalized licenses: dependency={norm_dependency_license}, project={norm_project_license}"
        ),
    );

    match compatibility_matrix.get(&norm_project_license) {
        Some(compatible_licenses) => {
            if compatible_licenses.contains(&norm_dependency_license) {
                log(
                    LogLevel::Info,
                    &format!(
                        "License {norm_dependency_license} is compatible with project license {norm_project_license}"
                    ),
                );
                LicenseCompatibility::Compatible
            } else {
                log(
                    LogLevel::Warn,
                    &format!(
                        "License {norm_dependency_license} may be incompatible with project license {norm_project_license}"
                    ),
                );
                LicenseCompatibility::Incompatible
            }
        }
        None => {
            if strict {
                log(
                    LogLevel::Warn,
                    &format!("Unknown compatibility for project license {norm_project_license} in strict mode, marking as incompatible"),
                );
                LicenseCompatibility::Incompatible
            } else {
                log(
                    LogLevel::Warn,
                    &format!("Unknown compatibility for project license {norm_project_license}"),
                );
                LicenseCompatibility::Unknown
            }
        }
    }
}

/// Normalize license identifier to a standard format
fn normalize_license_id(license_id: &str) -> String {
    let trimmed = license_id.trim().to_uppercase();

    // Handle common variations and aliases
    match trimmed.as_str() {
        "MIT" | "MIT LICENSE" => "MIT".to_string(),
        "ISC" | "ISC LICENSE" => "ISC".to_string(),
        "0BSD" | "BSD-ZERO-CLAUSE" | "BSD ZERO CLAUSE" => "0BSD".to_string(),
        "UNLICENSE" | "THE UNLICENSE" => "Unlicense".to_string(),
        "WTFPL" | "DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE" => "WTFPL".to_string(),
        "ZLIB" | "ZLIB LICENSE" => "Zlib".to_string(),
        "CC0" | "CC0-1.0" | "CC0 1.0" | "CREATIVE COMMONS ZERO" => "CC0-1.0".to_string(),

        id if id.contains("APACHE") && (id.contains("2.0") || id.contains("2")) => {
            "Apache-2.0".to_string()
        }

        id if id.contains("AGPL") && id.contains("3") => "AGPL-3.0".to_string(),
        id if id.contains("AFFERO") && id.contains("GPL") && id.contains("3") => {
            "AGPL-3.0".to_string()
        }

        id if id.contains("GPL") && id.contains("3") && !id.contains("LGPL") => {
            "GPL-3.0".to_string()
        }
        id if id.contains("GPL") && id.contains("2") && !id.contains("LGPL") => {
            "GPL-2.0".to_string()
        }

        id if id.contains("LGPL") && id.contains("3") => "LGPL-3.0".to_string(),
        id if id.contains("LGPL") && id.contains("2.1") => "LGPL-2.1".to_string(),
        id if id.contains("LGPL") && id.contains("2") && !id.contains("2.1") => {
            "LGPL-2.1".to_string()
        }

        id if id.contains("MPL") && id.contains("2.0") => "MPL-2.0".to_string(),

        id if id.contains("BSD") && (id.contains("3") || id.contains("THREE")) => {
            "BSD-3-Clause".to_string()
        }
        id if id.contains("BSD") && (id.contains("2") || id.contains("TWO")) => {
            "BSD-2-Clause".to_string()
        }

        _ => license_id.to_string(),
    }
}

/// Detect the project's license
pub fn detect_project_license(project_path: &str) -> FeludaResult<Option<String>> {
    log(
        LogLevel::Info,
        &format!("Detecting license for project at path: {project_path}"),
    );

    // Check LICENSE file
    let license_paths = [
        Path::new(project_path).join("LICENSE"),
        Path::new(project_path).join("LICENSE.txt"),
        Path::new(project_path).join("LICENSE.md"),
        Path::new(project_path).join("license"),
        Path::new(project_path).join("COPYING"),
    ];

    for license_path in &license_paths {
        if license_path.exists() {
            log(
                LogLevel::Info,
                &format!("Found license file: {}", license_path.display()),
            );

            match fs::read_to_string(license_path) {
                Ok(content) => {
                    // Check for MIT license
                    if content.contains("MIT License")
                        || content.contains("Permission is hereby granted, free of charge")
                    {
                        log(LogLevel::Info, "Detected MIT license");
                        return Ok(Some("MIT".to_string()));
                    }

                    // Check for GPL-3.0
                    if content.contains("GNU GENERAL PUBLIC LICENSE")
                        && content.contains("Version 3")
                    {
                        log(LogLevel::Info, "Detected GPL-3.0 license");
                        return Ok(Some("GPL-3.0".to_string()));
                    }

                    // Check for Apache-2.0
                    if content.contains("Apache License") && content.contains("Version 2.0") {
                        log(LogLevel::Info, "Detected Apache-2.0 license");
                        return Ok(Some("Apache-2.0".to_string()));
                    }

                    // Check for BSD-3-Clause
                    if content.contains("BSD")
                        && content.contains("Redistribution and use")
                        && content.contains("Neither the name")
                    {
                        log(LogLevel::Info, "Detected BSD-3-Clause license");
                        return Ok(Some("BSD-3-Clause".to_string()));
                    }

                    // Check for LGPL-3.0
                    if content.contains("GNU LESSER GENERAL PUBLIC LICENSE")
                        && content.contains("Version 3")
                    {
                        log(LogLevel::Info, "Detected LGPL-3.0 license");
                        return Ok(Some("LGPL-3.0".to_string()));
                    }

                    // Check for MPL-2.0
                    if content.contains("Mozilla Public License") && content.contains("Version 2.0")
                    {
                        log(LogLevel::Info, "Detected MPL-2.0 license");
                        return Ok(Some("MPL-2.0".to_string()));
                    }

                    log(
                        LogLevel::Warn,
                        "License file found but could not determine license type",
                    );
                }
                Err(err) => {
                    log(
                        LogLevel::Error,
                        &format!("Failed to read license file: {}", license_path.display()),
                    );
                    log_debug("Error details", &err);
                }
            }
        }
    }

    // Check package.json for Node.js projects
    let package_json_path = Path::new(project_path).join("package.json");
    if package_json_path.exists() {
        log(
            LogLevel::Info,
            &format!("Found package.json at {}", package_json_path.display()),
        );

        match fs::read_to_string(&package_json_path) {
            Ok(content) => match serde_json::from_str::<Value>(&content) {
                Ok(json) => {
                    if let Some(license) = json.get("license").and_then(|l| l.as_str()) {
                        log(
                            LogLevel::Info,
                            &format!("Detected license from package.json: {license}"),
                        );
                        return Ok(Some(license.to_string()));
                    }
                }
                Err(err) => {
                    log(
                        LogLevel::Error,
                        &format!("Failed to parse package.json: {err}"),
                    );
                }
            },
            Err(err) => {
                log(
                    LogLevel::Error,
                    &format!(
                        "Failed to read package.json: {}",
                        package_json_path.display()
                    ),
                );
                log_debug("Error details", &err);
            }
        }
    }

    // Check Cargo.toml for Rust projects
    let cargo_toml_path = Path::new(project_path).join("Cargo.toml");
    if cargo_toml_path.exists() {
        log(
            LogLevel::Info,
            &format!("Found Cargo.toml at {}", cargo_toml_path.display()),
        );

        match fs::read_to_string(&cargo_toml_path) {
            Ok(content) => match toml::from_str::<TomlValue>(&content) {
                Ok(toml) => {
                    if let Some(package) = toml.as_table().and_then(|t| t.get("package")) {
                        if let Some(license) = package.get("license").and_then(|l| l.as_str()) {
                            log(
                                LogLevel::Info,
                                &format!("Detected license from Cargo.toml: {license}"),
                            );
                            return Ok(Some(license.to_string()));
                        }
                    }
                }
                Err(err) => {
                    log(
                        LogLevel::Error,
                        &format!("Failed to parse Cargo.toml: {err}"),
                    );
                }
            },
            Err(err) => {
                log(
                    LogLevel::Error,
                    &format!("Failed to read Cargo.toml: {}", cargo_toml_path.display()),
                );
                log_debug("Error details", &err);
            }
        }
    }

    // Check pyproject.toml for Python projects
    let pyproject_toml_path = Path::new(project_path).join("pyproject.toml");
    if pyproject_toml_path.exists() {
        log(
            LogLevel::Info,
            &format!("Found pyproject.toml at {}", pyproject_toml_path.display()),
        );

        match fs::read_to_string(&pyproject_toml_path) {
            Ok(content) => match toml::from_str::<TomlValue>(&content) {
                Ok(toml) => {
                    if let Some(project) = toml.as_table().and_then(|t| t.get("project")) {
                        if let Some(license_info) = project.get("license") {
                            if let Some(license) = license_info.as_str() {
                                log(
                                    LogLevel::Info,
                                    &format!("Detected license from pyproject.toml: {license}"),
                                );
                                return Ok(Some(license.to_string()));
                            } else if let Some(license_table) = license_info.as_table() {
                                if let Some(license_text) =
                                    license_table.get("text").and_then(|t| t.as_str())
                                {
                                    log(
                                        LogLevel::Info,
                                        &format!(
                                            "Detected license from pyproject.toml: {license_text}"
                                        ),
                                    );
                                    return Ok(Some(license_text.to_string()));
                                }
                            }
                        }
                    }
                }
                Err(err) => {
                    log(
                        LogLevel::Error,
                        &format!("Failed to parse pyproject.toml: {err}"),
                    );
                }
            },
            Err(err) => {
                log(
                    LogLevel::Error,
                    &format!(
                        "Failed to read pyproject.toml: {}",
                        pyproject_toml_path.display()
                    ),
                );
                log_debug("Error details", &err);
            }
        }
    }

    log(LogLevel::Warn, "No license detected for project");
    Ok(None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_license_compatibility_display() {
        assert_eq!(LicenseCompatibility::Compatible.to_string(), "Compatible");
        assert_eq!(
            LicenseCompatibility::Incompatible.to_string(),
            "Incompatible"
        );
        assert_eq!(LicenseCompatibility::Unknown.to_string(), "Unknown");
    }

    #[test]
    fn test_license_info_methods() {
        let info = LicenseInfo {
            name: "test_package".to_string(),
            version: "1.0.0".to_string(),
            license: Some("MIT".to_string()),
            is_restrictive: false,
            compatibility: LicenseCompatibility::Compatible,
            osi_status: OsiStatus::Approved,
        };

        assert_eq!(info.name(), "test_package");
        assert_eq!(info.version(), "1.0.0");
        assert_eq!(info.get_license(), "MIT");
        assert!(!info.is_restrictive());
        assert_eq!(info.compatibility(), &LicenseCompatibility::Compatible);
    }

    #[test]
    fn test_license_info_no_license() {
        let info = LicenseInfo {
            name: "test_package".to_string(),
            version: "1.0.0".to_string(),
            license: None,
            is_restrictive: true,
            compatibility: LicenseCompatibility::Unknown,
            osi_status: OsiStatus::Unknown,
        };

        assert_eq!(info.get_license(), "No License");
    }

    #[test]
    fn test_normalize_license_id() {
        assert_eq!(normalize_license_id("MIT"), "MIT");
        assert_eq!(normalize_license_id("mit"), "MIT");
        assert_eq!(normalize_license_id("Apache 2.0"), "Apache-2.0");
        assert_eq!(normalize_license_id("APACHE-2.0"), "Apache-2.0");
        assert_eq!(normalize_license_id("GPL 3.0"), "GPL-3.0");
        assert_eq!(normalize_license_id("gpl-3.0"), "GPL-3.0");
        assert_eq!(normalize_license_id("LGPL 3.0"), "LGPL-3.0");
        assert_eq!(normalize_license_id("MPL 2.0"), "MPL-2.0");
        assert_eq!(normalize_license_id("BSD 3-Clause"), "BSD-3-Clause");
        assert_eq!(normalize_license_id("BSD 2-Clause"), "BSD-2-Clause");
        assert_eq!(normalize_license_id("Unknown License"), "Unknown License");
        assert_eq!(normalize_license_id("  MIT  "), "MIT");
    }

    #[test]
    #[ignore] // Skip this test due to static initialization issues in test runner
    fn test_is_license_compatible_mit_project() {
        assert_eq!(
            is_license_compatible("MIT", "MIT", false),
            LicenseCompatibility::Compatible
        );
        assert_eq!(
            is_license_compatible("BSD-2-Clause", "MIT", false),
            LicenseCompatibility::Compatible
        );
        assert_eq!(
            is_license_compatible("BSD-3-Clause", "MIT", false),
            LicenseCompatibility::Compatible
        );
        assert_eq!(
            is_license_compatible("Apache-2.0", "MIT", false),
            LicenseCompatibility::Compatible
        );
        assert_eq!(
            is_license_compatible("LGPL-3.0", "MIT", false),
            LicenseCompatibility::Incompatible
        );
        assert_eq!(
            is_license_compatible("MPL-2.0", "MIT", false),
            LicenseCompatibility::Incompatible
        );
        assert_eq!(
            is_license_compatible("GPL-3.0", "MIT", false),
            LicenseCompatibility::Incompatible
        );
    }

    #[test]
    fn test_detect_project_license_mit_file() {
        let temp_dir = TempDir::new().unwrap();
        let license_path = temp_dir.path().join("LICENSE");

        std::fs::write(
            &license_path,
            "MIT License\n\nPermission is hereby granted, free of charge...",
        )
        .unwrap();

        let result = detect_project_license(temp_dir.path().to_str().unwrap()).unwrap();
        assert_eq!(result, Some("MIT".to_string()));
    }

    #[test]
    fn test_detect_project_license_no_license() {
        let temp_dir = TempDir::new().unwrap();

        let result = detect_project_license(temp_dir.path().to_str().unwrap()).unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_is_license_ignored_with_no_license() {
        // Should return false when no license is provided
        assert!(!is_license_ignored(None));
    }

    #[test]
    fn test_is_license_ignored_not_in_ignore_list() {
        // License not in ignore list should return false
        // This test assumes no ignore list is configured
        let result = is_license_ignored(Some("GPL-3.0"));
        // Since we can't easily mock the config in this context,
        // we just verify it doesn't panic
        let _ = result;
    }

    #[test]
    fn test_is_license_ignored_empty_license() {
        // Empty string should return false
        assert!(!is_license_ignored(Some("")));
    }
}