dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
//! Assembly identity system for multi-assembly .NET analysis.
//!
//! This module provides comprehensive assembly identification and version management
//! for .NET assemblies according to ECMA-335 specifications. It serves as the
//! foundation for cross-assembly resolution and multi-assembly project management.
//!
//! # ECMA-335 References
//!
//! This module implements identity concepts defined in the ECMA-335 specification:
//! - **Section II.6.1**: Overview of assemblies - defines assembly identity components
//! - **Section II.6.2.1**: Assembly versioning - four-part version number semantics
//! - **Section II.6.2.1.3**: Public key and token - strong name identity format
//! - **Section II.6.2.3**: Processor architecture - platform-specific assembly targeting
//! - **Section II.22.2**: Assembly table - assembly metadata structure
//! - **Section II.22.5**: AssemblyRef table - assembly reference structure
//!
//! See: <https://ecma-international.org/publications-and-standards/standards/ecma-335/>
//!
//! # Key Components
//!
//! - [`AssemblyIdentity`] - Complete assembly identification with name, version, culture, and strong name
//! - [`AssemblyVersion`] - Four-part version numbering (major.minor.build.revision)  
//! - [`ProcessorArchitecture`] - Processor architecture specification
//!
//! # Identity Components
//!
//! .NET assemblies are uniquely identified by the combination of:
//! - **Simple Name**: The primary assembly name (e.g., "mscorlib", "System.Core")
//! - **Version**: Four-part version number for binding and compatibility
//! - **Culture**: Localization culture (None for culture-neutral assemblies)
//! - **Strong Name**: Cryptographic identity for verification and GAC storage
//! - **Architecture**: Target processor architecture for platform-specific assemblies
//!
//! # Assembly Versioning
//!
//! Assembly versions follow the .NET convention of four 16-bit components:
//! - **Major**: Significant API changes, breaking compatibility
//! - **Minor**: Feature additions, backward compatible
//! - **Build**: Bug fixes and minor updates
//! - **Revision**: Emergency patches and hotfixes
//!
//! # Examples
//!
//! ## Creating Assembly Identities
//!
//! ```rust,no_run
//! use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
//!
//! // Simple assembly without strong name
//! let simple = AssemblyIdentity::new(
//!     "MyLibrary",
//!     AssemblyVersion::new(1, 2, 3, 4),
//!     None,
//!     None,
//!     None,
//! );
//!
//! // Strong-named framework assembly
//! let mscorlib = AssemblyIdentity::parse(
//!     "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
//! )?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Parsing from Metadata
//!
//! ```rust,ignore
//! use dotscope::metadata::tables::AssemblyRef;
//! use dotscope::metadata::identity::AssemblyIdentity;
//!
//! // Parse from AssemblyRef table entry
//! let assembly_ref: AssemblyRef = // ... loaded from metadata
//! let identity = AssemblyIdentity::from_assembly_ref(&assembly_ref);
//!
//! // Parse from Assembly table entry
//! let assembly: Assembly = // ... loaded from metadata
//! let identity = AssemblyIdentity::from_assembly(&assembly);
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Version Parsing and Display
//!
//! ```rust,no_run
//! use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
//!
//! // Parse version string
//! let version = AssemblyVersion::parse("1.2.3.4")?;
//! assert_eq!(version.major, 1);
//! assert_eq!(version.minor, 2);
//!
//! // Display name generation
//! let identity = AssemblyIdentity::parse("System.Core, Version=3.5.0.0")?;
//! println!("Display name: {}", identity.display_name());
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Integration with CilProject
//!
//! This identity system serves as the foundation for:
//! - **Multi-assembly dependency tracking** in AssemblyDependencyGraph
//! - **Cross-assembly type resolution** in GlobalTypeResolver  
//! - **Assembly loading and management** in CilProject container
//! - **Version binding and compatibility** analysis
//!
//! # Thread Safety
//!
//! All types in this module are thread-safe and implement [`Send`] and [`Sync`].
//! Assembly identities can be safely shared across threads and used as keys in
//! concurrent collections like `DashMap` and `HashMap`.

use std::{fmt, fmt::Write as _, str::FromStr, sync::atomic::Ordering};

use crate::{
    metadata::{
        identity::cryptographic::Identity,
        tables::{Assembly, AssemblyHashAlgorithm, AssemblyRef},
    },
    Error, Result,
};

/// Complete identity information for a .NET assembly.
///
/// Provides comprehensive identification for .NET assemblies including name, version,
/// culture, strong name, and architecture information. This serves as the primary
/// identifier for assemblies in multi-assembly analysis and cross-assembly resolution.
///
/// # Identity Components
///
/// - **Name**: Simple assembly name used for basic identification
/// - **Version**: Four-part version for compatibility and binding decisions
/// - **Culture**: Localization culture (None for culture-neutral assemblies)
/// - **Strong Name**: Cryptographic identity for verification and security
/// - **Architecture**: Target processor architecture specification
///
/// # Equality Semantics
///
/// **Important**: The [`strong_name`](Self::strong_name) field is **excluded** from equality
/// comparison and hashing. This is an intentional design decision that enables:
///
/// - Assemblies with different strong name representations (Token vs PubKey vs EcmaKey)
///   to be considered equal for dependency resolution purposes
/// - Consistent [`HashMap`](std::collections::HashMap) behavior when the same assembly
///   is referenced with different key formats
/// - Matching dependencies by name+version+culture+architecture regardless of how
///   the strong name is stored in metadata
///
/// Two `AssemblyIdentity` instances are equal if and only if their `name`, `version`,
/// `culture`, and `processor_architecture` fields are equal. The `strong_name` field
/// is ignored in both `PartialEq` and `Hash` implementations.
///
/// If you need to compare strong names, access the `strong_name` field directly or use
/// a custom comparison function.
///
/// # Uniqueness
///
/// Two assemblies with identical identity components (excluding strong name) are
/// considered the same assembly. The combination of name, version, culture, and
/// architecture provides sufficient uniqueness for practical assembly identification
/// and resolution scenarios.
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
///
/// // Create identity for a simple library
/// let identity = AssemblyIdentity {
///     name: "MyLibrary".to_string(),
///     version: AssemblyVersion::new(1, 0, 0, 0),
///     culture: None,
///     strong_name: None,
///     processor_architecture: None,
/// };
///
/// // Use as key in collections
/// let mut assembly_map = std::collections::HashMap::new();
/// let assembly_data = "path/to/assembly.dll";
/// assembly_map.insert(identity, assembly_data);
/// ```
#[derive(Debug, Clone)]
pub struct AssemblyIdentity {
    /// Simple assembly name (e.g., "mscorlib", "System.Core").
    ///
    /// The primary identifier used for basic assembly lookup and display.
    /// This name appears in assembly references and is used for file system
    /// resolution when no culture or architecture specificity is required.
    pub name: String,

    /// Four-part version number for compatibility and binding.
    ///
    /// Used by the .NET runtime for version binding decisions, compatibility
    /// analysis, and side-by-side deployment scenarios. Version policies can
    /// specify exact, minimum, or range-based version requirements.
    pub version: AssemblyVersion,

    /// Culture information for localized assemblies.
    ///
    /// Specifies the localization culture for satellite assemblies containing
    /// culture-specific resources. `None` indicates a culture-neutral assembly
    /// that contains the default/fallback resources and executable code.
    ///
    /// # Examples
    /// - `None` - Culture-neutral assembly (default)
    /// - `Some("en-US")` - US English localized assembly
    /// - `Some("fr-FR")` - French (France) localized assembly
    pub culture: Option<String>,

    /// Cryptographic strong name identity.
    ///
    /// Provides cryptographic verification for assembly integrity and origin.
    /// Strong-named assemblies can be stored in the Global Assembly Cache (GAC)
    /// and provide security guarantees about assembly authenticity.
    ///
    /// Uses the existing cryptographic [`Identity`] system for public key
    /// or token-based identification.
    pub strong_name: Option<Identity>,

    /// Target processor architecture specification.
    ///
    /// Indicates the processor architecture for which the assembly was compiled.
    /// Used for platform-specific assemblies and deployment scenarios requiring
    /// architecture-specific code or optimizations.
    pub processor_architecture: Option<ProcessorArchitecture>,
}

impl PartialEq for AssemblyIdentity {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.version == other.version
            && self.culture == other.culture
            && self.processor_architecture == other.processor_architecture
        // Note: strong_name is excluded from equality comparison
        // This allows assemblies with different strong name representations
        // (PubKey vs Token) to be considered equal for dependency resolution
    }
}

impl Eq for AssemblyIdentity {}

impl std::hash::Hash for AssemblyIdentity {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.version.hash(state);
        self.culture.hash(state);
        self.processor_architecture.hash(state);
        // Note: strong_name is excluded from hash calculation
        // This ensures assemblies with different strong name representations
        // hash to the same value for consistent HashMap behavior
    }
}

/// Four-part version numbering for .NET assemblies.
///
/// Implements the standard .NET assembly versioning scheme with four 16-bit components.
/// This versioning system supports semantic versioning concepts while maintaining
/// compatibility with .NET runtime version binding and resolution mechanisms.
///
/// # Version Components
///
/// - **Major**: Significant API changes, potentially breaking compatibility
/// - **Minor**: Feature additions, maintaining backward compatibility  
/// - **Build**: Bug fixes, patches, and minor improvements
/// - **Revision**: Emergency fixes and hotfixes
///
/// # Version Comparison
///
/// Versions are compared component-wise in order: major, minor, build, revision.
/// This ordering enables proper version precedence and compatibility analysis
/// for assembly binding and dependency resolution.
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::metadata::identity::AssemblyVersion;
///
/// // Create version programmatically
/// let version = AssemblyVersion::new(1, 2, 3, 4);
/// assert_eq!(version.to_string(), "1.2.3.4");
///
/// // Parse from string representation
/// let parsed = AssemblyVersion::parse("2.0.0.0")?;
/// assert!(parsed > version);
/// # Ok::<(), dotscope::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AssemblyVersion {
    /// Major version component.
    ///
    /// Indicates significant changes that may break compatibility with previous versions.
    /// Typically incremented for major feature releases or API redesigns.
    pub major: u16,

    /// Minor version component.
    ///
    /// Indicates feature additions that maintain backward compatibility.
    /// New functionality is added without breaking existing public APIs.
    pub minor: u16,

    /// Build version component.
    ///
    /// Indicates bug fixes, performance improvements, and minor feature updates.
    /// Changes at this level should not affect public API compatibility.
    pub build: u16,

    /// Revision version component.
    ///
    /// Indicates emergency fixes, security patches, and critical hotfixes.
    /// Typically used for minimal changes addressing urgent issues.
    pub revision: u16,
}

/// Processor architecture specification for .NET assemblies.
///
/// Indicates the target processor architecture for platform-specific assemblies.
/// This information guides deployment decisions and runtime loading behavior
/// for architecture-sensitive code and optimizations.
///
/// # Architecture Types
///
/// - **MSIL**: Managed code, architecture-neutral (most common)
/// - **X86**: 32-bit Intel x86 architecture
/// - **IA64**: Intel Itanium 64-bit architecture  
/// - **AMD64**: 64-bit x86-64 architecture (Intel/AMD)
/// - **ARM**: ARM processor architecture
/// - **ARM64**: 64-bit ARM architecture
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProcessorArchitecture {
    /// Microsoft Intermediate Language - architecture neutral.
    ///
    /// Managed code that can run on any processor architecture supported
    /// by the .NET runtime. This is the most common architecture type
    /// for typical .NET assemblies.
    MSIL,

    /// 32-bit Intel x86 architecture.
    ///
    /// Platform-specific assemblies compiled for 32-bit Intel x86 processors.
    /// May contain P/Invoke calls or unsafe code specific to this architecture.
    X86,

    /// Intel Itanium 64-bit architecture.
    ///
    /// Platform-specific assemblies for Intel Itanium processors.
    /// Largely deprecated but may appear in legacy enterprise environments.
    IA64,

    /// 64-bit x86-64 architecture (Intel/AMD).
    ///
    /// Platform-specific assemblies for modern 64-bit Intel and AMD processors.
    /// Common for performance-critical code requiring 64-bit optimizations.
    ///
    /// # Parsing Alias
    ///
    /// Both "AMD64" and "x64" are accepted when parsing, but the canonical display
    /// name is "AMD64". This means `ProcessorArchitecture::parse("x64")` returns
    /// `AMD64`, which displays as "AMD64", not "x64".
    AMD64,

    /// ARM processor architecture.
    ///
    /// Platform-specific assemblies for ARM processors, common in mobile
    /// and embedded scenarios where .NET Core/5+ provides ARM support.
    ARM,

    /// 64-bit ARM architecture.
    ///
    /// Platform-specific assemblies for 64-bit ARM processors, increasingly
    /// common with ARM-based servers and Apple Silicon support.
    ARM64,
}

impl AssemblyIdentity {
    /// Create a new assembly identity with the specified components.
    ///
    /// This constructor provides a convenient way to create assembly identities
    /// programmatically with all required and optional components.
    ///
    /// # Arguments
    ///
    /// * `name` - Simple assembly name for identification
    /// * `version` - Four-part version number
    /// * `culture` - Optional culture for localized assemblies
    /// * `strong_name` - Optional cryptographic identity
    /// * `processor_architecture` - Optional architecture specification
    ///
    /// # Returns
    ///
    /// A new `AssemblyIdentity` with the specified components.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    ///
    /// let identity = AssemblyIdentity::new(
    ///     "MyLibrary",
    ///     AssemblyVersion::new(1, 0, 0, 0),
    ///     None,
    ///     None,
    ///     None,
    /// );
    /// ```
    pub fn new(
        name: impl Into<String>,
        version: AssemblyVersion,
        culture: Option<String>,
        strong_name: Option<Identity>,
        processor_architecture: Option<ProcessorArchitecture>,
    ) -> Self {
        Self {
            name: name.into(),
            version,
            culture,
            strong_name,
            processor_architecture,
        }
    }

    /// Create assembly identity from an AssemblyRef table entry.
    ///
    /// Extracts complete assembly identity information from a metadata
    /// AssemblyRef entry, including version, culture, and strong name data.
    /// This is the primary method for creating identities during metadata loading.
    ///
    /// # Arguments
    ///
    /// * `assembly_ref` - AssemblyRef table entry from metadata
    ///
    /// # Returns
    ///
    /// Complete `AssemblyIdentity` derived from the AssemblyRef data.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use dotscope::metadata::identity::AssemblyIdentity;
    ///
    /// let assembly_ref = // ... loaded from metadata
    /// let identity = AssemblyIdentity::from_assembly_ref(&assembly_ref);
    /// ```
    pub fn from_assembly_ref(assembly_ref: &AssemblyRef) -> Self {
        // Extract processor architecture from the AssemblyRefProcessor table data if present.
        // A value of 0 typically means MSIL/AnyCPU (architecture-neutral), but we only
        // set the architecture if a non-zero processor value is present to distinguish
        // between "no processor info" and "explicitly MSIL".
        let processor_value = assembly_ref.processor.load(Ordering::Relaxed);
        let processor_architecture = if processor_value != 0 {
            ProcessorArchitecture::try_from(processor_value).ok()
        } else {
            None
        };

        Self {
            name: assembly_ref.name.clone(),
            version: Self::version_from_u32(
                assembly_ref.major_version,
                assembly_ref.minor_version,
                assembly_ref.build_number,
                assembly_ref.revision_number,
            ),
            culture: assembly_ref.culture.clone(),
            strong_name: assembly_ref.identifier.clone(),
            processor_architecture,
        }
    }

    /// Create assembly identity from an Assembly table entry.
    ///
    /// Extracts complete assembly identity information from a metadata
    /// Assembly entry for the current assembly being analyzed.
    ///
    /// # Arguments
    ///
    /// * `assembly` - Assembly table entry from metadata
    ///
    /// # Returns
    ///
    /// Complete `AssemblyIdentity` derived from the Assembly data.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use dotscope::metadata::identity::AssemblyIdentity;
    ///
    /// let assembly = // ... loaded from metadata
    /// let identity = AssemblyIdentity::from_assembly(&assembly);
    /// ```
    pub fn from_assembly(assembly: &Assembly) -> Self {
        // Note: Processor architecture for the Assembly table is stored in the separate
        // AssemblyProcessor table (0x21), not in the Assembly flags. This table is rarely
        // used in modern .NET assemblies which typically use AnyCPU compilation.
        // The AssemblyProcessor table would need to be correlated separately if needed.
        Self {
            name: assembly.name.clone(),
            version: Self::version_from_u32(
                assembly.major_version,
                assembly.minor_version,
                assembly.build_number,
                assembly.revision_number,
            ),
            culture: assembly.culture.clone(),
            strong_name: assembly
                .public_key
                .as_ref()
                .and_then(|key| Identity::from(key, true).ok()),
            processor_architecture: None,
        }
    }

    /// Create an `AssemblyVersion` from u32 components with saturating conversion.
    ///
    /// Per ECMA-335, assembly version components should fit within u16 range (0-65535).
    /// However, the metadata stores them as u32 for alignment. This method uses
    /// saturating conversion (`u16::try_from` with `unwrap_or(u16::MAX)`) to handle
    /// potentially malformed metadata gracefully without panicking.
    #[inline]
    fn version_from_u32(major: u32, minor: u32, build: u32, revision: u32) -> AssemblyVersion {
        AssemblyVersion::new(
            u16::try_from(major).unwrap_or(u16::MAX),
            u16::try_from(minor).unwrap_or(u16::MAX),
            u16::try_from(build).unwrap_or(u16::MAX),
            u16::try_from(revision).unwrap_or(u16::MAX),
        )
    }

    /// Parse assembly identity from display name string.
    ///
    /// Parses .NET assembly display names in the standard format used by
    /// the .NET runtime and development tools. Supports both simple names
    /// and fully-qualified names with version, culture, and public key token.
    ///
    /// # Arguments
    ///
    /// * `display_name` - Assembly display name string to parse
    ///
    /// # Returns
    ///
    /// * `Ok(AssemblyIdentity)` - Successfully parsed identity
    /// * `Err(Error)` - Parsing failed due to invalid format
    ///
    /// # Format
    ///
    /// ```text
    /// AssemblyName[, Version=Major.Minor.Build.Revision][, Culture=culture][, PublicKeyToken=token]
    /// ```
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::identity::AssemblyIdentity;
    ///
    /// // Simple name only
    /// let simple = AssemblyIdentity::parse("MyLibrary")?;
    ///
    /// // Full specification
    /// let full = AssemblyIdentity::parse(
    ///     "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    /// )?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns an error if the display name cannot be parsed.
    pub fn parse(display_name: &str) -> Result<Self> {
        let mut version = AssemblyVersion::new(0, 0, 0, 0);
        let mut culture = None;
        let mut strong_name = None;
        let mut processor_architecture = None;

        let parts: Vec<&str> = display_name.split(',').map(str::trim).collect();

        if parts.is_empty() {
            return Err(malformed_error!("Empty assembly display name"));
        }

        let name = parts[0].to_string();
        if name.is_empty() {
            return Err(malformed_error!("Assembly name cannot be empty"));
        }

        // Process optional components
        for part in parts.iter().skip(1) {
            if let Some(value) = part.strip_prefix("Version=") {
                version = AssemblyVersion::parse(value)?;
            } else if let Some(value) = part.strip_prefix("Culture=") {
                if value != "neutral" {
                    culture = Some(value.to_string());
                }
            } else if let Some(value) = part.strip_prefix("PublicKeyToken=") {
                if value != "null" && !value.is_empty() {
                    let token_bytes = hex::decode(value).map_err(|e| {
                        malformed_error!("Invalid hex in PublicKeyToken '{}': {}", value, e)
                    })?;

                    if token_bytes.len() != 8 {
                        return Err(malformed_error!(
                            "PublicKeyToken must be exactly 8 bytes (16 hex characters), got {} bytes from '{}'",
                            token_bytes.len(),
                            value
                        ));
                    }

                    // Convert 8 bytes to u64 token
                    let mut token_array = [0u8; 8];
                    token_array.copy_from_slice(&token_bytes);
                    let token = u64::from_le_bytes(token_array);
                    strong_name = Some(Identity::Token(token));
                }
            } else if let Some(value) = part.strip_prefix("ProcessorArchitecture=") {
                processor_architecture = Some(ProcessorArchitecture::parse(value)?);
            }
        }

        Ok(Self {
            name,
            version,
            culture,
            strong_name,
            processor_architecture,
        })
    }

    /// Generate display name string for this assembly identity.
    ///
    /// Creates a .NET-compatible assembly display name that includes all
    /// available identity components. This format is compatible with .NET
    /// runtime assembly loading and resolution mechanisms.
    ///
    /// # Returns
    ///
    /// A formatted display name string suitable for assembly loading.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    ///
    /// let identity = AssemblyIdentity::new(
    ///     "MyLibrary",
    ///     AssemblyVersion::new(1, 2, 3, 4),
    ///     Some("en-US".to_string()),
    ///     None,
    ///     None,
    /// );
    ///
    /// let display_name = identity.display_name();
    /// // Result: "MyLibrary, Version=1.2.3.4, Culture=en-US, PublicKeyToken=null"
    /// ```
    #[must_use]
    pub fn display_name(&self) -> String {
        // Pre-allocate with estimated capacity to minimize reallocations
        // Typical format: "Name, Version=x.x.x.x, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx"
        let mut result = String::with_capacity(self.name.len() + 80);

        result.push_str(&self.name);

        let _ = write!(result, ", Version={}", self.version);

        let culture_str = self.culture.as_deref().unwrap_or("neutral");
        let _ = write!(result, ", Culture={culture_str}");

        // For PubKey and EcmaKey variants, compute the token using SHA1 (the .NET standard)
        // Note: Tokens are stored as u64 little-endian internally, but displayed as hex bytes
        // in their natural order (first byte of the u64 comes first in the hex string).
        // This matches the .NET display name format where "b77a5c561934e089" represents
        // the bytes [0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89].
        result.push_str(", PublicKeyToken=");
        match &self.strong_name {
            Some(Identity::Token(token)) => {
                let bytes = token.to_le_bytes();
                let _ = write!(
                    result,
                    "{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
                    bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]
                );
            }
            Some(identity @ (Identity::PubKey(_) | Identity::EcmaKey(_))) => {
                match identity.to_token(AssemblyHashAlgorithm::SHA1) {
                    Ok(token) => {
                        let bytes = token.to_le_bytes();
                        let _ = write!(
                            result,
                            "{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
                            bytes[0],
                            bytes[1],
                            bytes[2],
                            bytes[3],
                            bytes[4],
                            bytes[5],
                            bytes[6],
                            bytes[7]
                        );
                    }
                    Err(_) => result.push_str("null"),
                }
            }
            None => result.push_str("null"),
        }

        // Add processor architecture if specified
        if let Some(arch) = &self.processor_architecture {
            let _ = write!(result, ", ProcessorArchitecture={arch}");
        }

        result
    }

    /// Get the simple assembly name without version or culture information.
    ///
    /// Returns just the primary assembly name component for cases where
    /// version and culture information is not needed.
    ///
    /// # Returns
    ///
    /// The simple assembly name string.
    #[must_use]
    pub fn simple_name(&self) -> &str {
        &self.name
    }

    /// Check if this assembly is strong-named.
    ///
    /// Strong-named assemblies have cryptographic identity that can be verified
    /// and are eligible for Global Assembly Cache (GAC) storage.
    ///
    /// # Returns
    ///
    /// `true` if the assembly has a strong name, `false` otherwise.
    #[must_use]
    pub fn is_strong_named(&self) -> bool {
        self.strong_name.is_some()
    }

    /// Check if this assembly is culture-neutral.
    ///
    /// Culture-neutral assemblies contain the default resources and executable
    /// code, while culture-specific assemblies contain localized resources.
    ///
    /// # Returns
    ///
    /// `true` if the assembly is culture-neutral, `false` if culture-specific.
    #[must_use]
    pub fn is_culture_neutral(&self) -> bool {
        self.culture.is_none()
    }

    /// Check if this assembly identity satisfies a dependency requirement.
    ///
    /// This method determines whether this assembly can be used to satisfy a
    /// reference to another assembly. It checks name, culture, and version
    /// compatibility according to .NET binding rules.
    ///
    /// # Matching Rules
    ///
    /// 1. **Name**: Must match case-insensitively
    /// 2. **Culture**: Must match exactly (None matches None, "en-US" matches "en-US")
    /// 3. **Version**: Must be compatible per [`AssemblyVersion::is_compatible_with`]
    ///
    /// # Arguments
    ///
    /// * `required` - The assembly identity required by a dependency
    ///
    /// # Returns
    ///
    /// `true` if this assembly can satisfy the requirement, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    ///
    /// let available = AssemblyIdentity::new(
    ///     "System.Core",
    ///     AssemblyVersion::new(4, 5, 0, 0),
    ///     None,
    ///     None,
    ///     None,
    /// );
    ///
    /// let required = AssemblyIdentity::new(
    ///     "System.Core",
    ///     AssemblyVersion::new(4, 0, 0, 0),
    ///     None,
    ///     None,
    ///     None,
    /// );
    ///
    /// // v4.5 satisfies requirement for v4.0
    /// assert!(available.satisfies(&required));
    ///
    /// // But v4.0 does NOT satisfy requirement for v4.5
    /// assert!(!required.satisfies(&available));
    /// ```
    #[must_use]
    pub fn satisfies(&self, required: &AssemblyIdentity) -> bool {
        // Name must match (case-insensitive)
        if !self.name.eq_ignore_ascii_case(&required.name) {
            return false;
        }

        // Culture must match exactly
        if self.culture != required.culture {
            return false;
        }

        // Version must be compatible
        self.version.is_compatible_with(&required.version)
    }
}

impl AssemblyVersion {
    /// Sentinel value representing an unknown or unspecified version.
    ///
    /// This constant (0.0.0.0) is used when version information is not available, such as when
    /// creating assembly identities from `ModuleRef` or `File` table entries where
    /// version information is not stored in the metadata.
    ///
    /// Use [`is_unknown()`](Self::is_unknown) to check if a version represents this sentinel.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::identity::AssemblyVersion;
    ///
    /// let unknown = AssemblyVersion::UNKNOWN;
    /// assert!(unknown.is_unknown());
    ///
    /// let known = AssemblyVersion::new(1, 0, 0, 0);
    /// assert!(!known.is_unknown());
    /// ```
    pub const UNKNOWN: Self = Self {
        major: 0,
        minor: 0,
        build: 0,
        revision: 0,
    };

    /// Create a new assembly version with the specified components.
    ///
    /// # Arguments
    ///
    /// * `major` - Major version component
    /// * `minor` - Minor version component
    /// * `build` - Build version component
    /// * `revision` - Revision version component
    ///
    /// # Returns
    ///
    /// A new `AssemblyVersion` with the specified components.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::identity::AssemblyVersion;
    ///
    /// let version = AssemblyVersion::new(1, 2, 3, 4);
    /// assert_eq!(version.major, 1);
    /// assert_eq!(version.minor, 2);
    /// ```
    #[must_use]
    pub const fn new(major: u16, minor: u16, build: u16, revision: u16) -> Self {
        Self {
            major,
            minor,
            build,
            revision,
        }
    }

    /// Check if this version represents an unknown/unspecified version.
    ///
    /// Returns `true` if this version equals [`UNKNOWN`](Self::UNKNOWN) (0.0.0.0).
    /// This is useful for detecting dependencies where version information could not
    /// be determined from the metadata, such as `ModuleRef` or `File` entries.
    ///
    /// # Note
    ///
    /// While version 0.0.0.0 is technically a valid .NET version, it is extremely
    /// rare in practice. This method treats it as a sentinel for "version unknown".
    /// If you need to distinguish between "truly version 0.0.0.0" and "unknown",
    /// consider using additional context from the dependency source.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::identity::AssemblyVersion;
    ///
    /// assert!(AssemblyVersion::UNKNOWN.is_unknown());
    /// assert!(AssemblyVersion::new(0, 0, 0, 0).is_unknown());
    /// assert!(!AssemblyVersion::new(1, 0, 0, 0).is_unknown());
    /// ```
    #[must_use]
    pub const fn is_unknown(&self) -> bool {
        self.major == 0 && self.minor == 0 && self.build == 0 && self.revision == 0
    }

    /// Check if this version is compatible with a required version.
    ///
    /// .NET uses version unification where a higher version can satisfy a lower
    /// requirement if they share the same major version. This follows the standard
    /// .NET binding policy for strong-named assemblies.
    ///
    /// # Compatibility Rules
    ///
    /// - If the required version is unknown (0.0.0.0), any version is compatible
    /// - Otherwise, the major versions must match and this version must be >= required
    ///
    /// # Arguments
    ///
    /// * `required` - The version that is required by a dependency
    ///
    /// # Returns
    ///
    /// `true` if this version can satisfy the requirement, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::identity::AssemblyVersion;
    ///
    /// let v4_0 = AssemblyVersion::new(4, 0, 0, 0);
    /// let v4_5 = AssemblyVersion::new(4, 5, 0, 0);
    /// let v5_0 = AssemblyVersion::new(5, 0, 0, 0);
    ///
    /// // v4.5 is compatible with requirement for v4.0 (same major, higher version)
    /// assert!(v4_5.is_compatible_with(&v4_0));
    ///
    /// // v4.0 is NOT compatible with requirement for v4.5 (same major, but lower)
    /// assert!(!v4_0.is_compatible_with(&v4_5));
    ///
    /// // v5.0 is NOT compatible with requirement for v4.0 (different major)
    /// assert!(!v5_0.is_compatible_with(&v4_0));
    ///
    /// // Any version is compatible with unknown (0.0.0.0)
    /// assert!(v4_0.is_compatible_with(&AssemblyVersion::UNKNOWN));
    /// ```
    #[must_use]
    pub fn is_compatible_with(&self, required: &AssemblyVersion) -> bool {
        // Unknown version requirement accepts any version
        if required.is_unknown() {
            return true;
        }

        // Major version must match, and this version must be >= required
        self.major == required.major && *self >= *required
    }

    /// Check if this version is closer to a target than another version.
    ///
    /// Used for selecting the best fallback when no compatible version exists.
    /// The comparison prioritizes:
    ///
    /// 1. Same major version as target (strongly preferred)
    /// 2. For same major: higher version is better (closer to being compatible)
    /// 3. For different major: closer major number is better
    ///
    /// # Arguments
    ///
    /// * `other` - The version to compare against
    /// * `target` - The target version we're trying to match
    ///
    /// # Returns
    ///
    /// `true` if `self` is a better match for `target` than `other`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::identity::AssemblyVersion;
    ///
    /// let target = AssemblyVersion::new(4, 5, 0, 0);
    /// let v4_0 = AssemblyVersion::new(4, 0, 0, 0);
    /// let v3_0 = AssemblyVersion::new(3, 0, 0, 0);
    /// let v5_0 = AssemblyVersion::new(5, 0, 0, 0);
    ///
    /// // Same major is preferred over different major
    /// assert!(v4_0.is_closer_to(&v3_0, &target));
    /// assert!(v4_0.is_closer_to(&v5_0, &target));
    ///
    /// // For same major, higher version is better
    /// let v4_2 = AssemblyVersion::new(4, 2, 0, 0);
    /// assert!(v4_2.is_closer_to(&v4_0, &target));
    ///
    /// // For different majors, closer major number wins
    /// let v2_0 = AssemblyVersion::new(2, 0, 0, 0);
    /// assert!(v3_0.is_closer_to(&v2_0, &target)); // v3 is closer to v4 than v2
    /// ```
    #[must_use]
    pub fn is_closer_to(&self, other: &AssemblyVersion, target: &AssemblyVersion) -> bool {
        let self_same_major = self.major == target.major;
        let other_same_major = other.major == target.major;

        match (self_same_major, other_same_major) {
            (true, false) => true,
            (false, true) => false,
            (true, true) => {
                // Both have same major as target - prefer higher (closer to compatible)
                self > other
            }
            (false, false) => {
                // Both have different major - prefer closer major number
                let self_dist = self.major.abs_diff(target.major);
                let other_dist = other.major.abs_diff(target.major);
                self_dist < other_dist
            }
        }
    }

    /// Parse assembly version from string representation.
    ///
    /// Supports various version string formats:
    /// - "1.2.3.4" - Full four-part version
    /// - "1.2.3" - Three-part version (revision defaults to 0)
    /// - "1.2" - Two-part version (build and revision default to 0)
    /// - "1" - Single component (others default to 0)
    ///
    /// # Arguments
    ///
    /// * `version_str` - Version string to parse
    ///
    /// # Returns
    ///
    /// * `Ok(AssemblyVersion)` - Successfully parsed version
    /// * `Err(Error)` - Parsing failed due to invalid format
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::identity::AssemblyVersion;
    ///
    /// let full = AssemblyVersion::parse("1.2.3.4")?;
    /// let partial = AssemblyVersion::parse("2.0")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns an error if the version string has an invalid format.
    pub fn parse(version_str: &str) -> Result<Self> {
        let parts: Vec<&str> = version_str.split('.').collect();

        if parts.is_empty() || parts.len() > 4 {
            return Err(malformed_error!("Invalid version format: {}", version_str));
        }

        let mut components = [0u16; 4];

        for (i, part) in parts.iter().enumerate() {
            components[i] = part
                .parse::<u16>()
                .map_err(|_| malformed_error!("Invalid version component: {}", part))?;
        }

        Ok(Self::new(
            components[0],
            components[1],
            components[2],
            components[3],
        ))
    }
}

impl ProcessorArchitecture {
    /// Parse processor architecture from string representation.
    ///
    /// Supports standard .NET processor architecture names:
    /// - "MSIL" or "msil" - Microsoft Intermediate Language
    /// - "x86" or "X86" - 32-bit Intel x86
    /// - "IA64" or "ia64" - Intel Itanium 64-bit
    /// - "AMD64" or "amd64" or "x64" - 64-bit x86-64 (note: "x64" is an alias, displays as "AMD64")
    /// - "ARM" or "arm" - ARM architecture
    /// - "ARM64" or "arm64" - 64-bit ARM architecture
    ///
    /// # Arguments
    ///
    /// * `arch_str` - Architecture string to parse
    ///
    /// # Returns
    ///
    /// * `Ok(ProcessorArchitecture)` - Successfully parsed architecture
    /// * `Err(Error)` - Parsing failed due to unrecognized architecture
    ///
    /// # Errors
    /// Returns an error if the architecture string is not recognized.
    pub fn parse(arch_str: &str) -> Result<Self> {
        match arch_str.trim().to_lowercase().as_str() {
            "msil" => Ok(Self::MSIL),
            "x86" => Ok(Self::X86),
            "ia64" => Ok(Self::IA64),
            "amd64" | "x64" => Ok(Self::AMD64),
            "arm" => Ok(Self::ARM),
            "arm64" => Ok(Self::ARM64),
            _ => Err(malformed_error!(
                "Unknown processor architecture: '{}'",
                arch_str.trim()
            )),
        }
    }
}

// Display implementations
impl fmt::Display for AssemblyVersion {
    /// Format assembly version as standard dotted notation.
    ///
    /// Produces version strings in the format "major.minor.build.revision"
    /// compatible with .NET version string conventions.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}.{}.{}.{}",
            self.major, self.minor, self.build, self.revision
        )
    }
}

impl fmt::Display for ProcessorArchitecture {
    /// Format processor architecture as string.
    ///
    /// Uses standard .NET processor architecture names for consistency
    /// with runtime and development tool conventions.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let arch_str = match self {
            Self::MSIL => "MSIL",
            Self::X86 => "x86",
            Self::IA64 => "IA64",
            Self::AMD64 => "AMD64",
            Self::ARM => "ARM",
            Self::ARM64 => "ARM64",
        };
        write!(f, "{arch_str}")
    }
}

impl fmt::Display for AssemblyIdentity {
    /// Format assembly identity as display name.
    ///
    /// Delegates to the `display_name()` method for consistent formatting.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.display_name())
    }
}

// String parsing support
impl FromStr for AssemblyVersion {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        Self::parse(s)
    }
}

impl FromStr for AssemblyIdentity {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        Self::parse(s)
    }
}

impl FromStr for ProcessorArchitecture {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        Self::parse(s)
    }
}

impl TryFrom<u32> for ProcessorArchitecture {
    type Error = Error;

    /// Convert a processor ID from the AssemblyProcessor table to ProcessorArchitecture.
    ///
    /// The AssemblyProcessor table uses processor ID values that align with PE/COFF
    /// machine types. This implementation maps those values to the .NET ProcessorArchitecture enum.
    ///
    /// # Arguments
    ///
    /// * `value` - The processor value from the AssemblyProcessor table
    ///
    /// # Returns
    ///
    /// * `Ok(ProcessorArchitecture)` - Successfully mapped processor architecture
    /// * `Err(Error)` - Unknown or unsupported processor ID
    ///
    /// # Processor ID Mapping
    ///
    /// Based on PE/COFF specification (IMAGE_FILE_MACHINE_* constants):
    /// - `0x0000` - IMAGE_FILE_MACHINE_UNKNOWN (treated as MSIL/AnyCPU)
    /// - `0x014C` - IMAGE_FILE_MACHINE_I386 (x86)
    /// - `0x0200` - IMAGE_FILE_MACHINE_IA64 (Intel Itanium)
    /// - `0x8664` - IMAGE_FILE_MACHINE_AMD64 (x86-64)
    /// - `0x01C0` - IMAGE_FILE_MACHINE_ARM (32-bit ARM)
    /// - `0xAA64` - IMAGE_FILE_MACHINE_ARM64 (64-bit ARM)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::identity::ProcessorArchitecture;
    ///
    /// // x86 processor
    /// let arch = ProcessorArchitecture::try_from(0x014C)?;
    /// assert_eq!(arch, ProcessorArchitecture::X86);
    ///
    /// // AMD64/x64 processor
    /// let arch = ProcessorArchitecture::try_from(0x8664)?;
    /// assert_eq!(arch, ProcessorArchitecture::AMD64);
    ///
    /// // Unknown processor type
    /// assert!(ProcessorArchitecture::try_from(0xFFFF).is_err());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    fn try_from(value: u32) -> Result<Self> {
        match value {
            0x0000 => Ok(Self::MSIL),
            0x014C => Ok(Self::X86),
            0x0200 => Ok(Self::IA64),
            0x8664 => Ok(Self::AMD64),
            0x01C0 => Ok(Self::ARM),
            0xAA64 => Ok(Self::ARM64),
            _ => Err(malformed_error!(
                "Unknown processor architecture ID: 0x{:04X}",
                value
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;

    #[test]
    fn test_assembly_version_new() {
        let version = AssemblyVersion::new(1, 2, 3, 4);
        assert_eq!(version.major, 1);
        assert_eq!(version.minor, 2);
        assert_eq!(version.build, 3);
        assert_eq!(version.revision, 4);
    }

    #[test]
    fn test_assembly_version_parse_full() {
        let version = AssemblyVersion::parse("4.0.0.0").unwrap();
        assert_eq!(version.major, 4);
        assert_eq!(version.minor, 0);
        assert_eq!(version.build, 0);
        assert_eq!(version.revision, 0);
    }

    #[test]
    fn test_assembly_version_parse_partial() {
        // Three parts
        let v3 = AssemblyVersion::parse("1.2.3").unwrap();
        assert_eq!(v3, AssemblyVersion::new(1, 2, 3, 0));

        // Two parts
        let v2 = AssemblyVersion::parse("1.2").unwrap();
        assert_eq!(v2, AssemblyVersion::new(1, 2, 0, 0));

        // Single part
        let v1 = AssemblyVersion::parse("1").unwrap();
        assert_eq!(v1, AssemblyVersion::new(1, 0, 0, 0));
    }

    #[test]
    fn test_assembly_version_parse_invalid() {
        // Empty string
        assert!(AssemblyVersion::parse("").is_err());

        // Too many parts
        assert!(AssemblyVersion::parse("1.2.3.4.5").is_err());

        // Invalid component
        assert!(AssemblyVersion::parse("1.2.abc.4").is_err());

        // Overflow
        assert!(AssemblyVersion::parse("1.2.99999.4").is_err());
    }

    #[test]
    fn test_assembly_version_display() {
        let version = AssemblyVersion::new(4, 0, 0, 0);
        assert_eq!(version.to_string(), "4.0.0.0");

        let version = AssemblyVersion::new(1, 2, 3, 4);
        assert_eq!(version.to_string(), "1.2.3.4");
    }

    #[test]
    fn test_assembly_version_ordering() {
        let v1 = AssemblyVersion::new(1, 0, 0, 0);
        let v2 = AssemblyVersion::new(2, 0, 0, 0);
        let v1_1 = AssemblyVersion::new(1, 1, 0, 0);

        assert!(v1 < v2);
        assert!(v1 < v1_1);
        assert!(v1_1 < v2);
    }

    #[test]
    fn test_assembly_version_from_str() {
        let version: AssemblyVersion = "4.0.0.0".parse().unwrap();
        assert_eq!(version, AssemblyVersion::new(4, 0, 0, 0));
    }

    #[test]
    fn test_processor_architecture_parse() {
        assert_eq!(
            ProcessorArchitecture::parse("MSIL").unwrap(),
            ProcessorArchitecture::MSIL
        );
        assert_eq!(
            ProcessorArchitecture::parse("msil").unwrap(),
            ProcessorArchitecture::MSIL
        );
        assert_eq!(
            ProcessorArchitecture::parse("x86").unwrap(),
            ProcessorArchitecture::X86
        );
        assert_eq!(
            ProcessorArchitecture::parse("X86").unwrap(),
            ProcessorArchitecture::X86
        );
        assert_eq!(
            ProcessorArchitecture::parse("AMD64").unwrap(),
            ProcessorArchitecture::AMD64
        );
        assert_eq!(
            ProcessorArchitecture::parse("amd64").unwrap(),
            ProcessorArchitecture::AMD64
        );
        assert_eq!(
            ProcessorArchitecture::parse("x64").unwrap(),
            ProcessorArchitecture::AMD64
        );
        assert_eq!(
            ProcessorArchitecture::parse("IA64").unwrap(),
            ProcessorArchitecture::IA64
        );
        assert_eq!(
            ProcessorArchitecture::parse("ARM").unwrap(),
            ProcessorArchitecture::ARM
        );
        assert_eq!(
            ProcessorArchitecture::parse("arm").unwrap(),
            ProcessorArchitecture::ARM
        );
        assert_eq!(
            ProcessorArchitecture::parse("ARM64").unwrap(),
            ProcessorArchitecture::ARM64
        );
        assert_eq!(
            ProcessorArchitecture::parse("arm64").unwrap(),
            ProcessorArchitecture::ARM64
        );
    }

    #[test]
    fn test_processor_architecture_parse_invalid() {
        assert!(ProcessorArchitecture::parse("unknown").is_err());
        assert!(ProcessorArchitecture::parse("").is_err());
        assert!(ProcessorArchitecture::parse("PowerPC").is_err());
    }

    #[test]
    fn test_processor_architecture_parse_whitespace() {
        // Whitespace should be trimmed
        assert_eq!(
            ProcessorArchitecture::parse(" x86 ").unwrap(),
            ProcessorArchitecture::X86
        );
        assert_eq!(
            ProcessorArchitecture::parse("\tAMD64\n").unwrap(),
            ProcessorArchitecture::AMD64
        );
        // Whitespace-only should fail
        assert!(ProcessorArchitecture::parse("   ").is_err());
    }

    #[test]
    fn test_processor_architecture_display() {
        assert_eq!(ProcessorArchitecture::MSIL.to_string(), "MSIL");
        assert_eq!(ProcessorArchitecture::X86.to_string(), "x86");
        assert_eq!(ProcessorArchitecture::AMD64.to_string(), "AMD64");
        assert_eq!(ProcessorArchitecture::IA64.to_string(), "IA64");
        assert_eq!(ProcessorArchitecture::ARM.to_string(), "ARM");
        assert_eq!(ProcessorArchitecture::ARM64.to_string(), "ARM64");
    }

    #[test]
    fn test_processor_architecture_from_str() {
        let arch: ProcessorArchitecture = "x86".parse().unwrap();
        assert_eq!(arch, ProcessorArchitecture::X86);
    }

    #[test]
    fn test_assembly_identity_new() {
        let identity = AssemblyIdentity::new(
            "TestAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None,
            None,
        );

        assert_eq!(identity.name, "TestAssembly");
        assert_eq!(identity.version, AssemblyVersion::new(1, 0, 0, 0));
        assert!(identity.culture.is_none());
        assert!(identity.strong_name.is_none());
        assert!(identity.processor_architecture.is_none());
    }

    #[test]
    fn test_assembly_identity_parse_simple_name() {
        let identity = AssemblyIdentity::parse("MyLibrary").unwrap();
        assert_eq!(identity.name, "MyLibrary");
        assert_eq!(identity.version, AssemblyVersion::new(0, 0, 0, 0));
        assert!(identity.culture.is_none());
        assert!(identity.strong_name.is_none());
    }

    #[test]
    fn test_assembly_identity_parse_with_version() {
        let identity = AssemblyIdentity::parse("MyLibrary, Version=1.2.3.4").unwrap();
        assert_eq!(identity.name, "MyLibrary");
        assert_eq!(identity.version, AssemblyVersion::new(1, 2, 3, 4));
    }

    #[test]
    fn test_assembly_identity_parse_full_mscorlib() {
        let identity = AssemblyIdentity::parse(
            "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
        )
        .unwrap();

        assert_eq!(identity.name, "mscorlib");
        assert_eq!(identity.version, AssemblyVersion::new(4, 0, 0, 0));
        assert!(identity.culture.is_none()); // "neutral" maps to None
        assert!(identity.strong_name.is_some());

        if let Some(Identity::Token(token)) = identity.strong_name {
            // Token is parsed as little-endian bytes
            let expected = u64::from_le_bytes([0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89]);
            assert_eq!(token, expected);
        } else {
            panic!("Expected Token identity");
        }
    }

    #[test]
    fn test_assembly_identity_parse_with_culture() {
        let identity = AssemblyIdentity::parse(
            "Resources, Version=1.0.0.0, Culture=en-US, PublicKeyToken=null",
        )
        .unwrap();

        assert_eq!(identity.name, "Resources");
        assert_eq!(identity.culture, Some("en-US".to_string()));
        assert!(identity.strong_name.is_none());
    }

    #[test]
    fn test_assembly_identity_parse_with_architecture() {
        let identity =
            AssemblyIdentity::parse("NativeLib, Version=1.0.0.0, ProcessorArchitecture=x86")
                .unwrap();

        assert_eq!(identity.name, "NativeLib");
        assert_eq!(
            identity.processor_architecture,
            Some(ProcessorArchitecture::X86)
        );
    }

    #[test]
    fn test_assembly_identity_parse_empty_returns_error() {
        // Empty assembly names are invalid per ECMA-335
        let result = AssemblyIdentity::parse("");
        assert!(result.is_err());

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("cannot be empty"),
            "Error message should mention empty name: {}",
            err_msg
        );
    }

    #[test]
    fn test_assembly_identity_parse_whitespace_only_returns_error() {
        // Whitespace-only assembly names should also be rejected (trim happens first)
        let result = AssemblyIdentity::parse("   ");
        assert!(result.is_err());
    }

    #[test]
    fn test_assembly_identity_parse_invalid_hex_token() {
        // Invalid hex characters in PublicKeyToken should return an error
        let result =
            AssemblyIdentity::parse("MyLib, Version=1.0.0.0, PublicKeyToken=xyz_not_hex_123");
        assert!(result.is_err());

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Invalid hex"),
            "Error message should mention invalid hex: {}",
            err_msg
        );
    }

    #[test]
    fn test_assembly_identity_parse_wrong_length_token() {
        // Wrong length PublicKeyToken (not 8 bytes) should return an error
        let result = AssemblyIdentity::parse(
            "MyLib, Version=1.0.0.0, PublicKeyToken=b77a5c56", // Only 4 bytes
        );
        assert!(result.is_err());

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("8 bytes"),
            "Error message should mention expected length: {}",
            err_msg
        );
    }

    #[test]
    fn test_assembly_identity_parse_too_long_token() {
        // Too long PublicKeyToken should return an error
        let result = AssemblyIdentity::parse(
            "MyLib, Version=1.0.0.0, PublicKeyToken=b77a5c561934e089aabbccdd", // 12 bytes
        );
        assert!(result.is_err());

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("8 bytes"),
            "Error message should mention expected length: {}",
            err_msg
        );
    }

    #[test]
    fn test_assembly_identity_parse_invalid_processor_architecture() {
        // Invalid ProcessorArchitecture should return an error
        let result =
            AssemblyIdentity::parse("MyLib, Version=1.0.0.0, ProcessorArchitecture=PowerPC");
        assert!(result.is_err());

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Unknown processor architecture"),
            "Error message should mention unknown architecture: {}",
            err_msg
        );
    }

    #[test]
    fn test_assembly_identity_display_name_simple() {
        let identity = AssemblyIdentity::new(
            "MyLibrary",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None,
            None,
        );

        let display = identity.display_name();
        assert!(display.contains("MyLibrary"));
        assert!(display.contains("Version=1.0.0.0"));
        assert!(display.contains("Culture=neutral"));
        assert!(display.contains("PublicKeyToken=null"));
    }

    #[test]
    fn test_assembly_identity_display_name_with_culture() {
        let identity = AssemblyIdentity::new(
            "Resources",
            AssemblyVersion::new(1, 0, 0, 0),
            Some("fr-FR".to_string()),
            None,
            None,
        );

        let display = identity.display_name();
        assert!(display.contains("Culture=fr-FR"));
    }

    #[test]
    #[cfg(feature = "legacy-crypto")]
    fn test_assembly_identity_display_name_with_pubkey() {
        // Test that PubKey variants compute and display their token using SHA1
        // Note: This test requires legacy-crypto because token computation uses SHA1
        let pubkey_data = vec![
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
        ];
        let identity = AssemblyIdentity::new(
            "StrongLib",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            Some(Identity::PubKey(pubkey_data)),
            None,
        );

        let display = identity.display_name();
        // Should NOT contain "null" for PublicKeyToken since we have a PubKey
        assert!(
            !display.contains("PublicKeyToken=null"),
            "PubKey should compute a token, not show null: {}",
            display
        );
        // Should contain a 16-character hex token
        assert!(
            display.contains("PublicKeyToken="),
            "Should have PublicKeyToken in display: {}",
            display
        );
    }

    #[test]
    #[cfg(feature = "legacy-crypto")]
    fn test_assembly_identity_display_name_with_ecma_key() {
        // Test that EcmaKey variants compute and display their token using SHA1
        // Note: This test requires legacy-crypto because token computation uses SHA1
        let ecma_data = vec![
            0x06, 0x28, 0xAC, 0x03, 0x00, 0x06, 0x7A, 0x06, 0x6F, 0xAB, 0x02, 0x00, 0x0A, 0x0B,
            0x17, 0x6A,
        ];
        let identity = AssemblyIdentity::new(
            "FrameworkLib",
            AssemblyVersion::new(4, 0, 0, 0),
            None,
            Some(Identity::EcmaKey(ecma_data)),
            None,
        );

        let display = identity.display_name();
        // Should NOT contain "null" for PublicKeyToken since we have an EcmaKey
        assert!(
            !display.contains("PublicKeyToken=null"),
            "EcmaKey should compute a token, not show null: {}",
            display
        );
    }

    #[test]
    fn test_assembly_identity_simple_name() {
        let identity = AssemblyIdentity::new(
            "System.Core",
            AssemblyVersion::new(4, 0, 0, 0),
            None,
            None,
            None,
        );

        assert_eq!(identity.simple_name(), "System.Core");
    }

    #[test]
    fn test_assembly_identity_is_strong_named() {
        let weak = AssemblyIdentity::new(
            "WeakAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None,
            None,
        );
        assert!(!weak.is_strong_named());

        let strong = AssemblyIdentity::new(
            "StrongAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            Some(Identity::Token(0x1234567890ABCDEF)),
            None,
        );
        assert!(strong.is_strong_named());
    }

    #[test]
    fn test_assembly_identity_is_culture_neutral() {
        let neutral = AssemblyIdentity::new(
            "MainAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None,
            None,
        );
        assert!(neutral.is_culture_neutral());

        let localized = AssemblyIdentity::new(
            "Resources",
            AssemblyVersion::new(1, 0, 0, 0),
            Some("de-DE".to_string()),
            None,
            None,
        );
        assert!(!localized.is_culture_neutral());
    }

    #[test]
    fn test_assembly_identity_equality() {
        let id1 = AssemblyIdentity::new(
            "TestAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None,
            None,
        );

        let id2 = AssemblyIdentity::new(
            "TestAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None,
            None,
        );

        let id_different_version = AssemblyIdentity::new(
            "TestAssembly",
            AssemblyVersion::new(2, 0, 0, 0),
            None,
            None,
            None,
        );

        let id_different_name = AssemblyIdentity::new(
            "OtherAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None,
            None,
        );

        assert_eq!(id1, id2);
        assert_ne!(id1, id_different_version);
        assert_ne!(id1, id_different_name);
    }

    #[test]
    fn test_assembly_identity_equality_ignores_strong_name_difference() {
        // Strong name differences should NOT affect equality
        // (as per the PartialEq implementation comment)
        let id_with_token = AssemblyIdentity::new(
            "TestAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            Some(Identity::Token(0x1234567890ABCDEF)),
            None,
        );

        let id_without_token = AssemblyIdentity::new(
            "TestAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None,
            None,
        );

        // These should be equal because strong_name is excluded from equality
        assert_eq!(id_with_token, id_without_token);
    }

    #[test]
    fn test_assembly_identity_hash_consistency() {
        let id1 = AssemblyIdentity::new(
            "TestAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            Some(Identity::Token(0x1234567890ABCDEF)),
            None,
        );

        let id2 = AssemblyIdentity::new(
            "TestAssembly",
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None, // Different strong_name
            None,
        );

        // Since they are equal, they should hash to the same value
        // and work correctly as HashMap keys
        let mut map = HashMap::new();
        map.insert(id1.clone(), "value1");

        // Should find the same entry with id2 since they're equal
        assert!(map.contains_key(&id2));
    }

    #[test]
    fn test_assembly_identity_from_str() {
        let identity: AssemblyIdentity = "System.Core, Version=3.5.0.0".parse().unwrap();
        assert_eq!(identity.name, "System.Core");
        assert_eq!(identity.version, AssemblyVersion::new(3, 5, 0, 0));
    }

    #[test]
    fn test_assembly_identity_roundtrip_parse_display() {
        let original = AssemblyIdentity::new(
            "TestLib",
            AssemblyVersion::new(2, 1, 3, 4),
            None,
            None,
            Some(ProcessorArchitecture::AMD64),
        );

        let display = original.display_name();
        let parsed = AssemblyIdentity::parse(&display).unwrap();

        assert_eq!(original.name, parsed.name);
        assert_eq!(original.version, parsed.version);
        assert_eq!(original.culture, parsed.culture);
        assert_eq!(
            original.processor_architecture,
            parsed.processor_architecture
        );
    }

    #[test]
    fn test_assembly_identity_roundtrip_with_token() {
        // Test round-trip with a token-based strong name
        // The token value should be fully preserved through parse/display cycles
        let original = AssemblyIdentity::new(
            "StrongLib",
            AssemblyVersion::new(1, 2, 3, 4),
            Some("en-US".to_string()),
            Some(Identity::Token(0xb77a5c561934e089)),
            Some(ProcessorArchitecture::X86),
        );

        let display = original.display_name();
        let parsed = AssemblyIdentity::parse(&display).unwrap();

        assert_eq!(original.name, parsed.name);
        assert_eq!(original.version, parsed.version);
        assert_eq!(original.culture, parsed.culture);
        assert_eq!(
            original.processor_architecture,
            parsed.processor_architecture
        );

        // Strong name should be fully preserved
        assert_eq!(original.strong_name, parsed.strong_name);

        // Verify the display string is stable (same after multiple roundtrips)
        let display2 = parsed.display_name();
        assert_eq!(
            display, display2,
            "Display string should be stable across roundtrips"
        );

        // Parse again and verify everything is still equal
        let parsed2 = AssemblyIdentity::parse(&display2).unwrap();
        assert_eq!(parsed.strong_name, parsed2.strong_name);
    }

    #[test]
    fn test_assembly_identity_token_format_consistency() {
        // Test that tokens parsed from standard .NET format work correctly
        // The standard format is big-endian hex (e.g., "b77a5c561934e089")
        let identity = AssemblyIdentity::parse(
            "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
        )
        .unwrap();

        // Verify the token was parsed
        assert!(identity.strong_name.is_some());
        if let Some(Identity::Token(token)) = identity.strong_name {
            // The token bytes "b77a5c561934e089" interpreted as little-endian
            let expected = u64::from_le_bytes([0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89]);
            assert_eq!(token, expected);
        }
    }

    #[test]
    fn test_assembly_identity_parse_extra_whitespace() {
        // Parts are trimmed, so extra whitespace around commas should work
        let identity = AssemblyIdentity::parse(
            "MyLib ,  Version=1.0.0.0 ,  Culture=neutral ,  PublicKeyToken=null",
        )
        .unwrap();

        assert_eq!(identity.name, "MyLib");
        assert_eq!(identity.version, AssemblyVersion::new(1, 0, 0, 0));
    }

    #[test]
    fn test_assembly_identity_parse_case_insensitive_culture() {
        // Culture value should be preserved as-is (case-sensitive)
        let identity = AssemblyIdentity::parse("MyLib, Version=1.0.0.0, Culture=EN-us").unwrap();
        assert_eq!(identity.culture, Some("EN-us".to_string()));
    }

    #[test]
    fn test_assembly_identity_parse_unknown_fields_ignored() {
        // Unknown fields should be silently ignored
        let identity =
            AssemblyIdentity::parse("MyLib, Version=1.0.0.0, UnknownField=value, Culture=neutral")
                .unwrap();

        assert_eq!(identity.name, "MyLib");
        assert_eq!(identity.version, AssemblyVersion::new(1, 0, 0, 0));
        assert!(identity.culture.is_none());
    }

    #[test]
    fn test_assembly_version_unknown_sentinel() {
        let unknown = AssemblyVersion::UNKNOWN;
        assert!(unknown.is_unknown());
        assert_eq!(unknown.major, 0);
        assert_eq!(unknown.minor, 0);
        assert_eq!(unknown.build, 0);
        assert_eq!(unknown.revision, 0);

        let not_unknown = AssemblyVersion::new(0, 0, 0, 1);
        assert!(!not_unknown.is_unknown());
    }

    #[test]
    fn test_processor_architecture_full_coverage() {
        // This test ensures all ProcessorArchitecture variants are covered by both
        // parse() and try_from(), and that Display outputs match parse() inputs.
        // If a new variant is added, this test will fail until both implementations
        // are updated.
        let all_variants = [
            (ProcessorArchitecture::MSIL, "MSIL", 0x0000_u32),
            (ProcessorArchitecture::X86, "x86", 0x014C),
            (ProcessorArchitecture::IA64, "IA64", 0x0200),
            (ProcessorArchitecture::AMD64, "AMD64", 0x8664),
            (ProcessorArchitecture::ARM, "ARM", 0x01C0),
            (ProcessorArchitecture::ARM64, "ARM64", 0xAA64),
        ];

        for (expected_arch, display_name, machine_code) in all_variants {
            // Test parse() accepts the display name (case-insensitive)
            let parsed = ProcessorArchitecture::parse(display_name)
                .unwrap_or_else(|_| panic!("Failed to parse '{}'", display_name));
            assert_eq!(
                parsed, expected_arch,
                "parse('{}') returned wrong variant",
                display_name
            );

            // Test parse() accepts lowercase version
            let parsed_lower = ProcessorArchitecture::parse(&display_name.to_lowercase())
                .unwrap_or_else(|_| panic!("Failed to parse lowercase '{}'", display_name));
            assert_eq!(
                parsed_lower, expected_arch,
                "parse('{}') lowercase returned wrong variant",
                display_name
            );

            // Test try_from() accepts the machine code
            let from_code = ProcessorArchitecture::try_from(machine_code)
                .unwrap_or_else(|_| panic!("Failed try_from(0x{:04X})", machine_code));
            assert_eq!(
                from_code, expected_arch,
                "try_from(0x{:04X}) returned wrong variant",
                machine_code
            );

            // Test Display outputs the expected name
            let displayed = expected_arch.to_string();
            // Display should output a name that can be parsed back
            let roundtrip = ProcessorArchitecture::parse(&displayed)
                .unwrap_or_else(|_| panic!("Failed to roundtrip '{}'", displayed));
            assert_eq!(
                roundtrip, expected_arch,
                "Display roundtrip failed for {:?}",
                expected_arch
            );
        }

        // Also test the x64 alias for AMD64
        let x64_parsed = ProcessorArchitecture::parse("x64").unwrap();
        assert_eq!(x64_parsed, ProcessorArchitecture::AMD64);
    }

    #[test]
    fn test_assembly_version_is_compatible_with() {
        let v4_0 = AssemblyVersion::new(4, 0, 0, 0);
        let v4_5 = AssemblyVersion::new(4, 5, 0, 0);
        let v4_5_1 = AssemblyVersion::new(4, 5, 1, 0);
        let v5_0 = AssemblyVersion::new(5, 0, 0, 0);
        let v_unknown = AssemblyVersion::UNKNOWN;

        // Same version is always compatible
        assert!(v4_0.is_compatible_with(&v4_0));
        assert!(v4_5.is_compatible_with(&v4_5));

        // Higher minor version is compatible with lower requirement (same major)
        assert!(v4_5.is_compatible_with(&v4_0));
        assert!(v4_5_1.is_compatible_with(&v4_0));
        assert!(v4_5_1.is_compatible_with(&v4_5));

        // Lower version is NOT compatible with higher requirement
        assert!(!v4_0.is_compatible_with(&v4_5));
        assert!(!v4_5.is_compatible_with(&v4_5_1));

        // Different major version is NOT compatible
        assert!(!v5_0.is_compatible_with(&v4_0));
        assert!(!v4_0.is_compatible_with(&v5_0));
        assert!(!v5_0.is_compatible_with(&v4_5));

        // Any version is compatible with unknown (0.0.0.0)
        assert!(v4_0.is_compatible_with(&v_unknown));
        assert!(v4_5.is_compatible_with(&v_unknown));
        assert!(v5_0.is_compatible_with(&v_unknown));
        assert!(v_unknown.is_compatible_with(&v_unknown));
    }

    #[test]
    fn test_assembly_identity_satisfies() {
        let system_core_v4_0 = AssemblyIdentity::new(
            "System.Core".to_string(),
            AssemblyVersion::new(4, 0, 0, 0),
            None,
            None,
            None,
        );

        let system_core_v4_5 = AssemblyIdentity::new(
            "System.Core".to_string(),
            AssemblyVersion::new(4, 5, 0, 0),
            None,
            None,
            None,
        );

        let system_core_v5_0 = AssemblyIdentity::new(
            "System.Core".to_string(),
            AssemblyVersion::new(5, 0, 0, 0),
            None,
            None,
            None,
        );

        let system_v4_0 = AssemblyIdentity::new(
            "System".to_string(),
            AssemblyVersion::new(4, 0, 0, 0),
            None,
            None,
            None,
        );

        // Same identity satisfies itself
        assert!(system_core_v4_0.satisfies(&system_core_v4_0));

        // Higher version satisfies lower requirement (same name)
        assert!(system_core_v4_5.satisfies(&system_core_v4_0));

        // Lower version does NOT satisfy higher requirement
        assert!(!system_core_v4_0.satisfies(&system_core_v4_5));

        // Different major version does NOT satisfy
        assert!(!system_core_v5_0.satisfies(&system_core_v4_0));

        // Different name does NOT satisfy
        assert!(!system_v4_0.satisfies(&system_core_v4_0));
        assert!(!system_core_v4_0.satisfies(&system_v4_0));
    }

    #[test]
    fn test_assembly_identity_satisfies_case_insensitive() {
        let lower = AssemblyIdentity::new(
            "system.core".to_string(),
            AssemblyVersion::new(4, 0, 0, 0),
            None,
            None,
            None,
        );

        let upper = AssemblyIdentity::new(
            "System.Core".to_string(),
            AssemblyVersion::new(4, 0, 0, 0),
            None,
            None,
            None,
        );

        let mixed = AssemblyIdentity::new(
            "SYSTEM.CORE".to_string(),
            AssemblyVersion::new(4, 0, 0, 0),
            None,
            None,
            None,
        );

        // Name comparison should be case-insensitive
        assert!(lower.satisfies(&upper));
        assert!(upper.satisfies(&lower));
        assert!(mixed.satisfies(&lower));
        assert!(lower.satisfies(&mixed));
    }

    #[test]
    fn test_assembly_identity_satisfies_culture() {
        let neutral = AssemblyIdentity::new(
            "MyLib".to_string(),
            AssemblyVersion::new(1, 0, 0, 0),
            None,
            None,
            None,
        );

        let en_us = AssemblyIdentity::new(
            "MyLib".to_string(),
            AssemblyVersion::new(1, 0, 0, 0),
            Some("en-US".to_string()),
            None,
            None,
        );

        let fr_fr = AssemblyIdentity::new(
            "MyLib".to_string(),
            AssemblyVersion::new(1, 0, 0, 0),
            Some("fr-FR".to_string()),
            None,
            None,
        );

        // Same culture satisfies
        assert!(neutral.satisfies(&neutral));
        assert!(en_us.satisfies(&en_us));

        // Different cultures do NOT satisfy
        assert!(!neutral.satisfies(&en_us));
        assert!(!en_us.satisfies(&neutral));
        assert!(!en_us.satisfies(&fr_fr));
    }
}