bgpkit-commons 0.13.0

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

mod as2org;
mod hegemony;
mod population;
mod sibling_orgs;

use crate::errors::{data_sources, load_methods, modules};
use crate::peeringdb::{Network, Peeringdb};
use crate::{BgpkitCommons, BgpkitCommonsError, LazyLoadable, Result};
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
use serde::{Deserialize, Serialize};
use sibling_orgs::SiblingOrgsUtils;
use std::collections::HashMap;
use std::io::{BufRead, Read};
use tracing::{info, warn};

pub use hegemony::HegemonyData;
pub use population::AsnPopulationData;

/// RIR delegated-stats data for a single ASN.
///
/// Sourced from the five RIR delegated stats files (NRO format). These are
/// authoritative allocation records, updated daily. For each ASN, the
/// registry that allocated it, the allocation date, status, and country
/// code are recorded.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DelegatedInfo {
    /// The RIR that allocated/assigned this ASN (e.g. `"ripencc"`, `"arin"`).
    pub registry: String,
    /// The ISO 3166-1 alpha-2 country code (uppercased).
    pub country: String,
    /// The allocation/assignment date (as-is from the record, format: `YYYYMMDD`).
    pub date: String,
    /// The allocation status (`"allocated"` or `"assigned"`).
    pub status: String,
}

/// IRR data for a single ASN from a single registry source.
///
/// Each entry corresponds to one IRR registry's view of this ASN. An ASN may
/// have entries from multiple registries (e.g. both RIPE and RADB) — the
/// `irr` field on [`AsInfo`] is a `Vec<IrrAsnInfo>` so callers can pick which
/// source(s) to trust.
///
/// Provenance is preserved via `source` (the registry name from the RPSL
/// `source:` attribute). IRR data is self-registered; trust varies by
/// registry authorization model.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IrrAsnInfo {
    /// The `as-name` attribute from the IRR `aut-num` object.
    pub as_name: String,
    /// The `descr` attribute(s), if any.
    pub descr: Vec<String>,
    /// The `source:` attribute — which IRR registry published this object.
    pub source: String,
    /// The `mnt-by` attribute(s) — maintainers controlling this object.
    pub mnt_by: Vec<String>,
    /// Registered IPv4 prefixes from `route` objects with this ASN as origin.
    pub route_prefixes: Vec<Ipv4Net>,
    /// Registered IPv6 prefixes from `route6` objects with this ASN as origin.
    pub route6_prefixes: Vec<Ipv6Net>,
    /// AS-set names that contain this ASN as a direct member.
    pub member_of_sets: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsInfo {
    pub asn: u32,
    pub name: String,
    pub country: String,
    /// Serde defaults on every optional field keep newly-serialized records
    /// (which omit absent fields) readable by the same struct on deserialization.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub as2org: Option<As2orgInfo>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub population: Option<AsnPopulationData>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hegemony: Option<HegemonyData>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub peeringdb: Option<Network>,
    /// RIR delegated-stats allocation data. Present for every allocated ASN.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delegated: Option<DelegatedInfo>,
    /// IRR data per registry source. Empty if the ASN has no IRR registrations.
    /// Multiple sources may have data; callers choose which to trust.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub irr: Vec<IrrAsnInfo>,
}

impl AsInfo {
    /// Returns the preferred name for the AS.
    ///
    /// The order of preference is:
    /// 1. `peeringdb.name` if available
    /// 2. `as2org.org_name` if available and not empty
    /// 3. The default `name` field
    ///
    /// This method does not perform any network access.
    pub fn get_preferred_name(&self) -> String {
        if let Some(peeringdb_data) = &self.peeringdb {
            if let Some(name) = &peeringdb_data.name {
                if !name.is_empty() {
                    return name.clone();
                }
            }
        }
        if let Some(as2org_info) = &self.as2org {
            if !as2org_info.org_name.is_empty() {
                return as2org_info.org_name.clone();
            }
        }
        self.name.clone()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct As2orgInfo {
    pub name: String,
    pub country: String,
    pub org_id: String,
    pub org_name: String,
}

const RIPE_RIS_ASN_TXT_URL: &str = "https://ftp.ripe.net/ripe/asnames/asn.txt";
const BGPKIT_ASN_TXT_MIRROR_URL: &str = "https://data.bgpkit.com/commons/asn.txt";
const BGPKIT_ASNINFO_URL: &str = "https://data.bgpkit.com/commons/asinfo.jsonl";

/// Configuration for which IRR sources to fetch.
///
/// By default, `with_irr()` uses every catalogued source.
/// For finer control, use `with_irr_sources()` to pick specific registries.
///
/// # Example
///
/// ```rust,no_run
/// use bgpkit_commons::asinfo::AsInfoBuilder;
/// use bgpkit_commons::asinfo::IrrSourceConfig;
///
/// // Only RIPE + RADB
/// let config = IrrSourceConfig::only(&["RIPE", "RADB"]).unwrap();
/// let asinfo = AsInfoBuilder::new()
///     .with_irr_sources(config)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone, Default)]
pub struct IrrSourceConfig {
    /// Registry names to fetch. Empty is reserved for [`Self::all`].
    sources: Vec<String>,
}

impl IrrSourceConfig {
    /// Compatibility alias for [`Self::only`].
    pub fn sources(names: &[&str]) -> Result<Self> {
        Self::only(names)
    }

    /// Create a config that fetches exactly the named sources.
    pub fn only(names: &[&str]) -> Result<Self> {
        if names.is_empty() {
            return Err(BgpkitCommonsError::invalid_format(
                "IRR source selection",
                "[]",
                "explicit source selection must not be empty",
            ));
        }
        let selected = crate::irr::sources_by_name(names)?;
        Ok(Self {
            sources: selected
                .into_iter()
                .map(|source| source.name.to_string())
                .collect(),
        })
    }

    /// Create a config that fetches every catalogued source.
    pub fn all() -> Self {
        Self {
            sources: Vec::new(),
        }
    }

    /// Resolve to the actual list of `IrrSource` structs to fetch.
    fn resolve(&self) -> Result<Vec<crate::irr::IrrSource>> {
        if self.sources.is_empty() {
            Ok(crate::irr::all_sources())
        } else {
            let names = self.sources.iter().map(String::as_str).collect::<Vec<_>>();
            crate::irr::sources_by_name(&names)
        }
    }
}

/// Loading profile for AS information data sources.
///
/// Controls which data sources are loaded. Each profile is a curated preset;
/// use [`AsInfoBuilder`] directly for fine-grained control beyond these.
///
/// # Profiles
///
/// | Profile | Sources | Load time | Output size |
/// |---------|---------|-----------|-------------|
/// | [`Minimum`](AsInfoProfile::Minimum) | `asn.txt` only | ~1s | ~37 MB JSONL |
/// | [`Default`](AsInfoProfile::Default) | asn.txt + as2org + population + hegemony + peeringdb | ~30s | ~50 MB JSONL |
/// | [`Full`](AsInfoProfile::Full) | everything: + delegated stats + IRR (all sources) + route prefixes | ~75s | ~210 MB JSONL |
///
/// # Example
///
/// ```rust,no_run
/// use bgpkit_commons::asinfo::AsInfoProfile;
/// use bgpkit_commons::BgpkitCommons;
///
/// let mut commons = BgpkitCommons::new();
/// commons.load_asinfo_with_profile(AsInfoProfile::Full).unwrap();
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AsInfoProfile {
    /// Core `asn.txt` only: AS names + countries. Fast (~1s), minimal data.
    Minimum,

    /// Production default: asn.txt + as2org + population + hegemony + peeringdb.
    /// Matches the current asninfo generator output.
    #[default]
    Default,

    /// Everything: all of Default + delegated stats + IRR data from every
    /// catalogued source, including route prefix lists.
    Full,
}

impl AsInfoProfile {
    /// Convert this profile into a builder configuration.
    pub fn builder(self) -> AsInfoBuilder {
        match self {
            AsInfoProfile::Minimum => AsInfoBuilder::new(),
            AsInfoProfile::Default => AsInfoBuilder::new()
                .with_as2org()
                .with_population()
                .with_hegemony()
                .with_peeringdb(),
            AsInfoProfile::Full => AsInfoBuilder::new()
                .with_as2org()
                .with_population()
                .with_hegemony()
                .with_peeringdb()
                .with_delegated()
                .with_irr()
                .with_irr_route_prefixes(),
        }
    }
}

/// Builder for configuring which data sources to load for AS information.
///
/// This is the canonical way to configure AS info loading. All data sources
/// are opt-in — the core `asn.txt` name/country data always loads; everything
/// else is gated behind a builder method.
///
/// # Example
///
/// ```rust,no_run
/// use bgpkit_commons::asinfo::AsInfoBuilder;
///
/// let asinfo = AsInfoBuilder::new()
///     .with_delegated()
///     .with_irr()
///     .with_as2org()
///     .with_peeringdb()
///     .build()
///     .unwrap();
/// ```
///
/// Selecting specific IRR sources only:
///
/// ```rust,no_run
/// use bgpkit_commons::asinfo::AsInfoBuilder;
/// use bgpkit_commons::asinfo::IrrSourceConfig;
///
/// let asinfo = AsInfoBuilder::new()
///     .with_irr_sources(IrrSourceConfig::only(&["RIPE", "RADB"]).unwrap())
///     .build()
///     .unwrap();
/// ```
#[derive(Default)]
pub struct AsInfoBuilder {
    load_as2org: bool,
    load_population: bool,
    load_hegemony: bool,
    load_peeringdb: bool,
    load_delegated: bool,
    load_irr: bool,
    irr_config: IrrSourceConfig,
    irr_route_prefixes: bool,
}

impl AsInfoBuilder {
    /// Create a new builder with all data sources disabled by default.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable loading CAIDA AS-to-Organization mapping data.
    pub fn with_as2org(mut self) -> Self {
        self.load_as2org = true;
        self
    }

    /// Enable loading APNIC AS population data.
    pub fn with_population(mut self) -> Self {
        self.load_population = true;
        self
    }

    /// Enable loading IIJ IHR hegemony score data.
    pub fn with_hegemony(mut self) -> Self {
        self.load_hegemony = true;
        self
    }

    /// Enable loading PeeringDB data.
    pub fn with_peeringdb(mut self) -> Self {
        self.load_peeringdb = true;
        self
    }

    /// Enable loading RIR delegated-stats data (registry, country, date, status
    /// per ASN from five RIR delegated stats files).
    pub fn with_delegated(mut self) -> Self {
        self.load_delegated = true;
        self
    }

    /// Enable loading IRR data using every source in the IRR catalog.
    pub fn with_irr(mut self) -> Self {
        self.load_irr = true;
        self
    }

    /// Enable loading IRR data with a custom set of sources.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use bgpkit_commons::asinfo::{AsInfoBuilder, IrrSourceConfig};
    ///
    /// let asinfo = AsInfoBuilder::new()
    ///     .with_irr_sources(IrrSourceConfig::only(&["RIPE", "RADB"]).unwrap())
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_irr_sources(mut self, config: IrrSourceConfig) -> Self {
        self.load_irr = true;
        self.irr_config = config;
        self
    }

    /// Enable collecting IRR route/route6 prefix lists per ASN.
    ///
    /// Off by default — prefix lists are the largest data component
    /// (~90MB JSON for all sources). Only enable when you need the
    /// actual registered prefixes, not just AS names/metadata.
    pub fn with_irr_route_prefixes(mut self) -> Self {
        self.irr_route_prefixes = true;
        self
    }

    /// Enable all optional data, including route prefixes from every IRR source.
    pub fn with_all(mut self) -> Self {
        self.load_as2org = true;
        self.load_population = true;
        self.load_hegemony = true;
        self.load_peeringdb = true;
        self.load_delegated = true;
        self.load_irr = true;
        self.irr_config = IrrSourceConfig::all();
        self.irr_route_prefixes = true;
        self
    }

    /// Build the AsInfoUtils with the configured data sources.
    pub fn build(self) -> Result<AsInfoUtils> {
        AsInfoUtils::from_builder(&self)
    }

    /// Internal: expose config for AsInfoUtils construction.
    fn config(&self) -> Result<AsInfoLoadConfig> {
        Ok(AsInfoLoadConfig {
            load_as2org: self.load_as2org,
            load_population: self.load_population,
            load_hegemony: self.load_hegemony,
            load_peeringdb: self.load_peeringdb,
            load_delegated: self.load_delegated,
            load_irr: self.load_irr,
            irr_sources: self.irr_config.resolve()?,
            irr_route_prefixes: self.irr_route_prefixes,
        })
    }
}

/// Internal configuration extracted from the builder.
#[derive(Debug, Clone)]
struct AsInfoLoadConfig {
    load_as2org: bool,
    load_population: bool,
    load_hegemony: bool,
    load_peeringdb: bool,
    load_delegated: bool,
    load_irr: bool,
    irr_sources: Vec<crate::irr::IrrSource>,
    irr_route_prefixes: bool,
}

pub struct AsInfoUtils {
    pub asinfo_map: HashMap<u32, AsInfo>,
    pub sibling_orgs: Option<SiblingOrgsUtils>,
    config: AsInfoLoadConfig,
}

impl AsInfoUtils {
    /// Build from a builder (canonical path).
    fn from_builder(builder: &AsInfoBuilder) -> Result<Self> {
        let config = builder.config()?;
        let asinfo_map = get_asinfo_map(&config)?;
        let sibling_orgs = if config.load_as2org {
            Some(SiblingOrgsUtils::new()?)
        } else {
            None
        };
        Ok(AsInfoUtils {
            asinfo_map,
            sibling_orgs,
            config,
        })
    }

    pub fn new_from_cached() -> Result<Self> {
        let asinfo_map = get_asinfo_map_cached()?;
        let sibling_orgs = Some(SiblingOrgsUtils::new()?);
        Ok(AsInfoUtils {
            asinfo_map,
            sibling_orgs,
            config: AsInfoLoadConfig {
                load_as2org: true,
                load_population: true,
                load_hegemony: true,
                load_peeringdb: true,
                load_delegated: true,
                load_irr: true,
                irr_sources: crate::irr::all_sources(),
                irr_route_prefixes: false,
            },
        })
    }

    pub fn reload(&mut self) -> Result<()> {
        self.asinfo_map = get_asinfo_map(&self.config)?;
        Ok(())
    }

    pub fn get(&self, asn: u32) -> Option<&AsInfo> {
        self.asinfo_map.get(&asn)
    }
}

impl LazyLoadable for AsInfoUtils {
    fn reload(&mut self) -> Result<()> {
        self.reload()
    }

    fn is_loaded(&self) -> bool {
        !self.asinfo_map.is_empty()
    }

    fn loading_status(&self) -> &'static str {
        if self.is_loaded() {
            "ASInfo data loaded"
        } else {
            "ASInfo data not loaded"
        }
    }
}

pub fn get_asinfo_map_cached() -> Result<HashMap<u32, AsInfo>> {
    info!("loading asinfo from previously generated BGPKIT cache file...");
    let mut asnames_map = HashMap::new();
    let reader = oneio::get_reader(BGPKIT_ASNINFO_URL)?;
    for line in std::io::BufReader::new(reader).lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        let asinfo: AsInfo = serde_json::from_str(&line)?;
        asnames_map.insert(asinfo.asn, asinfo);
    }
    Ok(asnames_map)
}

/// Project a source-faithful delegated-statistics record into AsInfo data.
///
/// Only `asn` records with `allocated`/`assigned` status and a real (non-empty,
/// non-`*`) country code are kept; private-use ASN ranges (RFC 6996:
/// 64512-65534 and 4200000000+) are excluded. Ranges are expanded per-ASN
/// (`value` is a count).
fn project_delegated_record(
    record: crate::delegated::DelegatedRecord,
    map: &mut HashMap<u32, DelegatedInfo>,
) {
    if record.record_type != "asn" {
        return;
    }
    let status = record.status.trim();
    if status != "allocated" && status != "assigned" {
        return;
    }
    let cc = record.country.trim();
    if cc.is_empty() || cc == "*" {
        return;
    }
    let (Ok(start), Ok(count)) = (record.start.parse::<u64>(), record.value.parse::<u64>()) else {
        return;
    };
    let registry = record.registry.trim().to_lowercase();
    let country = cc.to_uppercase();
    let date = record.date.trim().to_string();
    for asn in start..start.saturating_add(count) {
        if asn > u32::MAX as u64 {
            break;
        }
        let asn = asn as u32;
        if (64512..=65534).contains(&asn) || asn >= 4_200_000_000 {
            continue;
        }
        map.entry(asn).or_insert(DelegatedInfo {
            registry: registry.clone(),
            country: country.clone(),
            date: date.clone(),
            status: status.to_string(),
        });
    }
}

#[cfg(test)]
fn project_delegated_stats(text: &str, map: &mut HashMap<u32, DelegatedInfo>) {
    for record in crate::delegated::parse_reader(text.as_bytes()).flatten() {
        project_delegated_record(record, map);
    }
}

/// Look up optional enrichment data (as2org, population, hegemony, peeringdb)
/// for an ASN from already-loaded datasets. Shared by the main `asn.txt` parse
/// loop and the delegated-stats fill so both paths behave identically.
#[allow(clippy::type_complexity)]
fn lookup_enrichment(
    asn: u32,
    as2org_utils: Option<&as2org::As2org>,
    population_utils: Option<&population::AsnPopulation>,
    hegemony_utils: Option<&hegemony::Hegemony>,
    peeringdb_utils: Option<&Peeringdb>,
) -> (
    Option<As2orgInfo>,
    Option<AsnPopulationData>,
    Option<HegemonyData>,
    Option<Network>,
) {
    let as2org = as2org_utils.and_then(|as2org_data| {
        as2org_data.get_as_info(asn).map(|info| As2orgInfo {
            name: info.name.clone(),
            country: info.country_code.clone(),
            org_id: info.org_id.clone(),
            org_name: info.org_name.clone(),
        })
    });
    let population = population_utils.and_then(|p| p.get(asn));
    let hegemony = hegemony_utils.and_then(|h| h.get_score(asn).cloned());
    let peeringdb = peeringdb_utils.and_then(|h| h.get_network(asn).cloned());
    (as2org, population, hegemony, peeringdb)
}

/// Load RIR delegated stats and attach [`DelegatedInfo`] to every ASN in the
/// map. For ASNs missing from `asn.txt`, new entries are created with
/// `name: "UNKNOWN"` and the delegated country code.
///
/// Delegated stats are authoritative allocation records updated daily, covering
/// newly-allocated ASNs that `asn.txt` lags on by days to weeks. Every ASN
/// (not just gap ASNs) gets structured delegated data attached.
///
/// Best-effort: failures fetching individual files are logged and skipped.
fn fill_delegated_data(
    asnames_map: &mut HashMap<u32, AsInfo>,
    as2org_utils: Option<&as2org::As2org>,
    population_utils: Option<&population::AsnPopulation>,
    hegemony_utils: Option<&hegemony::Hegemony>,
    peeringdb_utils: Option<&Peeringdb>,
) {
    let mut delegated: HashMap<u32, DelegatedInfo> = HashMap::new();
    for url in crate::delegated::RIR_DELEGATED_STATS_URLS {
        match crate::delegated::fetch(url) {
            Ok(reader) => {
                for record in crate::delegated::parse_reader(reader) {
                    match record {
                        Ok(record) => project_delegated_record(record, &mut delegated),
                        Err(e) => warn!("failed to parse delegated stats from {url}: {e}"),
                    }
                }
            }
            Err(e) => warn!("failed to load delegated stats from {}: {}", url, e),
        }
    }
    attach_delegated_data(
        asnames_map,
        delegated,
        as2org_utils,
        population_utils,
        hegemony_utils,
        peeringdb_utils,
    );
}

/// Attach per-ASN [`DelegatedInfo`] values to the map, creating `AsInfo`
/// entries for ASNs absent from `asn.txt` (with `name: "UNKNOWN"` and the
/// delegated country as the base country).
///
/// Only the `delegated` field of existing entries is modified; the base `name`
/// and `country` fields are never overwritten. When the same ASN appears in
/// multiple RIR files (possible during inter-RIR transfers), the first
/// [`DelegatedInfo`] encountered wins; file order is the order of
/// [`crate::delegated::RIR_DELEGATED_STATS_URLS`].
fn attach_delegated_data(
    asnames_map: &mut HashMap<u32, AsInfo>,
    delegated: HashMap<u32, DelegatedInfo>,
    as2org_utils: Option<&as2org::As2org>,
    population_utils: Option<&population::AsnPopulation>,
    hegemony_utils: Option<&hegemony::Hegemony>,
    peeringdb_utils: Option<&Peeringdb>,
) {
    let mut new_entries = 0usize;
    let mut attached = 0usize;
    for (asn, delegated_info) in delegated {
        asnames_map
            .entry(asn)
            .and_modify(|info| {
                info.delegated = Some(delegated_info.clone());
                attached += 1;
            })
            .or_insert_with(|| {
                new_entries += 1;
                let (as2org, population, hegemony, peeringdb) = lookup_enrichment(
                    asn,
                    as2org_utils,
                    population_utils,
                    hegemony_utils,
                    peeringdb_utils,
                );
                AsInfo {
                    asn,
                    name: "UNKNOWN".to_string(),
                    country: delegated_info.country.clone(),
                    as2org,
                    population,
                    hegemony,
                    peeringdb,
                    delegated: Some(delegated_info.clone()),
                    irr: Vec::new(),
                }
            });
    }
    info!(
        "delegated stats: {attached} existing entries enriched, {new_entries} new entries created"
    );
}
/// Enrich AsInfo entries with structured IRR data from selected sources.
///
/// For each IRR source (RIPE, APNIC, ARIN, LACNIC, AFRINIC, NTTCOM, RADB),
/// collects:
/// - `aut-num` objects → `as-name`, `descr`, `mnt-by`
/// - `route` objects → registered IPv4 prefixes per ASN
/// - `route6` objects → registered IPv6 prefixes per ASN
/// - `as-set` objects → reverse membership (which sets contain this ASN)
///
/// Each source produces an [`IrrAsnInfo`] entry in the `irr` Vec, so callers
/// can pick which source(s) to trust. Per-source failures are logged and
/// skipped.
///
fn enrich_from_irr(
    asnames_map: &mut HashMap<u32, AsInfo>,
    irr_sources: &[crate::irr::IrrSource],
    collect_route_prefixes: bool,
) {
    use crate::irr::sources::DumpFormat;
    use crate::irr::types::{IrrObject, IrrObjectType};
    use std::collections::HashMap as StdMap;

    // Per-source accumulator: source_name -> (asn -> IrrAsnInfo builder)
    let mut per_source: StdMap<String, StdMap<u32, IrrAsnInfoBuilder>> = StdMap::new();

    // Track which dump URLs we've already parsed (whole-DB files serve all types).
    let mut parsed_urls: std::collections::HashSet<String> = std::collections::HashSet::new();

    let wanted_types: Vec<IrrObjectType> = if collect_route_prefixes {
        vec![
            IrrObjectType::AutNum,
            IrrObjectType::Route,
            IrrObjectType::Route6,
            IrrObjectType::AsSet,
        ]
    } else {
        // Without route prefixes: only aut-num + as-set.
        // For WholeDb sources this means we still download once but skip route objects.
        // For SplitFile sources we skip the route/route6 files entirely.
        vec![IrrObjectType::AutNum, IrrObjectType::AsSet]
    };

    for source in irr_sources.iter().cloned() {
        let source_name = source.name.to_string();

        // For each source, figure out the unique URLs to download.
        // SplitFile sources have one URL per type; WholeDb has a single URL
        // that we parse once and extract all types.
        let mut urls_to_parse: Vec<(String, Vec<IrrObjectType>)> = Vec::new();

        if source.format == DumpFormat::WholeDb {
            // Single URL, parse once for all types
            let url = source.dump_urls(IrrObjectType::AutNum);
            if let Some(dump) = url.first() {
                urls_to_parse.push((dump.url.clone(), wanted_types.to_vec()));
            }
        } else {
            // Split files: one URL per type
            for obj_type in &wanted_types {
                for dump in source.dump_urls(*obj_type) {
                    urls_to_parse.push((dump.url.clone(), vec![*obj_type]));
                }
            }
        }

        for (url, _types_for_url) in urls_to_parse {
            if parsed_urls.contains(&url) {
                continue;
            }
            parsed_urls.insert(url.clone());

            let sn = source_name.clone();

            match crate::irr::parse_dump(
                &crate::irr::IrrDumpUrl {
                    url: url.clone(),
                    transport: source.transport,
                    format: source.format,
                },
                |obj| {
                    let source_map = per_source.entry(sn.clone()).or_default();
                    match &obj {
                        IrrObject::AutNum(a) => {
                            let entry = source_map.entry(a.asn).or_default();
                            entry.source = a.source.clone();
                            entry.as_name = a.as_name.clone();
                            entry.descr = a.descr.clone();
                            if let Some(mnt) = a.extra.get("mnt-by") {
                                entry.mnt_by = mnt.clone();
                            }
                        }
                        // Route/route6 prefixes are collected only when
                        // explicitly enabled. WholeDb dumps still download once
                        // (URL dedup above) but route objects are skipped here
                        // in the default no-prefix mode.
                        IrrObject::Route(r) if collect_route_prefixes => {
                            let entry = source_map.entry(r.origin).or_default();
                            if entry.source.is_empty() {
                                entry.source = r.source.clone();
                            }
                            if let IpNet::V4(prefix) = r.prefix {
                                entry.route_prefixes.push(prefix);
                            }
                        }
                        IrrObject::Route6(r) if collect_route_prefixes => {
                            let entry = source_map.entry(r.origin).or_default();
                            if entry.source.is_empty() {
                                entry.source = r.source.clone();
                            }
                            if let IpNet::V6(prefix) = r.prefix {
                                entry.route6_prefixes.push(prefix);
                            }
                        }
                        IrrObject::AsSet(s) => {
                            let set_name = s.name.clone();
                            for &member_asn in &s.members {
                                let entry = source_map.entry(member_asn).or_default();
                                if entry.source.is_empty() {
                                    entry.source = s.source.clone();
                                }
                                entry.member_of_sets.push(set_name.clone());
                            }
                        }
                        _ => {}
                    }
                },
            ) {
                Ok(stats) => info!(
                    "IRR from {source_name} ({url}): {} objects extracted",
                    stats.extracted
                ),
                Err(e) => warn!("failed to load IRR from {source_name} ({url}): {e}"),
            }
        }
    }

    attach_irr_data(asnames_map, per_source, irr_sources);
}

/// Attach per-source [`IrrAsnInfo`] values to each ASN.
///
/// Only the `irr` field of existing entries is modified; the base `name` and
/// `country` fields are never overwritten. Entries are produced in the order
/// of `irr_sources`, one per registry that has any data for the ASN.
fn attach_irr_data(
    asnames_map: &mut HashMap<u32, AsInfo>,
    per_source: std::collections::HashMap<
        String,
        std::collections::HashMap<u32, IrrAsnInfoBuilder>,
    >,
    irr_sources: &[crate::irr::IrrSource],
) {
    let mut irr_attached = 0usize;

    for (asn, info) in asnames_map.iter_mut() {
        let mut irr_entries: Vec<IrrAsnInfo> = Vec::new();

        for source in irr_sources.iter().cloned() {
            if let Some(source_map) = per_source.get(source.name) {
                if let Some(builder) = source_map.get(asn) {
                    irr_entries.push(builder.clone().build());
                }
            }
        }

        if !irr_entries.is_empty() {
            info.irr = irr_entries;
            irr_attached += 1;
        }
    }

    info!("IRR data attached to {irr_attached} ASNs");
}

/// Builder for IrrAsnInfo — accumulates data from multiple object types
/// (aut-num, route, route6, as-set) before producing the final struct.
#[derive(Debug, Clone, Default)]
struct IrrAsnInfoBuilder {
    as_name: String,
    descr: Vec<String>,
    source: String,
    mnt_by: Vec<String>,
    route_prefixes: Vec<Ipv4Net>,
    route6_prefixes: Vec<Ipv6Net>,
    member_of_sets: Vec<String>,
}

impl IrrAsnInfoBuilder {
    fn build(self) -> IrrAsnInfo {
        IrrAsnInfo {
            as_name: self.as_name,
            descr: self.descr,
            source: self.source,
            mnt_by: self.mnt_by,
            route_prefixes: self.route_prefixes,
            route6_prefixes: self.route6_prefixes,
            member_of_sets: self.member_of_sets,
        }
    }
}

/// Loads the ASN information map and returns it.
///
/// The core RIPE NCC `asn.txt` data (plus the RIR delegated-stats fill) is
/// required: load failures propagate as `Err`. Optional enrichment datasets
/// (as2org, population, hegemony, peeringdb) fail soft — a failed download or
/// API error (e.g., PeeringDB rate limiting without `PEERINGDB_API_KEY`)
/// logs a warning and proceeds with that dataset's fields left as `None`.
/// Loads the ASN information map and returns it.
///
/// The core RIPE NCC `asn.txt` data (plus the RIR delegated-stats fill) is
/// required: load failures propagate as `Err`. Optional enrichment datasets
/// (as2org, population, hegemony, peeringdb) fail soft — a failed download or
/// API error (e.g., PeeringDB rate limiting without `PEERINGDB_API_KEY`)
/// logs a warning and proceeds with that dataset's fields left as `None`.
fn get_asinfo_map(config: &AsInfoLoadConfig) -> Result<HashMap<u32, AsInfo>> {
    let load_as2org = config.load_as2org;
    let load_population = config.load_population;
    let load_hegemony = config.load_hegemony;
    let load_peeringdb = config.load_peeringdb;
    let read_text = |url: &str| -> Result<String> {
        let mut text = String::new();
        oneio::get_reader(url)?.read_to_string(&mut text)?;
        Ok(text)
    };
    let text = match read_text(BGPKIT_ASN_TXT_MIRROR_URL) {
        Ok(t) => t,
        Err(_) => match read_text(RIPE_RIS_ASN_TXT_URL) {
            Ok(t) => t,
            Err(e) => {
                return Err(BgpkitCommonsError::data_source_error(
                    data_sources::BGPKIT,
                    format!(
                        "error reading asinfo (neither mirror or original works): {}",
                        e
                    ),
                ));
            }
        },
    };

    let as2org_utils = if load_as2org {
        info!("loading as2org data from CAIDA...");
        match as2org::As2org::new(None) {
            Ok(data) => Some(data),
            Err(e) => {
                warn!("failed to load as2org data, proceeding without it: {e}");
                None
            }
        }
    } else {
        None
    };
    let population_utils = if load_population {
        info!("loading ASN population data from APNIC...");
        match population::AsnPopulation::new() {
            Ok(data) => Some(data),
            Err(e) => {
                warn!("failed to load population data, proceeding without it: {e}");
                None
            }
        }
    } else {
        None
    };
    let hegemony_utils = if load_hegemony {
        info!("loading IIJ IHR hegemony score data from BGPKIT mirror...");
        match hegemony::Hegemony::new() {
            Ok(data) => Some(data),
            Err(e) => {
                warn!("failed to load hegemony data, proceeding without it: {e}");
                None
            }
        }
    } else {
        None
    };
    let peeringdb_utils = if load_peeringdb {
        info!("loading peeringdb data...");
        match Peeringdb::new_networks_only() {
            Ok(data) => Some(data),
            Err(e) => {
                warn!(
                    "failed to load peeringdb data, proceeding without it: {e} \
                     (hint: set PEERINGDB_API_KEY to avoid rate limiting)"
                );
                None
            }
        }
    } else {
        None
    };

    let asnames = text
        .lines()
        .filter_map(|line| {
            let (asn_str, name_country_str) = match line.split_once(' ') {
                Some((asn, name)) => (asn, name),
                None => return None,
            };
            let (name_str, country_str) = match name_country_str.rsplit_once(", ") {
                Some((name, country)) => (name, country),
                None => return None,
            };
            let asn = asn_str.parse::<u32>().unwrap();
            let (as2org, population, hegemony, peeringdb) = lookup_enrichment(
                asn,
                as2org_utils.as_ref(),
                population_utils.as_ref(),
                hegemony_utils.as_ref(),
                peeringdb_utils.as_ref(),
            );
            Some(AsInfo {
                asn,
                name: name_str.to_string(),
                country: country_str.to_string(),
                as2org,
                population,
                hegemony,
                peeringdb,
                delegated: None,
                irr: Vec::new(),
            })
        })
        .collect::<Vec<AsInfo>>();

    let mut asnames_map = HashMap::new();
    for asname in asnames {
        asnames_map.insert(asname.asn, asname);
    }

    if config.load_delegated {
        info!("loading delegated stats data...");
        fill_delegated_data(
            &mut asnames_map,
            as2org_utils.as_ref(),
            population_utils.as_ref(),
            hegemony_utils.as_ref(),
            peeringdb_utils.as_ref(),
        );
    }

    if config.load_irr {
        info!("enriching from IRR data...");
        enrich_from_irr(
            &mut asnames_map,
            &config.irr_sources,
            config.irr_route_prefixes,
        );
    }

    Ok(asnames_map)
}

impl BgpkitCommons {
    /// Returns a HashMap containing all AS information.
    ///
    /// # Returns
    ///
    /// - `Ok(HashMap<u32, AsInfo>)`: A HashMap where the key is the ASN and the value is the corresponding AsInfo.
    /// - `Err`: If the asinfo is not loaded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use bgpkit_commons::BgpkitCommons;
    ///
    /// let mut bgpkit = BgpkitCommons::new();
    /// bgpkit.load_asinfo_with_profile(Default::default()).unwrap();
    /// let all_asinfo = bgpkit.asinfo_all().unwrap();
    /// ```
    pub fn asinfo_all(&self) -> Result<HashMap<u32, AsInfo>> {
        if self.asinfo.is_none() {
            return Err(BgpkitCommonsError::module_not_loaded(
                modules::ASINFO,
                load_methods::LOAD_ASINFO,
            ));
        }

        Ok(self.asinfo.as_ref().unwrap().asinfo_map.clone())
    }

    /// Retrieves AS information for a specific ASN.
    ///
    /// # Arguments
    ///
    /// * `asn` - The Autonomous System Number to look up.
    ///
    /// # Returns
    ///
    /// - `Ok(Some(AsInfo))`: The AS information if found.
    /// - `Ok(None)`: If the ASN is not found in the database.
    /// - `Err`: If the asinfo is not loaded.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use bgpkit_commons::BgpkitCommons;
    ///
    /// let mut bgpkit = BgpkitCommons::new();
    /// bgpkit.load_asinfo_with_profile(Default::default()).unwrap();
    /// let asinfo = bgpkit.asinfo_get(3333).unwrap();
    /// ```
    pub fn asinfo_get(&self, asn: u32) -> Result<Option<AsInfo>> {
        if self.asinfo.is_none() {
            return Err(BgpkitCommonsError::module_not_loaded(
                modules::ASINFO,
                load_methods::LOAD_ASINFO,
            ));
        }

        Ok(self.asinfo.as_ref().unwrap().get(asn).cloned())
    }

    /// Checks if two ASNs are siblings (belong to the same organization).
    ///
    /// # Arguments
    ///
    /// * `asn1` - The first Autonomous System Number.
    /// * `asn2` - The second Autonomous System Number.
    ///
    /// # Returns
    ///
    /// - `Ok(bool)`: True if the ASNs are siblings, false otherwise.
    /// - `Err`: If the asinfo is not loaded or not loaded with as2org data.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use bgpkit_commons::BgpkitCommons;
    ///
    /// let mut bgpkit = BgpkitCommons::new();
    /// bgpkit.load_asinfo_with(bgpkit.asinfo_builder().with_as2org()).unwrap();
    /// let are_siblings = bgpkit.asinfo_are_siblings(3333, 3334).unwrap();
    /// ```
    ///
    /// # Note
    ///
    /// This function requires the asinfo to be loaded with as2org data.
    pub fn asinfo_are_siblings(&self, asn1: u32, asn2: u32) -> Result<bool> {
        if self.asinfo.is_none() {
            return Err(BgpkitCommonsError::module_not_loaded(
                modules::ASINFO,
                load_methods::LOAD_ASINFO,
            ));
        }
        if !self.asinfo.as_ref().unwrap().config.load_as2org {
            return Err(BgpkitCommonsError::module_not_configured(
                modules::ASINFO,
                "as2org data",
                "load_asinfo() with as2org=true",
            ));
        }

        let info_1_opt = self.asinfo_get(asn1)?;
        let info_2_opt = self.asinfo_get(asn2)?;

        if let (Some(info1), Some(info2)) = (info_1_opt, info_2_opt) {
            if let (Some(org1), Some(org2)) = (info1.as2org, info2.as2org) {
                let org_id_1 = org1.org_id;
                let org_id_2 = org2.org_id;

                return Ok(org_id_1 == org_id_2
                    || self
                        .asinfo
                        .as_ref()
                        .and_then(|a| a.sibling_orgs.as_ref())
                        .map(|s| s.are_sibling_orgs(org_id_1.as_str(), org_id_2.as_str()))
                        .unwrap_or(false));
            }
        }
        Ok(false)
    }
}

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

    /// Helper: check country from DelegatedInfo in map.
    fn cc(map: &HashMap<u32, DelegatedInfo>, asn: u32) -> Option<&str> {
        map.get(&asn).map(|d| d.country.as_str())
    }

    #[test]
    fn test_parse_delegated_stats_basic() {
        let text = "\
2|ripencc|ZZ|209|20250704|00000000+00000000+00000000|UTF-8
ripencc|*|asn|*|39634|summary
ripencc|GB|asn|219157|1|20260722|allocated
ripencc|DE|asn|219125|1|20260728|allocated
arin||asn|212|1||reserved|
arin|*|asn|*|32843|summary
arin|US|asn|402598|1|20260604|assigned|
apnic|BD|asn|154708|1|20260609|allocated
ripencc|NL|asn|1000|4|19970901|allocated
ripencc|NL|ipv4|185.0.0.0|65536|20000101|allocated
";
        let mut map = HashMap::new();
        project_delegated_stats(text, &mut map);
        assert_eq!(cc(&map, 219157), Some("GB"));
        assert_eq!(cc(&map, 219125), Some("DE"));
        assert_eq!(cc(&map, 402598), Some("US"));
        assert_eq!(cc(&map, 154708), Some("BD"));
        // range expansion: AS1000..=AS1003 (value is a count of 4)
        assert_eq!(cc(&map, 1000), Some("NL"));
        assert_eq!(cc(&map, 1003), Some("NL"));
        assert!(!map.contains_key(&1004));
        // reserved entries with empty CC are skipped
        assert!(!map.contains_key(&212));
        // non-asn records are skipped
        assert_eq!(map.len(), 8);
        // Verify structured fields
        let info = &map[&219157];
        assert_eq!(info.registry, "ripencc");
        assert_eq!(info.status, "allocated");
        assert_eq!(info.date, "20260722");
    }

    #[test]
    fn test_parse_delegated_stats_skips_private_and_invalid() {
        let text = "\
arin|US|asn|64512|1023|19891201|reserved
arin|US|asn|4200000000|9999|19891201|reserved
arin|US|asn|notanumber|1|20200101|allocated
arin|US|asn|123|notacount|20200101|allocated
";
        let mut map = HashMap::new();
        project_delegated_stats(text, &mut map);
        assert!(map.is_empty());
    }

    #[test]
    fn test_parse_delegated_stats_status_filter() {
        // reserved/available records are dropped even when they carry a
        // real-looking country code; only allocated/assigned are kept
        let text = "\
arin|US|asn|300000|1|20200101|reserved
arin|US|asn|300001|1|20200101|available
arin|US|asn|300002|1|20200101|allocated
arin|US|asn|300003|1|20200101|assigned
";
        let mut map = HashMap::new();
        project_delegated_stats(text, &mut map);
        assert!(!map.contains_key(&300000));
        assert!(!map.contains_key(&300001));
        assert_eq!(cc(&map, 300002), Some("US"));
        assert_eq!(cc(&map, 300003), Some("US"));
        assert_eq!(map.len(), 2);
    }

    #[test]
    fn test_parse_delegated_stats_private_boundary() {
        // AS65535 (last private 16-bit ASN, not in 64512..=65534) is kept;
        // AS65534 is dropped. RFC 6996 documentation ASN 64496 is public but
        // unused; it is kept since only the exact private ranges are filtered.
        let text = "\
arin|US|asn|65535|1|19891201|allocated
arin|US|asn|65534|1|19891201|allocated
arin|US|asn|64496|1|19891201|allocated
arin|US|asn|4199999999|1|19891201|allocated
arin|US|asn|4200000000|1|19891201|allocated
";
        let mut map = HashMap::new();
        project_delegated_stats(text, &mut map);
        assert_eq!(cc(&map, 65535), Some("US"));
        assert!(!map.contains_key(&65534));
        assert_eq!(cc(&map, 64496), Some("US"));
        assert_eq!(cc(&map, 4199999999), Some("US"));
        assert!(!map.contains_key(&4200000000));
    }

    #[test]
    fn test_parse_delegated_stats_case_normalization() {
        let text = "lacnic|br|asn|269000|1|20150101|allocated\n";
        let mut map = HashMap::new();
        project_delegated_stats(text, &mut map);
        assert_eq!(cc(&map, 269000), Some("BR"));
        assert_eq!(map[&269000].registry, "lacnic");
    }

    #[test]
    fn test_parse_delegated_stats_malformed_lines() {
        let text = "\
# comment line

ripencc|GB|asn
ripencc|GB|ipv6|2001:db8::|32|20200101|allocated
some garbage line with no pipes at all
|GB|asn|100|1|20200101|allocated
ripencc|GB|asn|100|1|20200101
ripencc|GB|asn|100|1|20200101|allocated|extra|fields|ok
";
        let mut map = HashMap::new();
        project_delegated_stats(text, &mut map);
        // empty registry is kept (only CC matters), short lines dropped,
        // extended lines with >7 fields still parsed
        assert_eq!(cc(&map, 100), Some("GB"));
        assert_eq!(map.len(), 1);
    }

    #[test]
    fn test_profiles_match_asninfo_v1_and_full_uses_all_sources() {
        let minimum = AsInfoProfile::Minimum.builder().config().unwrap();
        assert!(!minimum.load_as2org);
        assert!(!minimum.load_population);
        assert!(!minimum.load_hegemony);
        assert!(!minimum.load_peeringdb);
        assert!(!minimum.load_delegated);
        assert!(!minimum.load_irr);

        let default = AsInfoProfile::Default.builder().config().unwrap();
        assert!(default.load_as2org);
        assert!(default.load_population);
        assert!(default.load_hegemony);
        assert!(default.load_peeringdb);
        assert!(!default.load_delegated);
        assert!(!default.load_irr);

        let full = AsInfoProfile::Full.builder().config().unwrap();
        assert!(full.load_delegated);
        assert!(full.load_irr);
        assert!(full.irr_route_prefixes);
        assert_eq!(full.irr_sources.len(), crate::irr::all_sources().len());

        let all = AsInfoBuilder::new().with_all().config().unwrap();
        assert!(all.irr_route_prefixes);
        assert_eq!(all.irr_sources.len(), crate::irr::all_sources().len());
    }

    #[test]
    fn test_custom_irr_sources_are_validated() {
        assert!(IrrSourceConfig::only(&[]).is_err());
        assert!(IrrSourceConfig::sources(&[]).is_err());
        assert!(IrrSourceConfig::sources(&["RIPE", "NOT-A-REGISTRY"]).is_err());

        let selected = IrrSourceConfig::sources(&["RIPE", "RADB"]).unwrap();
        let config = AsInfoBuilder::new()
            .with_irr_sources(selected)
            .config()
            .unwrap();
        assert_eq!(
            config
                .irr_sources
                .iter()
                .map(|source| source.name)
                .collect::<Vec<_>>(),
            vec!["RIPE", "RADB"]
        );
    }

    #[test]
    fn delegated_enrichment_never_overwrites_name_or_country() {
        let mut map = HashMap::new();
        map.insert(
            13335,
            AsInfo {
                asn: 13335,
                name: "CLOUDFLARENET".to_string(),
                country: "US".to_string(),
                as2org: None,
                population: None,
                hegemony: None,
                peeringdb: None,
                delegated: None,
                irr: Vec::new(),
            },
        );

        let mut delegated = HashMap::new();
        delegated.insert(
            13335,
            DelegatedInfo {
                registry: "ripencc".to_string(),
                country: "GB".to_string(),
                date: "20260722".to_string(),
                status: "allocated".to_string(),
            },
        );
        // ASN missing from asn.txt: a new entry is created, not an overwrite.
        delegated.insert(
            400644,
            DelegatedInfo {
                registry: "arin".to_string(),
                country: "US".to_string(),
                date: "20200101".to_string(),
                status: "allocated".to_string(),
            },
        );

        attach_delegated_data(&mut map, delegated, None, None, None, None);

        // Existing entry: base fields untouched, delegated attached.
        let existing = &map[&13335];
        assert_eq!(existing.name, "CLOUDFLARENET");
        assert_eq!(existing.country, "US");
        assert_eq!(existing.delegated.as_ref().unwrap().registry, "ripencc");

        // New entry: UNKNOWN name, delegated country as base country.
        let new_entry = &map[&400644];
        assert_eq!(new_entry.name, "UNKNOWN");
        assert_eq!(new_entry.country, "US");
        assert_eq!(new_entry.delegated.as_ref().unwrap().registry, "arin");
    }

    #[test]
    fn irr_enrichment_never_overwrites_name_or_country() {
        let mut map = HashMap::new();
        map.insert(
            13335,
            AsInfo {
                asn: 13335,
                name: "CLOUDFLARENET".to_string(),
                country: "US".to_string(),
                as2org: None,
                population: None,
                hegemony: None,
                peeringdb: None,
                delegated: None,
                irr: Vec::new(),
            },
        );

        // A single source with data for AS13335 (as_name disagrees with the
        // base name on purpose: IRR must not replace the base fields).
        let mut per_source: std::collections::HashMap<
            String,
            std::collections::HashMap<u32, IrrAsnInfoBuilder>,
        > = std::collections::HashMap::new();
        let mut builder = IrrAsnInfoBuilder::default();
        builder.source = "RIPE".to_string();
        builder.as_name = "CLOUDFLARE-NET".to_string();
        per_source.insert("RIPE".to_string(), [(13335, builder)].into_iter().collect());

        let ripe = crate::irr::sources::all_sources()
            .into_iter()
            .find(|source| source.name == "RIPE")
            .unwrap();
        attach_irr_data(&mut map, per_source, &[ripe]);

        let info = &map[&13335];
        assert_eq!(info.name, "CLOUDFLARENET");
        assert_eq!(info.country, "US");
        assert_eq!(info.irr.len(), 1);
        assert_eq!(info.irr[0].as_name, "CLOUDFLARE-NET");
        assert_eq!(info.irr[0].source, "RIPE");
    }
}