daaki-message 0.2.0

RFC 5322 email message parser and builder
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
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
#![allow(clippy::unwrap_used, clippy::expect_used)]

use super::*;

/// Test-only helper that folds before an oversized token without splitting it.
///
/// RFC 5322 Section 2.2.3 only permits folding at existing FWS boundaries, so
/// any internal splitting must stay outside the token itself.
fn force_fold_word(output: &mut Vec<u8>, bytes: &[u8], mut line_len: usize) -> usize {
    if line_len > 1 {
        output.extend_from_slice(b"\r\n ");
        line_len = 1;
    }
    output.extend_from_slice(bytes);
    line_len += bytes.len();
    line_len
}

/// Test-only infallible wrapper for focused header-folding unit tests.
fn write_header(output: &mut Vec<u8>, name: &str, value: &str) {
    try_write_header(output, name, value)
        .expect("test header values must satisfy RFC 5322 line-length limits");
}

/// Helper: create a `HeaderName` in test code (unchecked).
fn hdr(s: &str) -> HeaderName {
    HeaderName::new_unchecked(s)
}

/// Helper: create a message-ID string in test code.
fn mid(s: &str) -> String {
    s.to_owned()
}

fn make_email() -> OutgoingEmail {
    OutgoingEmail {
        from: vec![Address {
            name: Some("Sender".into()),
            email: "sender@example.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "to@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Test Subject".into(),
        body_text: None,
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    }
}

/// Helper: convert raw bytes to string for assertion.
fn raw_str(built: &BuiltMessage) -> String {
    String::from_utf8_lossy(&built.raw).into_owned()
}

#[test]
fn build_text_only() {
    let mut email = make_email();
    email.body_text = Some("Hello, World!".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("Content-Type: text/plain; charset=utf-8"));
    assert!(s.contains("Hello, World!"));
    assert!(s.contains("From: Sender <sender@example.com>"));
    assert!(s.contains("To: to@example.com"));
    assert!(s.contains("Subject: Test Subject"));
    assert!(s.contains("MIME-Version: 1.0"));
    assert!(s.contains("Date: "));
    assert!(s.contains("Message-ID: <"));
}

#[test]
fn build_html_only() {
    let mut email = make_email();
    email.body_html = Some("<h1>Hello</h1>".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("Content-Type: text/html; charset=utf-8"));
    assert!(s.contains("<h1>Hello</h1>"));
}

#[test]
fn build_text_and_html() {
    let mut email = make_email();
    email.body_text = Some("Plain text".into());
    email.body_html = Some("<p>HTML</p>".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("multipart/alternative"));
    assert!(s.contains("text/plain; charset=utf-8"));
    assert!(s.contains("text/html; charset=utf-8"));
    assert!(s.contains("Plain text"));
    assert!(s.contains("<p>HTML</p>"));
    // text/plain should come before text/html (RFC 2046 Section 5.1.4)
    let plain_pos = s.find("text/plain").unwrap();
    let html_pos = s.find("text/html").unwrap();
    assert!(plain_pos < html_pos);
}

#[test]
fn build_with_attachment() {
    let mut email = make_email();
    email.body_text = Some("See attached".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "test.pdf".into(),
        content_type: "application/pdf".into(),
        data: b"fake pdf data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("multipart/mixed"));
    assert!(s.contains("Content-Type: application/pdf"));
    assert!(s.contains("Content-Disposition: attachment; filename=\"test.pdf\""));
    assert!(s.contains("Content-Transfer-Encoding: base64"));
}

/// RFC 2387: inline attachments with Content-ID must be wrapped in
/// `multipart/related` with the HTML body they reference, not placed
/// as siblings in `multipart/mixed`.
#[test]
fn build_inline_image_uses_multipart_related() {
    let mut email = make_email();
    email.body_html = Some("<img src=\"cid:logo@example.com\">".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "logo.png".into(),
        content_type: "image/png".into(),
        data: b"PNG data".to_vec(),
        is_inline: true,
        content_id: Some("logo@example.com".into()),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("multipart/related"),
        "inline images with Content-ID must be in multipart/related (RFC 2387): {s}"
    );
}

/// RFC 2387: when inline and regular attachments coexist, the structure
/// must be multipart/mixed containing a multipart/related (with HTML +
/// inline images) and the regular attachment as a sibling.
#[test]
fn build_mixed_inline_and_regular_attachments() {
    let mut email = make_email();
    email.body_html = Some("<img src=\"cid:logo@example.com\">".into());
    email.attachments = vec![
        OutgoingAttachment {
            filename: "logo.png".into(),
            content_type: "image/png".into(),
            data: b"PNG data".to_vec(),
            is_inline: true,
            content_id: Some("logo@example.com".into()),
        },
        OutgoingAttachment {
            filename: "report.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"PDF data".to_vec(),
            is_inline: false,
            content_id: None,
        },
    ];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("multipart/mixed"),
        "mixed inline + regular attachments needs multipart/mixed: {s}"
    );
    assert!(
        s.contains("multipart/related"),
        "inline images must be in multipart/related (RFC 2387): {s}"
    );
}

/// RFC 2183 Section 2 / RFC 2392: inline attachments must emit
/// `Content-Disposition: inline` and a `Content-ID` header wrapped in
/// angle brackets.
#[test]
fn build_inline_attachment_with_content_id() {
    let mut email = make_email();
    email.body_html = Some("<img src=\"cid:img001@example.com\">".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "logo.png".into(),
        content_type: "image/png".into(),
        data: b"fake png data".to_vec(),
        is_inline: true,
        content_id: Some("img001@example.com".into()),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Disposition: inline; filename=\"logo.png\""),
        "inline disposition missing: {s}"
    );
    assert!(
        s.contains("Content-ID: <img001@example.com>"),
        "Content-ID header missing or not wrapped in angle brackets: {s}"
    );
}

/// RFC 2392 / RFC 5322 Section 3.6.4: caller input that already includes
/// angle brackets must be normalized to a single on-wire `Content-ID:
/// <...>` header, not double-wrapped as `<<...>>`.
#[test]
fn build_inline_attachment_normalizes_bracketed_content_id() {
    let mut email = make_email();
    email.body_html = Some("<img src=\"cid:img001@example.com\">".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "logo.png".into(),
        content_type: "image/png".into(),
        data: b"fake png data".to_vec(),
        is_inline: true,
        content_id: Some("<img001@example.com>".into()),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-ID: <img001@example.com>\r\n"),
        "Content-ID must be normalized to a single bracketed msg-id: {s}"
    );
    assert!(
        !s.contains("Content-ID: <<img001@example.com>>"),
        "Content-ID must not be double-wrapped: {s}"
    );
}

#[test]
fn build_text_html_attachments() {
    let mut email = make_email();
    email.body_text = Some("Text".into());
    email.body_html = Some("<b>HTML</b>".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "file.txt".into(),
        content_type: "text/plain".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Should have outer multipart/mixed and inner multipart/alternative
    assert!(s.contains("multipart/mixed"));
    assert!(s.contains("multipart/alternative"));
}

#[test]
fn build_no_body() {
    let email = make_email();
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Should still have a text/plain content type
    assert!(s.contains("Content-Type: text/plain; charset=utf-8"));
}

#[test]
fn build_bcc_not_in_headers() {
    let mut email = make_email();
    email.bcc = vec![Address {
        name: None,
        email: "hidden@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // BCC must NOT appear in headers (RFC 5322 Section 3.6.3)
    assert!(!s.contains("Bcc:"));
    assert!(!s.contains("hidden@example.com"));
}

#[test]
fn build_bcc_in_envelope() {
    let mut email = make_email();
    email.bcc = vec![Address {
        name: None,
        email: "hidden@example.com".into(),
    }];

    let built = build_message(&email).unwrap();

    // BCC must be in envelope recipients
    assert!(built
        .envelope_recipients
        .contains(&"hidden@example.com".to_string()));
    assert!(built
        .envelope_recipients
        .contains(&"to@example.com".to_string()));
}

#[test]
fn build_message_id_format() {
    let email = make_email();
    let built = build_message(&email).unwrap();

    // Message-ID should be hex@domain
    assert!(built.message_id.contains('@'));
    assert!(built.message_id.ends_with("example.com"));

    // Should appear in headers with angle brackets
    let s = raw_str(&built);
    assert!(s.contains(&format!("Message-ID: <{}>", built.message_id)));
}

#[test]
fn build_threading_headers() {
    let mut email = make_email();
    email.in_reply_to = vec![mid("parent@host.com")];
    email.references = vec![mid("root@host.com"), mid("parent@host.com")];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("In-Reply-To: <parent@host.com>"));
    assert!(s.contains("References: <root@host.com> <parent@host.com>"));
}

/// If the caller accidentally passes already-bracketed message-IDs,
/// the builder must strip them before wrapping — not produce `<<id>>` which
/// violates RFC 5322 Section 3.6.4 (msg-id = "<" addr-spec ">").
#[test]
fn build_threading_headers_already_bracketed() {
    let mut email = make_email();
    email.in_reply_to = vec![mid("<parent@host.com>")];
    email.references = vec![mid("<root@host.com>"), mid("<parent@host.com>")];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Must NOT double-wrap
    assert!(
        !s.contains("<<"),
        "Double angle brackets found in headers: {s}"
    );
    assert!(s.contains("In-Reply-To: <parent@host.com>"));
    assert!(s.contains("References: <root@host.com> <parent@host.com>"));
}

#[test]
fn build_invalid_address_error() {
    let mut email = make_email();
    email.from[0].email = "not-an-email".into();

    let result = build_message(&email);
    assert!(matches!(result, Err(Error::InvalidAddress(_))));
}

#[test]
fn build_empty_address_error() {
    let mut email = make_email();
    email.from[0].email = String::new();

    let result = build_message(&email);
    assert!(matches!(result, Err(Error::InvalidAddress(_))));
}

#[test]
fn build_invalid_mime_fallback() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "file.bin".into(),
        content_type: "not_a_valid_mime".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Should fall back to application/octet-stream
    assert!(s.contains("Content-Type: application/octet-stream"));
}

#[test]
fn build_reply_to() {
    let mut email = make_email();
    email.reply_to = vec![Address {
        name: Some("Reply".into()),
        email: "reply@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("Reply-To: Reply <reply@example.com>"));
}

/// RFC 5322 Section 3.6 field occurrence table: destination fields are
/// optional, so a draft-like message with no `To`, `Cc`, or `Bcc` is
/// still syntactically valid.
#[test]
fn build_no_destination_headers_is_valid() {
    let mut email = make_email();
    email.to.clear();
    email.body_text = Some("draft body".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(!s.contains("\r\nTo:"));
    assert!(!s.contains("\r\nCc:"));
    assert!(!s.contains("\r\nBcc:"));
    assert!(built.envelope_recipients.is_empty());
}

#[test]
fn build_cc_in_headers_and_envelope() {
    let mut email = make_email();
    email.cc = vec![Address {
        name: None,
        email: "cc@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("Cc: cc@example.com"));
    assert!(built
        .envelope_recipients
        .contains(&"cc@example.com".to_string()));
}

#[test]
fn build_attachment_base64_line_wrapping() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    // Create data that produces base64 longer than 76 chars
    email.attachments = vec![OutgoingAttachment {
        filename: "big.bin".into(),
        content_type: "application/octet-stream".into(),
        data: vec![0xAB; 100],
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Find base64 lines after Content-Transfer-Encoding: base64
    let after_b64_header = s.find("Content-Transfer-Encoding: base64").unwrap();
    let body_section = &s[after_b64_header..];
    // Check that no line exceeds 78 chars (76 + \r\n)
    for line in body_section.split("\r\n") {
        if !line.is_empty() && !line.starts_with("--") && !line.contains(':') {
            assert!(
                line.len() <= 76,
                "Base64 line too long ({} chars): {line}",
                line.len()
            );
        }
    }
}

#[test]
fn message_id_domain_fallback() {
    let mut email = make_email();
    email.from[0].email = "local-only@".into();
    // Should fail validation due to empty domain
    assert!(build_message(&email).is_err());
}

#[test]
fn round_trip_build_then_parse() {
    let mut email = make_email();
    email.body_text = Some("Round-trip test body".into());
    email.body_html = Some("<p>Round-trip HTML</p>".into());
    email.in_reply_to = vec![mid("parent@host.com")];
    email.references = vec![mid("root@host.com"), mid("parent@host.com")];
    email.cc = vec![Address {
        name: Some("CC User".into()),
        email: "cc@example.com".into(),
    }];

    let built = build_message(&email).unwrap();

    // Parse the built message
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(parsed.from[0].email, "sender@example.com");
    assert_eq!(parsed.from[0].name.as_deref(), Some("Sender"));
    assert_eq!(parsed.to.len(), 1);
    assert_eq!(parsed.to[0].email, "to@example.com");
    assert_eq!(parsed.cc.len(), 1);
    assert_eq!(parsed.cc[0].email, "cc@example.com");
    assert_eq!(parsed.subject.as_deref(), Some("Test Subject"));
    assert_eq!(
        parsed.message_id.as_deref(),
        Some(built.message_id.as_str())
    );
    assert_eq!(parsed.in_reply_to, vec!["parent@host.com"]);
    assert_eq!(parsed.references, vec!["root@host.com", "parent@host.com"]);
    assert_eq!(parsed.body_text.as_deref(), Some("Round-trip test body"));
    assert_eq!(parsed.body_html.as_deref(), Some("<p>Round-trip HTML</p>"));
    assert!(parsed.date.is_some());
}

#[test]
fn message_id_is_crypto_random() {
    // Generate two Message-IDs and verify they're different (crypto-random)
    let email = make_email();
    let built1 = build_message(&email).unwrap();
    let built2 = build_message(&email).unwrap();
    assert_ne!(built1.message_id, built2.message_id);

    // Verify hex format: should be 32 hex chars + @ + domain
    let at_pos = built1.message_id.find('@').unwrap();
    let hex_part = &built1.message_id[..at_pos];
    assert_eq!(hex_part.len(), 32);
    assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
}

#[test]
fn build_bcc_only_recipients() {
    // BCC-only: no To/Cc — should succeed with bcc in envelope only
    let mut email = make_email();
    email.to.clear();
    email.bcc = vec![Address {
        name: None,
        email: "hidden@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // No To header
    assert!(!s.contains("\r\nTo:"));
    // BCC must NOT appear in headers
    assert!(!s.contains("Bcc:"));
    assert!(!s.contains("hidden@example.com"));
    // But must be in envelope
    assert_eq!(built.envelope_recipients, vec!["hidden@example.com"]);
}

#[test]
fn build_round_trip_with_attachments() {
    let mut email = make_email();
    email.body_text = Some("Text body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "test.txt".into(),
        content_type: "text/plain".into(),
        data: b"attachment data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(parsed.body_text.as_deref(), Some("Text body"));
    assert_eq!(parsed.attachments.len(), 1);
    assert_eq!(parsed.attachments[0].filename.as_deref(), Some("test.txt"));
}

#[test]
fn build_html_only_with_attachments() {
    let mut email = make_email();
    email.body_html = Some("<p>Hello</p>".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "data.bin".into(),
        content_type: "application/octet-stream".into(),
        data: vec![1, 2, 3],
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Should have outer multipart/mixed
    assert!(s.contains("multipart/mixed"));
    assert!(s.contains("text/html; charset=utf-8"));
    assert!(s.contains("<p>Hello</p>"));
    assert!(s.contains("Content-Disposition: attachment; filename=\"data.bin\""));
}

#[test]
fn build_whitespace_in_address_rejected() {
    let mut email = make_email();
    email.to = vec![Address {
        name: None,
        email: "bad user@example.com".into(),
    }];

    let result = build_message(&email);
    assert!(matches!(result, Err(Error::InvalidAddress(_))));
}

#[test]
fn build_control_char_in_address_rejected() {
    let mut email = make_email();
    email.to = vec![Address {
        name: None,
        email: "user\x00@example.com".into(),
    }];

    let result = build_message(&email);
    assert!(matches!(result, Err(Error::InvalidAddress(_))));
}

#[test]
fn build_envelope_contains_all_recipients() {
    let mut email = make_email();
    email.to = vec![Address {
        name: None,
        email: "to@x.com".into(),
    }];
    email.cc = vec![Address {
        name: None,
        email: "cc@x.com".into(),
    }];
    email.bcc = vec![Address {
        name: None,
        email: "bcc@x.com".into(),
    }];

    let built = build_message(&email).unwrap();
    assert_eq!(built.envelope_recipients.len(), 3);
    assert!(built.envelope_recipients.contains(&"to@x.com".to_string()));
    assert!(built.envelope_recipients.contains(&"cc@x.com".to_string()));
    assert!(built.envelope_recipients.contains(&"bcc@x.com".to_string()));
}

#[test]
fn build_message_has_crlf_line_endings() {
    let mut email = make_email();
    email.body_text = Some("Hello".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // All header lines should end with \r\n
    for line in s.split("\r\n") {
        assert!(
            !line.contains('\n') || line.is_empty(),
            "bare LF found in line: {line:?}"
        );
    }
}

/// Body text containing bare LF (`\n`) must be normalized
/// to CRLF (`\r\n`) per RFC 5322 Section 2.1.
#[test]
fn build_body_bare_lf_normalized_to_crlf() {
    let mut email = make_email();
    email.body_text = Some("Line 1\nLine 2\nLine 3".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The body must not contain bare LF — all newlines should be CRLF
    for line in s.split("\r\n") {
        assert!(
            !line.contains('\n') || line.is_empty(),
            "bare LF found in output: {line:?}"
        );
    }
    // Verify the content is preserved
    assert!(s.contains("Line 1\r\nLine 2\r\nLine 3"));
}

/// HTML body with bare LF must also be normalized to CRLF.
#[test]
fn build_html_body_bare_lf_normalized_to_crlf() {
    let mut email = make_email();
    email.body_html = Some("<p>Line 1</p>\n<p>Line 2</p>".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    for line in s.split("\r\n") {
        assert!(
            !line.contains('\n') || line.is_empty(),
            "bare LF found in HTML output: {line:?}"
        );
    }
}

/// Body with mixed line endings (\r\n and \n) must normalize all.
#[test]
fn build_body_mixed_line_endings_normalized() {
    let mut email = make_email();
    email.body_text = Some("CRLF line\r\nLF line\nAnother LF\n".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    for line in s.split("\r\n") {
        assert!(
            !line.contains('\n') || line.is_empty(),
            "bare LF in mixed-endings output: {line:?}"
        );
    }
}

#[test]
fn build_empty_attachment_data() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "empty.bin".into(),
        content_type: "application/octet-stream".into(),
        data: vec![],
        is_inline: false,
        content_id: None,
    }];

    // Should succeed even with empty attachment data
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    assert!(s.contains("Content-Disposition: attachment; filename=\"empty.bin\""));
}

#[test]
fn build_multiple_attachments() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![
        OutgoingAttachment {
            filename: "a.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"pdf data".to_vec(),
            is_inline: false,
            content_id: None,
        },
        OutgoingAttachment {
            filename: "b.png".into(),
            content_type: "image/png".into(),
            data: b"png data".to_vec(),
            is_inline: false,
            content_id: None,
        },
    ];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("filename=\"a.pdf\""));
    assert!(s.contains("filename=\"b.png\""));
    assert!(s.contains("Content-Type: application/pdf"));
    assert!(s.contains("Content-Type: image/png"));
}

#[test]
fn build_date_header_rfc5322_format() {
    let email = make_email();
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Find the Date header and verify format
    let date_line = s
        .lines()
        .find(|l| l.starts_with("Date: "))
        .expect("Date header missing");
    // Should contain day-of-week abbreviation
    let dow_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
    assert!(
        dow_names.iter().any(|d| date_line.contains(d)),
        "Date header missing day-of-week: {date_line}"
    );
    // Should end with timezone offset
    assert!(
        date_line.contains("+0000"),
        "Date header missing timezone: {date_line}"
    );
}

/// RFC 5322 Section 3.6.1: when `OutgoingEmail.date` is `Some(...)`,
/// the builder must use that exact date instead of `DateTime::now()`.
#[test]
fn build_custom_date_honored() {
    let mut email = make_email();
    email.date = Some(crate::types::DateTime {
        year: 2020,
        month: 6,
        day: 15,
        hour: 10,
        minute: 30,
        second: 0,
        tz_offset_minutes: -300, // -0500
    });
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    let date_line = s
        .lines()
        .find(|l| l.starts_with("Date: "))
        .expect("Date header missing");
    assert_eq!(
        date_line, "Date: Mon, 15 Jun 2020 10:30:00 -0500",
        "builder must use the caller-supplied date"
    );
}

// -----------------------------------------------------------------------
// Additional edge case tests
// -----------------------------------------------------------------------

#[test]
fn build_unicode_subject() {
    let mut email = make_email();
    email.subject = "Héllo Wörld 你好 🌍".into();

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Subject must be RFC 2047 encoded, not raw UTF-8 (RFC 5322 Section 2.2)
    let header_section = s.split("\r\n\r\n").next().unwrap();
    assert!(
        header_section.is_ascii(),
        "Headers must be pure ASCII per RFC 5322 Section 2.2"
    );
    assert!(s.contains("=?UTF-8?B?"));

    // Must round-trip through parse
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(parsed.subject.as_deref(), Some("Héllo Wörld 你好 🌍"));
}

#[test]
/// Non-ASCII display names must be RFC 2047 encoded in the raw
/// message headers (RFC 5322 Section 2.2, RFC 2047 Section 5). The parser
/// must decode them back to the original name.
fn build_unicode_display_name() {
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("José García".into()),
        email: "jose@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Raw headers must be pure ASCII (RFC 5322 Section 2.2)
    let header_section = s.split("\r\n\r\n").next().unwrap();
    assert!(
        header_section.is_ascii(),
        "Headers must be pure ASCII per RFC 5322 Section 2.2, \
         but found non-ASCII in: {header_section}"
    );

    // Round-trip: parser must decode the display name back
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(parsed.from[0].name.as_deref(), Some("José García"));
    assert_eq!(parsed.from[0].email, "jose@example.com");
}

#[test]
fn build_empty_subject() {
    let mut email = make_email();
    email.subject = String::new();

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("Subject: \r\n"));
}

#[test]
fn build_special_chars_in_filename() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "my file (1).pdf".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("filename=\"my file (1).pdf\""));
}

/// Non-ASCII filenames must be encoded using RFC 2231
/// parameter encoding (`filename*=UTF-8''percent-encoded`), not raw
/// UTF-8 bytes in a quoted-string. The parser must round-trip the
/// encoded filename back to the original.
#[test]
fn build_non_ascii_filename_rfc2231_encoded() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "résumé.pdf".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Must use RFC 2231 encoding for non-ASCII filename
    assert!(
        s.contains("filename*=UTF-8''"),
        "Non-ASCII filename must use RFC 2231 encoding, got: {s}"
    );

    // Round-trip: parser should decode the RFC 2231 filename back
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(parsed.attachments.len(), 1);
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some("résumé.pdf")
    );
}

/// Non-ASCII filenames must include a legacy `filename`
/// parameter alongside `filename*` for backward compatibility with older
/// email clients that don't support RFC 2231 (RFC 2231 Section 5).
#[test]
fn build_non_ascii_filename_includes_legacy_fallback() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "résumé.pdf".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Must have RFC 2231 encoded filename*
    assert!(
        s.contains("filename*=UTF-8''"),
        "Missing RFC 2231 filename*: {s}"
    );

    // Must ALSO have legacy filename= fallback for older clients
    // (RFC 2231 Section 5 — dual parameter approach)
    assert!(
        s.contains("filename=\""),
        "Missing legacy filename fallback for non-ASCII attachment: {s}"
    );
}

#[test]
fn build_multiple_bcc_all_excluded() {
    let mut email = make_email();
    email.bcc = vec![
        Address {
            name: None,
            email: "bcc1@example.com".into(),
        },
        Address {
            name: None,
            email: "bcc2@example.com".into(),
        },
        Address {
            name: Some("BCC Three".into()),
            email: "bcc3@example.com".into(),
        },
    ];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // None of the BCC addresses should appear in headers (RFC 5322 Section 3.6.3)
    assert!(!s.contains("bcc1@example.com"));
    assert!(!s.contains("bcc2@example.com"));
    assert!(!s.contains("bcc3@example.com"));
    assert!(!s.contains("BCC Three"));
    assert!(!s.contains("Bcc:"));

    // But all should be in envelope
    assert_eq!(built.envelope_recipients.len(), 4); // 1 To + 3 BCC
    assert!(built
        .envelope_recipients
        .contains(&"bcc1@example.com".to_string()));
    assert!(built
        .envelope_recipients
        .contains(&"bcc2@example.com".to_string()));
    assert!(built
        .envelope_recipients
        .contains(&"bcc3@example.com".to_string()));
}

#[test]
fn build_from_without_display_name() {
    let mut email = make_email();
    email.from = vec![Address {
        name: None,
        email: "plain@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Should be bare email without angle brackets
    assert!(s.contains("From: plain@example.com\r\n"));
}

#[test]
fn build_all_recipient_types_together() {
    let mut email = make_email();
    email.to = vec![
        Address {
            name: Some("To One".into()),
            email: "to1@x.com".into(),
        },
        Address {
            name: None,
            email: "to2@x.com".into(),
        },
    ];
    email.cc = vec![Address {
        name: Some("CC One".into()),
        email: "cc1@x.com".into(),
    }];
    email.bcc = vec![Address {
        name: None,
        email: "bcc1@x.com".into(),
    }];
    email.reply_to = vec![Address {
        name: None,
        email: "reply@x.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("To: To One <to1@x.com>, to2@x.com"));
    assert!(s.contains("Cc: CC One <cc1@x.com>"));
    assert!(s.contains("Reply-To: reply@x.com"));
    assert!(!s.contains("Bcc:"));
    assert_eq!(built.envelope_recipients.len(), 4);
}

#[test]
fn build_large_attachment_base64() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    // 1000 bytes of data → base64 should be properly line-wrapped
    email.attachments = vec![OutgoingAttachment {
        filename: "large.bin".into(),
        content_type: "application/octet-stream".into(),
        data: vec![0x42; 1000],
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Find base64 content and check all lines are ≤76 chars
    let b64_header = "Content-Transfer-Encoding: base64\r\n\r\n";
    let b64_start = s.find(b64_header).unwrap() + b64_header.len();
    let b64_end = s[b64_start..].find("\r\n--").unwrap_or(s.len() - b64_start);
    let b64_block = &s[b64_start..b64_start + b64_end];

    for line in b64_block.split("\r\n") {
        if !line.is_empty() {
            assert!(
                line.len() <= 76,
                "Base64 line exceeds 76 chars ({} chars): {}",
                line.len(),
                line
            );
        }
    }
}

#[test]
fn build_round_trip_text_html_attachments() {
    // Full round-trip: build a complex message and verify it parses back
    let mut email = make_email();
    email.subject = "Complex message".into();
    email.body_text = Some("Plain text part".into());
    email.body_html = Some("<h1>HTML part</h1>".into());
    email.in_reply_to = vec![mid("parent-id@example.com")];
    email.references = vec![mid("root@example.com"), mid("parent-id@example.com")];
    email.cc = vec![Address {
        name: Some("CC User".into()),
        email: "cc@example.com".into(),
    }];
    email.attachments = vec![
        OutgoingAttachment {
            filename: "doc.pdf".into(),
            content_type: "application/pdf".into(),
            data: b"pdf content".to_vec(),
            is_inline: false,
            content_id: None,
        },
        OutgoingAttachment {
            filename: "img.png".into(),
            content_type: "image/png".into(),
            data: b"png content".to_vec(),
            is_inline: false,
            content_id: None,
        },
    ];

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(parsed.subject.as_deref(), Some("Complex message"));
    assert_eq!(parsed.from[0].email, "sender@example.com");
    assert_eq!(parsed.to.len(), 1);
    assert_eq!(parsed.cc.len(), 1);
    assert_eq!(
        parsed.message_id.as_deref(),
        Some(built.message_id.as_str())
    );
    assert_eq!(parsed.in_reply_to, vec!["parent-id@example.com"]);
    assert_eq!(
        parsed.references,
        vec!["root@example.com", "parent-id@example.com"]
    );
    assert_eq!(parsed.body_text.as_deref(), Some("Plain text part"));
    assert_eq!(parsed.body_html.as_deref(), Some("<h1>HTML part</h1>"));
    assert_eq!(parsed.attachments.len(), 2);
    assert_eq!(parsed.attachments[0].filename.as_deref(), Some("doc.pdf"));
    assert_eq!(parsed.attachments[1].filename.as_deref(), Some("img.png"));
}

#[test]
fn build_message_id_fallback_domain() {
    // Test that domain extraction works correctly
    assert_eq!(extract_domain("user@example.com"), Some("example.com"));
    assert_eq!(
        extract_domain("user@sub.domain.org"),
        Some("sub.domain.org")
    );
    assert_eq!(extract_domain("user@"), None);
    assert_eq!(extract_domain("no-at-sign"), None);
}

#[test]
fn build_no_body_with_attachments() {
    // No body text/html but has attachments — should get empty text/plain + attachment
    let mut email = make_email();
    email.attachments = vec![OutgoingAttachment {
        filename: "data.bin".into(),
        content_type: "application/octet-stream".into(),
        data: vec![1, 2, 3],
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(s.contains("multipart/mixed"));
    assert!(s.contains("text/plain; charset=utf-8"));
    assert!(s.contains("Content-Disposition: attachment; filename=\"data.bin\""));
}

#[test]
fn build_multiple_mime_type_fallbacks() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![
        OutgoingAttachment {
            filename: "a.bin".into(),
            content_type: String::new(), // empty
            data: b"data".to_vec(),
            is_inline: false,
            content_id: None,
        },
        OutgoingAttachment {
            filename: "b.bin".into(),
            content_type: "no-slash".into(), // no slash
            data: b"data".to_vec(),
            is_inline: false,
            content_id: None,
        },
        OutgoingAttachment {
            filename: "c.bin".into(),
            content_type: "/subtype".into(), // empty type
            data: b"data".to_vec(),
            is_inline: false,
            content_id: None,
        },
    ];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // All should fall back to application/octet-stream
    let count = s.matches("Content-Type: application/octet-stream").count();
    assert_eq!(count, 3, "Expected 3 fallback MIME types, got {count}");
}

#[test]
fn build_address_at_boundary_rejected() {
    // Address with @ at start or end
    let mut email = make_email();
    email.to = vec![Address {
        name: None,
        email: "@domain.com".into(),
    }];

    let result = build_message(&email);
    assert!(matches!(result, Err(Error::InvalidAddress(_))));

    let mut email2 = make_email();
    email2.to = vec![Address {
        name: None,
        email: "user@".into(),
    }];

    let result2 = build_message(&email2);
    assert!(matches!(result2, Err(Error::InvalidAddress(_))));
}

#[test]
fn mime_type_validation_subtype_chars() {
    // Valid MIME types
    assert!(is_valid_mime_type("application/pdf"));
    assert!(is_valid_mime_type("image/svg+xml"));
    assert!(is_valid_mime_type("application/vnd.ms-excel"));

    // RFC 2045 Section 5.1: token allows any ASCII char except SPACE, CTLs,
    // and tspecials. Underscore, bang, hash, etc. are valid token chars.
    assert!(
        is_valid_mime_type("application/x-my_type"),
        "underscore is a valid token char per RFC 2045 Section 5.1"
    );
    assert!(
        is_valid_mime_type("application/x-custom!type"),
        "bang is a valid token char per RFC 2045 Section 5.1"
    );

    // Invalid: tspecials in subtype (RFC 2045 Section 5.1)
    assert!(!is_valid_mime_type("text/plain; charset=utf-8"));
    assert!(!is_valid_mime_type("text/html@bad"));
    assert!(!is_valid_mime_type("text/html(bad)"));
}

#[test]
fn build_parameterized_mime_type_preserved() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "file.bin".into(),
        content_type: "application/pdf; extra=bad".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Type: application/pdf; extra=bad; name=\"file.bin\""),
        "valid Content-Type parameters must be preserved on attachment parts: {s}"
    );
    assert!(
        !s.contains("Content-Type: application/octet-stream"),
        "valid Content-Type parameters must not trigger octet-stream fallback: {s}"
    );
}

#[test]
fn build_invalid_parameterized_mime_fallback() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "file.bin".into(),
        content_type: "application/pdf; extra".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Type: application/octet-stream"),
        "malformed Content-Type parameters must still fall back safely: {s}"
    );
}

#[test]
fn build_display_name_with_comma_is_quoted() {
    // Display names with commas must be quoted (RFC 5322 Section 3.4)
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("Doe, John".into()),
        email: "john@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("From: \"Doe, John\" <john@example.com>"),
        "From header should quote display name with comma: {s}"
    );
}

#[test]
fn build_display_name_with_special_chars_is_quoted() {
    // Display names with RFC 5322 specials are quoted
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("O'Brien (test)".into()),
        email: "ob@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("\"O'Brien (test)\" <ob@example.com>"),
        "From header should quote display name with parens: {s}"
    );
}

#[test]
fn build_display_name_with_quotes_escaped() {
    // Double-quotes in display names must be backslash-escaped (RFC 5322 Section 3.2.4)
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("John \"Doc\" Doe".into()),
        email: "john@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("\"John \\\"Doc\\\" Doe\" <john@example.com>"),
        "From header should escape quotes in display name: {s}"
    );
}

#[test]
fn build_display_name_plain_not_quoted() {
    // Simple display names without specials should NOT be quoted
    let email = make_email();
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // "Sender" has no specials — should not be quoted
    assert!(
        s.contains("From: Sender <sender@example.com>"),
        "Simple display name should not be quoted: {s}"
    );
}

#[test]
fn build_round_trip_display_name_with_comma() {
    // Round-trip: build with comma in display name, parse it back
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("Doe, John".into()),
        email: "john@example.com".into(),
    }];
    email.body_text = Some("Body".into());

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(parsed.from[0].name.as_deref(), Some("Doe, John"));
    assert_eq!(parsed.from[0].email, "john@example.com");
}

#[test]
fn build_round_trip_display_name_with_escaped_quotes() {
    // Round-trip: build with quotes in display name, parse it back
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("John \"Doc\" Doe".into()),
        email: "john@example.com".into(),
    }];
    email.body_text = Some("Body".into());

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(parsed.from[0].name.as_deref(), Some("John \"Doc\" Doe"));
    assert_eq!(parsed.from[0].email, "john@example.com");
}

#[test]
fn build_attachment_filename_with_quotes_escaped() {
    // RFC 2183 Section 2 / RFC 5322 Section 3.2.4: quotes and backslashes
    // in filenames must be escaped within the quoted-string.
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "file\"name.pdf".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The quote inside the filename must be backslash-escaped
    assert!(
        s.contains(r#"filename="file\"name.pdf""#),
        "Filename with quote not properly escaped: {s}"
    );
}

#[test]
fn build_attachment_filename_with_backslash_escaped() {
    // RFC 5322 Section 3.2.4: backslash in quoted-string must be escaped
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "path\\file.pdf".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains(r#"filename="path\\file.pdf""#),
        "Filename with backslash not properly escaped: {s}"
    );
}

#[test]
fn build_long_subject_is_folded() {
    // RFC 5322 Section 2.2.3: folding is only permitted where FWS
    // appears in the grammar. A single 1000-char word has no internal
    // FWS, so it must be emitted as-is (possibly exceeding the 998-char
    // hard limit) rather than inserting spaces that would corrupt the
    // value. Receivers tolerate long lines per Postel's law
    // (RFC 1122 Section 1.2.2).
    let mut email = make_email();
    email.subject = "A".repeat(1000);

    let built = build_message(&email).unwrap();

    // The subject must round-trip without corruption.
    let parsed = crate::parse_email(&built.raw).unwrap();
    let parsed_subject = parsed.subject.unwrap();
    assert_eq!(
        parsed_subject, email.subject,
        "Single-word subject must round-trip without inserted spaces"
    );
}

#[test]
fn build_long_references_header_is_folded() {
    // Long References header with many message-ids
    let mut email = make_email();
    let ids: Vec<String> = (0..30)
        .map(|i| {
            mid(&format!(
                "id{i:04}@very-long-domain-name-for-testing.example.com"
            ))
        })
        .collect();
    email.references = ids;

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    for line in s.split("\r\n") {
        assert!(
            line.len() <= 998,
            "Line exceeds 998 chars ({} chars)",
            line.len()
        );
    }

    // The References header should still be parseable after folding
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(parsed.references.len(), 30);
}

// -----------------------------------------------------------------------
// UTF-8-safe long-subject encoding
// -----------------------------------------------------------------------

#[test]
fn build_force_fold_preserves_utf8_boundaries() {
    // A single word of 300 emoji (1200 bytes) exceeds the RFC 5322
    // Section 2.1.1 line limit, so the builder must switch to RFC 2047
    // encoded-words instead of splitting inside a UTF-8 code point.
    let mut email = make_email();
    // 300 emoji * 4 bytes = 1200 bytes.
    email.subject = "🌍".repeat(300);

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Every line must be valid UTF-8 on its own
    for (i, line) in s.split("\r\n").enumerate() {
        // Verify it's valid UTF-8 (raw_str already converted, but check
        // that no replacement characters were introduced by mid-char splits)
        assert!(
            !line.contains('\u{FFFD}'),
            "Line {i} contains UTF-8 replacement character from mid-char split: {line:?}"
        );
    }

    // The subject must round-trip exactly after RFC 2047 decoding.
    let parsed = crate::parse_email(&built.raw).unwrap();
    let parsed_subject = parsed.subject.unwrap();
    assert_eq!(
        parsed_subject, email.subject,
        "UTF-8 subject must round-trip exactly without inserted spaces"
    );
}

#[test]
fn split_header_words_handles_escaped_quotes() {
    // RFC 5322 Section 3.2.4: a backslash-escaped quote `\"` inside a
    // quoted-string must NOT toggle the in_quotes state. Without this
    // fix, `"A\" B" <a@b.com>` is split into `["\"A\\\"", "B\"",
    // "<a@b.com>"]` — breaking the quoted-string across words.
    let value = r#""A\" B" <a@b.com>"#;
    let words = split_header_words(value);
    // The entire display-name + angle-addr should produce exactly two
    // tokens: the quoted-string name and the angle-bracketed email.
    assert_eq!(
        words,
        (vec![(r#""A\" B""#, None), ("<a@b.com>", Some(" "))], None),
        "split_header_words must skip escaped quotes inside quoted-strings \
         per RFC 5322 Section 3.2.4"
    );
}

#[test]
fn spec_audit_split_header_words_backslash_multibyte_utf8() {
    // RFC 5322 Section 3.2.4: quoted-pair = "\" (VCHAR / WSP).
    // While the RFC only defines escaping for ASCII, user strings may
    // contain a backslash followed by a multi-byte UTF-8 character.
    // The old code did `i += 2` which only skips 2 bytes — but a 4-byte
    // emoji after the backslash means 3 bytes are left dangling, causing
    // byte-level misalignment and potential panics or incorrect splits.
    let value = r#""test\🌍 rest" after"#;
    let words = split_header_words(value);
    // The quoted string `"test\🌍 rest"` must stay as one token, and
    // `after` must be a separate token.
    assert_eq!(
        words,
        (
            vec![(r#""test\🌍 rest""#, None), ("after", Some(" "))],
            None
        ),
        "split_header_words must skip the full multi-byte UTF-8 character \
         after a backslash, not just 2 bytes (RFC 5322 Section 3.2.4)"
    );
}

#[test]
fn spec_audit_split_header_words_backslash_ascii_still_works() {
    // RFC 5322 Section 3.2.4: quoted-pair with ASCII character after
    // backslash — the normal case must continue to work after the fix.
    let value = r#""hello\" world" next"#;
    let words = split_header_words(value);
    assert_eq!(
        words,
        (
            vec![(r#""hello\" world""#, None), ("next", Some(" "))],
            None
        ),
        "split_header_words must handle backslash + ASCII in quoted-string \
         (RFC 5322 Section 3.2.4)"
    );
}

#[test]
fn spec_audit_split_header_words_backslash_2byte_utf8() {
    // RFC 5322 Section 3.2.4: backslash followed by a 2-byte UTF-8
    // character (e.g., U+00E9 'é' = 0xC3 0xA9). The old `i += 2` code
    // happens to work here by accident, but the fix should handle it
    // correctly via proper char-length detection.
    let value = "\"test\\é more\" end";
    let words = split_header_words(value);
    assert_eq!(
        words,
        (vec![("\"test\\é more\"", None), ("end", Some(" "))], None),
        "split_header_words must handle backslash + 2-byte UTF-8 char \
         (RFC 5322 Section 3.2.4)"
    );
}

#[test]
fn spec_audit_split_header_words_backslash_3byte_utf8() {
    // RFC 5322 Section 3.2.4: backslash followed by a 3-byte UTF-8
    // character (e.g., U+4E16 '世' = 0xE4 0xB8 0x96). The old `i += 2`
    // skips only 2 of 3 bytes, causing misalignment.
    let value = "\"test\\世 more\" end";
    let words = split_header_words(value);
    assert_eq!(
        words,
        (vec![("\"test\\世 more\"", None), ("end", Some(" "))], None),
        "split_header_words must handle backslash + 3-byte UTF-8 char \
         (RFC 5322 Section 3.2.4)"
    );
}

#[test]
fn build_crlf_in_display_name_stripped() {
    // CRLF in a display name must not inject headers
    // (RFC 5322 Section 2.1/2.2 — header injection prevention).
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("evil\r\nBcc: injected@evil.com".into()),
        email: "sender@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The CRLF must be stripped — no injected header line starting with "Bcc:"
    assert!(
        !s.contains("\r\nBcc:"),
        "CRLF in display name must not inject headers: {s}"
    );
    // The injected address must not appear in envelope recipients
    assert!(
        !built
            .envelope_recipients
            .contains(&"injected@evil.com".to_string()),
        "Injected address must not appear in envelope"
    );
}

#[test]
fn build_crlf_in_subject_stripped() {
    // CRLF in subject must not inject headers.
    let mut email = make_email();
    email.subject = "Test\r\nBcc: injected@evil.com".into();

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The CRLF must be stripped — no injected header line
    assert!(
        !s.contains("\r\nBcc:"),
        "CRLF in subject must not inject headers: {s}"
    );
}

#[test]
fn build_bare_lf_in_display_name_stripped() {
    // bare LF in a display name must not inject headers
    // (some servers treat bare LF as line ending).
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("evil\nBcc: injected@evil.com".into()),
        email: "sender@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // No bare-LF-injected header line
    assert!(
        !s.contains("\nBcc:"),
        "Bare LF in display name must not inject headers: {s}"
    );
}

#[test]
fn build_crlf_in_references_stripped() {
    // CRLF in references must not inject headers.
    let mut email = make_email();
    email.references = vec![mid("root@host.com\r\nBcc: injected@evil.com")];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // No CRLF-injected header line
    assert!(
        !s.contains("\r\nBcc:"),
        "CRLF in references must not inject headers: {s}"
    );
}

#[test]
fn build_round_trip_escaped_quote_name_long_header() {
    // Build a message with an escaped-quote display name long enough to
    // trigger header folding, then parse it back. The fold must not
    // split inside the quoted-string.
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("A\" B".into()),
        email: "user@very-long-domain-name-that-pushes-header-over-78-chars.example.com".into(),
    }];
    email.body_text = Some("Body".into());

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(
        parsed.from[0].name.as_deref(),
        Some("A\" B"),
        "Display name with escaped quote must survive folding round-trip"
    );
}

/// `normalize_line_endings` was processing bytes individually
/// with `bytes[i] as char`, which treats each byte of a multi-byte UTF-8
/// sequence as a separate Latin-1 character. This corrupts any non-ASCII
/// text in the email body (e.g., "é" → "é").
///
/// RFC 5322 Section 2.1 requires CRLF line endings, but the normalization
/// must preserve UTF-8 character integrity (RFC 6532). The builder now
/// uses quoted-printable for non-ASCII bodies, so we verify the original
/// text survives a build -> parse round-trip.
#[test]
fn build_non_ascii_body_preserved() {
    let mut email = make_email();
    let body = "Héllo, José! Ñoño. 日本語テスト";
    email.body_text = Some(body.into());

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_text.as_deref(),
        Some(body),
        "Non-ASCII UTF-8 body text must round-trip through QP encoding"
    );
}

/// Non-ASCII characters in HTML bodies must also survive
/// quoted-printable encoding without corruption.
#[test]
fn build_non_ascii_html_body_preserved() {
    let mut email = make_email();
    let html = "<p>Ünïcödé résumé</p>";
    email.body_html = Some(html.into());

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_html.as_deref(),
        Some(html),
        "Non-ASCII UTF-8 HTML body must round-trip through QP encoding"
    );
}

/// Non-ASCII in multipart text parts (text+html+attachments)
/// must survive quoted-printable encoding.
#[test]
fn build_non_ascii_multipart_body_preserved() {
    let mut email = make_email();
    let text = "Café";
    let html = "<b>Café</b>";
    email.body_text = Some(text.into());
    email.body_html = Some(html.into());
    email.attachments = vec![OutgoingAttachment {
        filename: "test.txt".into(),
        content_type: "text/plain".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_text.as_deref(),
        Some(text),
        "Non-ASCII in multipart text must round-trip through QP encoding"
    );
    assert_eq!(
        parsed.body_html.as_deref(),
        Some(html),
        "Non-ASCII in multipart HTML must round-trip through QP encoding"
    );
}

/// Non-ASCII Subject must be RFC 2047 encoded in the raw
/// message headers (RFC 5322 Section 2.2 — field bodies must be US-ASCII;
/// RFC 2047 provides the encoding mechanism for non-ASCII text).
/// The parser must decode it back to the original text.
#[test]
fn build_non_ascii_subject_rfc2047_round_trip() {
    let mut email = make_email();
    email.subject = "Héllo Wörld".into();

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Raw headers must NOT contain raw non-ASCII bytes — they must be
    // RFC 2047 encoded (RFC 5322 Section 2.2).
    let header_section = s.split("\r\n\r\n").next().unwrap();
    assert!(
        header_section.is_ascii(),
        "Headers must be pure ASCII per RFC 5322 Section 2.2, \
         but found non-ASCII in: {header_section}"
    );

    // The Subject header must contain RFC 2047 encoded word(s)
    assert!(
        s.contains("=?UTF-8?B?"),
        "Subject must be RFC 2047 B-encoded, got: {s}"
    );

    // Round-trip: parser must decode it back
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.subject.as_deref(),
        Some("Héllo Wörld"),
        "Subject must round-trip through RFC 2047 encoding"
    );
}

/// body text with lines exceeding 998 characters must use
/// `Content-Transfer-Encoding: quoted-printable` instead of `8bit` to
/// comply with RFC 2045 Section 2.8 and RFC 5322 Section 2.1.1.
#[test]
fn build_long_body_line_uses_quoted_printable() {
    let mut email = make_email();
    // Single line > 998 characters — violates RFC 5322 Section 2.1.1
    let long_line = "A".repeat(1200);
    email.body_text = Some(long_line.clone());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Must use quoted-printable, not 8bit
    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "Long body lines must trigger quoted-printable encoding \
         (RFC 2045 Section 2.8), but got:\n{s}"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: 8bit"),
        "8bit encoding must not be used when body has lines > 998 chars"
    );

    // No line in the output should exceed 998 characters
    for (i, line) in s.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "Line {i} exceeds 998 chars ({} chars): {}...",
            line.len(),
            &line[..80.min(line.len())]
        );
    }

    // Round-trip: parse the built message and verify body text matches
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_text.as_deref(),
        Some(long_line.as_str()),
        "Body text must round-trip through quoted-printable encoding"
    );
}

/// Verify that short pure-ASCII body lines use `7bit` encoding (no
/// unnecessary overhead from quoted-printable).
#[test]
fn build_normal_body_line_uses_7bit() {
    let mut email = make_email();
    email.body_text = Some("Short line, well under 998 chars.".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: 7bit"),
        "Short body lines should use 7bit encoding, got:\n{s}"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: quoted-printable"),
        "Short body lines should not use quoted-printable"
    );
}

/// A body line of exactly 998 characters is at the RFC 5322 Section 2.1.1
/// hard limit. Pure ASCII with lines <= 998 uses `7bit` CTE — no need for
/// quoted-printable overhead.
///
/// RFC 2045 Section 2.7, RFC 5322 Section 2.1.1
#[test]
fn build_body_line_exactly_998_chars_uses_7bit() {
    let mut email = make_email();
    // Exactly 998 characters — right at the HARD_LINE_LIMIT boundary
    let boundary_line = "B".repeat(998);
    email.body_text = Some(boundary_line.clone());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: 7bit"),
        "A 998-char pure ASCII line is within the RFC 5322 Section 2.1.1 limit \
         and must use 7bit encoding, got:\n{s}"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: quoted-printable"),
        "A 998-char line must not trigger quoted-printable encoding"
    );

    // No output line should exceed 998 characters
    for (i, line) in s.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "Line {i} exceeds 998 chars ({} chars): {}...",
            line.len(),
            &line[..80.min(line.len())]
        );
    }

    // Round-trip: parse and verify body text preserved
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_text.as_deref(),
        Some(boundary_line.as_str()),
        "Body text must round-trip through 7bit encoding"
    );
}

/// A body line of exactly 999 characters exceeds the RFC 5322 Section 2.1.1
/// hard limit of 998 and must use `Content-Transfer-Encoding: quoted-printable`
/// to ensure all output lines comply with RFC 2045 Section 2.8.
#[test]
fn build_body_line_exactly_999_chars_uses_quoted_printable() {
    let mut email = make_email();
    // 999 characters — one past the HARD_LINE_LIMIT boundary
    let over_line = "C".repeat(999);
    email.body_text = Some(over_line.clone());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Must use quoted-printable, not 8bit
    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "A 999-char line exceeds the RFC 5322 Section 2.1.1 limit \
         and must trigger quoted-printable encoding, got:\n{s}"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: 8bit"),
        "8bit encoding must not be used when a body line exceeds 998 chars"
    );

    // No output line should exceed 998 characters
    for (i, line) in s.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "Line {i} exceeds 998 chars ({} chars): {}...",
            line.len(),
            &line[..80.min(line.len())]
        );
    }

    // Round-trip: parse and verify body text preserved
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_text.as_deref(),
        Some(over_line.as_str()),
        "Body text must round-trip through quoted-printable encoding"
    );
}

/// `generate_boundary_not_in` must return a boundary that does
/// not appear in the supplied content. RFC 2046 Section 5.1.1 says:
/// "The boundary delimiter MUST NOT appear within the encapsulated material."
#[test]
fn generate_boundary_not_in_avoids_collision() {
    // Generate a boundary and embed it in "content"
    let first = generate_boundary();
    let content = format!("Some text before\r\n--{first}\r\nSome text after");

    // generate_boundary_not_in must return a boundary different from `first`
    let second = generate_boundary_not_in(content.as_bytes());
    assert_ne!(
        first, second,
        "generate_boundary_not_in must produce a boundary that \
         differs from one already present in the content"
    );
    // The returned boundary must NOT appear anywhere in the content
    assert!(
        !content.contains(&second),
        "Returned boundary must not appear in the content, but \
         found '{second}' in '{content}'"
    );
}

/// the builder must generate boundaries that do not collide
/// with body text. Verifies that a multipart message whose body text
/// contains the boundary prefix `----=_Part_` round-trips correctly.
///
/// RFC 2046 Section 5.1.1
#[test]
fn build_boundary_not_in_body() {
    let mut email = make_email();
    // Body text intentionally contains the boundary prefix used by
    // generate_boundary(). The full boundary (with 32 random hex chars)
    // must not collide.
    email.body_text =
        Some("Line 1\r\n----=_Part_00000000000000000000000000000000\r\nLine 2".into());
    email.body_html = Some("<p>HTML body</p>".into());

    let built = build_message(&email).unwrap();

    // Parse the built message back
    let parsed = crate::parse_email(&built.raw).unwrap();

    // The body text must round-trip exactly
    assert_eq!(
        parsed.body_text.as_deref(),
        Some("Line 1\r\n----=_Part_00000000000000000000000000000000\r\nLine 2"),
        "Body text containing boundary prefix must round-trip correctly"
    );
    assert_eq!(
        parsed.body_html.as_deref(),
        Some("<p>HTML body</p>"),
        "HTML body must round-trip correctly"
    );
}

/// RFC 2046 Section 5.1.1: boundary parameter values for nested multipart
/// levels within the same message MUST be distinct. When building a
/// text+html+attachments message, the outer multipart/mixed and inner
/// multipart/alternative boundaries must differ.
#[test]
fn build_nested_multipart_boundaries_are_distinct() {
    let mut email = make_email();
    email.body_text = Some("Plain text".into());
    email.body_html = Some("<p>HTML</p>".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "data.bin".into(),
        content_type: "application/octet-stream".into(),
        data: vec![1, 2, 3],
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Extract all boundary values — search the raw string for boundary=
    // patterns since Content-Type headers may be folded across lines.
    let mut boundaries: Vec<String> = Vec::new();
    let lower = s.to_lowercase();
    let mut search_from = 0;
    while let Some(pos) = lower[search_from..].find("boundary=\"") {
        let abs = search_from + pos;
        let rest = &s[abs + 10..]; // skip 'boundary="'
        let end = rest.find('"').unwrap_or(rest.len());
        boundaries.push(rest[..end].to_string());
        search_from = abs + 10 + end;
    }

    assert_eq!(
        boundaries.len(),
        2,
        "Expected 2 boundary values (mixed + alternative), got {boundaries:?}"
    );
    assert_ne!(
        boundaries[0], boundaries[1],
        "Nested multipart boundaries must be distinct per RFC 2046 Section 5.1.1"
    );
}

/// attachment filenames containing CRLF must not inject
/// arbitrary headers into the built message. RFC 5322 Section 2.1
/// defines header fields as terminated by CRLF, so bare CRLF in
/// user-provided values is a header injection vector.
#[test]
fn build_attachment_filename_crlf_sanitized() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "evil\r\nBcc: attacker@evil.com\r\nX-Injected: yes".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The injected Bcc header must NOT appear as a real header
    assert!(
        !s.contains("\r\nBcc: attacker@evil.com"),
        "CRLF in filename must be stripped to prevent header injection \
         (RFC 5322 Section 2.1)"
    );
    assert!(
        !s.contains("\r\nX-Injected:"),
        "CRLF in filename must be stripped to prevent header injection"
    );
    // The filename should still be present (minus the CRLF)
    assert!(
        s.contains("Content-Disposition: attachment"),
        "Content-Disposition header must still be present"
    );
}

/// non-ASCII attachment filenames with CRLF must also be
/// sanitized. The RFC 2231 encoding path percent-encodes CRLF in the
/// `filename*` parameter, but the legacy `filename` fallback must
/// also be safe.
#[test]
fn build_non_ascii_attachment_filename_crlf_sanitized() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "résumé\r\nBcc: attacker@evil.com".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The injected Bcc header must NOT appear as a real header
    assert!(
        !s.contains("\r\nBcc: attacker@evil.com"),
        "CRLF in non-ASCII filename must be stripped to prevent header injection"
    );
}

#[test]
fn build_attachment_filename_with_backslash_and_quote_escaped() {
    // Both backslash and double-quote in the same filename must be escaped
    // independently. Order matters: backslash first, then quote
    // (RFC 5322 Section 3.2.4).
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "path\\file\"name.pdf".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains(r#"filename="path\\file\"name.pdf""#),
        "Filename with both backslash and quote not properly escaped: {s}"
    );
}

#[test]
fn build_display_name_with_backslash_escaped() {
    // Backslash in a display name must be escaped in the quoted-string
    // (RFC 5322 Section 3.2.4).
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("Back\\Slash".into()),
        email: "bs@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains(r#""Back\\Slash" <bs@example.com>"#),
        "Display name with backslash not properly escaped: {s}"
    );
}

#[test]
fn build_then_parse_filename_with_backslash_and_quote_round_trip() {
    // Round-trip: filename with both backslash and double-quote must survive
    // build → parse without corruption (RFC 5322 Section 3.2.4).
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "path\\file\"name.pdf".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(parsed.attachments.len(), 1);
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some("path\\file\"name.pdf"),
        "Round-trip filename with backslash and quote must be preserved"
    );
}

// -----------------------------------------------------------------------
// Coverage: generate_boundary_not_in fallback path (L529, L534-535, L538)
// -----------------------------------------------------------------------

/// `generate_boundary_not_in` falls back to a counter-based boundary
/// when all random attempts collide with content. This is astronomically
/// unlikely in production (32 hex chars of randomness), but the fallback
/// path must work correctly.
///
/// We cannot easily force the random generator to collide, so we test
/// the fallback indirectly by verifying that the function always returns
/// a boundary not present in the content, even when the content contains
/// the boundary prefix.
///
/// RFC 2046 Section 5.1.1
#[test]
fn generate_boundary_not_in_with_prefix_in_content() {
    // Content that contains many boundary-like strings. The function
    // should still return a boundary that does NOT collide.
    let mut content = String::new();
    for i in 0..20 {
        use std::fmt::Write;
        let _ = write!(content, "----=_Part_{i:032x}\r\n");
    }
    let boundary = generate_boundary_not_in(content.as_bytes());
    assert!(
        !content.contains(&boundary),
        "Returned boundary must not appear in content containing \
         many boundary-like strings (RFC 2046 Section 5.1.1)"
    );
}

// -----------------------------------------------------------------------
// Coverage: generate_message_id (L573, L577-583)
// -----------------------------------------------------------------------

/// `generate_message_id` produces a string in `{hex}@{domain}` format
/// per RFC 5322 Section 3.6.4. Verify format and uniqueness.
#[test]
fn generate_message_id_format_and_uniqueness() {
    let id1 = generate_message_id("example.com");
    let id2 = generate_message_id("example.com");

    // Each ID must contain exactly one '@'
    assert_eq!(
        id1.matches('@').count(),
        1,
        "Message-ID must contain exactly one '@' (RFC 5322 Section 3.6.4)"
    );
    // Domain must match
    assert!(
        id1.ends_with("@example.com"),
        "Message-ID must end with @domain: {id1}"
    );
    // Two consecutive IDs must differ (crypto-random)
    assert_ne!(
        id1, id2,
        "Message-IDs must be unique (RFC 5322 Section 3.6.4)"
    );
    // The local part (before @) must be 32 hex chars
    let local = id1.split('@').next().unwrap();
    assert_eq!(local.len(), 32, "Local part must be 32 hex chars: {local}");
    assert!(
        local.chars().all(|c| c.is_ascii_hexdigit()),
        "Local part must be hex digits: {local}"
    );
}

// -----------------------------------------------------------------------
// Coverage: quoted-printable encoding (L746-784)
// -----------------------------------------------------------------------

/// CRLF passthrough in quoted-printable encoding (Rule #4):
/// CRLF sequences must pass through unchanged as hard line breaks.
///
/// RFC 2045 Section 6.7 Rule #4
#[test]
fn qp_crlf_passthrough() {
    let input = b"Line one\r\nLine two\r\n";
    let encoded = encode_quoted_printable(input);
    assert_eq!(
        encoded, b"Line one\r\nLine two\r\n",
        "CRLF must pass through unchanged in QP encoding \
         (RFC 2045 Section 6.7 Rule #4)"
    );
}

/// Trailing whitespace before CRLF must be encoded in QP (Rule #3).
/// Space and TAB at end of a line must become =20 and =09.
///
/// RFC 2045 Section 6.7 Rule #3
#[test]
fn qp_trailing_whitespace_encoded() {
    // Space before CRLF
    let input = b"trailing space \r\nnext line";
    let encoded = encode_quoted_printable(input);
    let encoded_str = String::from_utf8_lossy(&encoded);
    assert!(
        encoded_str.contains("trailing space=20\r\n"),
        "Trailing space before CRLF must be encoded as =20 \
         (RFC 2045 Section 6.7 Rule #3), got: {encoded_str}"
    );

    // TAB before CRLF
    let input_tab = b"trailing tab\t\r\nnext line";
    let encoded_tab = encode_quoted_printable(input_tab);
    let encoded_tab_str = String::from_utf8_lossy(&encoded_tab);
    assert!(
        encoded_tab_str.contains("trailing tab=09\r\n"),
        "Trailing TAB before CRLF must be encoded as =09 \
         (RFC 2045 Section 6.7 Rule #3), got: {encoded_tab_str}"
    );
}

/// Trailing whitespace at end of data (no CRLF following) must also
/// be encoded (RFC 2045 Section 6.7 Rule #3).
#[test]
fn qp_trailing_whitespace_at_eof_encoded() {
    let input = b"end with space ";
    let encoded = encode_quoted_printable(input);
    let encoded_str = String::from_utf8_lossy(&encoded);
    assert!(
        encoded_str.ends_with("=20"),
        "Trailing space at EOF must be encoded as =20 \
         (RFC 2045 Section 6.7 Rule #3), got: {encoded_str}"
    );
}

/// Non-trailing whitespace (space/TAB followed by non-whitespace before
/// next CRLF) should pass through unchanged (RFC 2045 Section 6.7 Rule #2).
#[test]
fn qp_non_trailing_whitespace_passthrough() {
    let input = b"hello world";
    let encoded = encode_quoted_printable(input);
    assert_eq!(
        encoded, b"hello world",
        "Non-trailing space must pass through unchanged \
         (RFC 2045 Section 6.7 Rule #2)"
    );
}

/// The `=` character must always be encoded as `=3D` in QP
/// (RFC 2045 Section 6.7 Rule #1).
#[test]
fn qp_equals_sign_encoded() {
    let input = b"a=b";
    let encoded = encode_quoted_printable(input);
    assert_eq!(
        encoded, b"a=3Db",
        "`=` must be encoded as =3D (RFC 2045 Section 6.7 Rule #1)"
    );
}

/// Non-printable bytes must be encoded as `=XX` with uppercase hex
/// (RFC 2045 Section 6.7 Rule #1).
#[test]
fn qp_non_printable_bytes_encoded() {
    // NUL byte
    let input = &[0x00u8];
    let encoded = encode_quoted_printable(input);
    assert_eq!(
        encoded, b"=00",
        "NUL byte must be encoded as =00 (RFC 2045 Section 6.7 Rule #1)"
    );

    // High byte (0xFF)
    let input_hi = &[0xFFu8];
    let encoded_hi = encode_quoted_printable(input_hi);
    assert_eq!(
        encoded_hi, b"=FF",
        "0xFF must be encoded as =FF (RFC 2045 Section 6.7 Rule #1)"
    );

    // DEL (0x7F)
    let input_del = &[0x7Fu8];
    let encoded_del = encode_quoted_printable(input_del);
    assert_eq!(
        encoded_del, b"=7F",
        "DEL must be encoded as =7F (RFC 2045 Section 6.7 Rule #1)"
    );
}

/// Lines in QP encoding must not exceed 76 characters. When encoding
/// bytes that push past the limit, a soft line break (`=\r\n`) must
/// be inserted (RFC 2045 Section 6.7 Rule #5).
#[test]
fn qp_soft_line_break_on_long_encoded_data() {
    // 100 bytes of 0xFF → each becomes =FF (3 chars). 100 * 3 = 300 chars.
    // Should be split across multiple lines of ≤76 chars each.
    let input: Vec<u8> = vec![0xFF; 100];
    let encoded = encode_quoted_printable(&input);
    let encoded_str = String::from_utf8_lossy(&encoded);
    for line in encoded_str.split("\r\n") {
        assert!(
            line.len() <= 76,
            "QP line exceeds 76-char limit ({} chars): {line} \
             (RFC 2045 Section 6.7 Rule #5)",
            line.len()
        );
    }
    // Verify content round-trips: count the =FF occurrences
    let ff_count = encoded_str.matches("=FF").count();
    assert_eq!(
        ff_count, 100,
        "All 100 bytes must be encoded as =FF, got {ff_count}"
    );
}

/// Soft line breaks for literal (non-encoded) characters that would
/// push past the 76-char line limit (RFC 2045 Section 6.7 Rule #5).
#[test]
fn qp_soft_line_break_on_long_literal_data() {
    // 200 'A' characters on one line — all printable, pass through as-is,
    // but must be wrapped with soft breaks at 76-char boundaries.
    let input: Vec<u8> = vec![b'A'; 200];
    let encoded = encode_quoted_printable(&input);
    let encoded_str = String::from_utf8_lossy(&encoded);
    for line in encoded_str.split("\r\n") {
        assert!(
            line.len() <= 76,
            "QP line exceeds 76-char limit ({} chars): {line}",
            line.len()
        );
    }
    // Verify all 'A' characters are preserved (soft breaks stripped)
    let reassembled: String = encoded_str.replace("=\r\n", "");
    let a_count = reassembled.chars().filter(|&c| c == 'A').count();
    assert_eq!(a_count, 200, "All 200 'A' chars must be preserved");
}

/// Mixed content: printable ASCII, CRLF, trailing whitespace, and
/// non-printable bytes in a single QP encoding pass.
#[test]
fn qp_mixed_content_round_trip() {
    let mut email = make_email();
    // Body with a very long line (>998 chars) that includes special chars
    let mut long_line = String::new();
    long_line.push_str("Start ");
    for _ in 0..200 {
        long_line.push_str("abcde");
    }
    long_line.push_str(" \t end"); // trailing whitespace
    long_line.push_str("\r\n");
    long_line.push_str("Line with = sign and \x01 control char\r\n");
    email.body_text = Some(long_line.clone());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Must use quoted-printable due to the long line
    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "Long body line must trigger QP encoding (RFC 2045 Section 2.8)"
    );

    // No line in the output should exceed 998 characters
    for (i, line) in s.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "Line {i} exceeds 998 chars ({} chars)",
            line.len()
        );
    }
}

// -----------------------------------------------------------------------
// Coverage: is_trailing_whitespace helper (L810-821)
// -----------------------------------------------------------------------

/// `is_trailing_whitespace` returns `true` when whitespace is followed
/// only by more whitespace before CRLF.
///
/// RFC 2045 Section 6.7 Rule #3
#[test]
fn is_trailing_whitespace_before_crlf() {
    // Space followed by CRLF
    let data = b"abc \r\n";
    assert!(
        is_trailing_whitespace(data, 3),
        "Space directly before CRLF is trailing"
    );

    // Space followed by more spaces then CRLF
    let data2 = b"abc   \r\n";
    assert!(
        is_trailing_whitespace(data2, 3),
        "Space followed by spaces before CRLF is trailing"
    );

    // TAB followed by CRLF
    let data3 = b"abc\t\r\n";
    assert!(
        is_trailing_whitespace(data3, 3),
        "TAB directly before CRLF is trailing"
    );
}

/// `is_trailing_whitespace` returns `true` when whitespace is at
/// end of data (no CRLF following).
///
/// RFC 2045 Section 6.7 Rule #3
#[test]
fn is_trailing_whitespace_at_eof() {
    let data = b"abc ";
    assert!(
        is_trailing_whitespace(data, 3),
        "Space at end of data is trailing"
    );

    let data2 = b"abc\t";
    assert!(
        is_trailing_whitespace(data2, 3),
        "TAB at end of data is trailing"
    );
}

/// `is_trailing_whitespace` returns `false` when whitespace is
/// followed by non-whitespace before the next CRLF.
///
/// RFC 2045 Section 6.7 Rule #3
#[test]
fn is_trailing_whitespace_not_trailing() {
    let data = b"abc def";
    assert!(
        !is_trailing_whitespace(data, 3),
        "Space followed by non-whitespace is NOT trailing"
    );

    // TAB followed by text
    let data2 = b"abc\tdef";
    assert!(
        !is_trailing_whitespace(data2, 3),
        "TAB followed by non-whitespace is NOT trailing"
    );
}

// -----------------------------------------------------------------------
// Coverage: utf8_char_len (L1025-1035)
// -----------------------------------------------------------------------

/// `utf8_char_len` returns the expected byte length for each class
/// of UTF-8 lead byte.
#[test]
fn utf8_char_len_all_classes() {
    // ASCII (0x00..0x7F) → 1 byte
    assert_eq!(utf8_char_len(b'A'), 1, "ASCII 'A' is 1 byte");
    assert_eq!(utf8_char_len(0x00), 1, "NUL is 1 byte");
    assert_eq!(utf8_char_len(0x7F), 1, "DEL is 1 byte");

    // 2-byte lead (0x80..0xDF) → 2 bytes
    // 'é' = 0xC3 0xA9
    assert_eq!(utf8_char_len(0xC3), 2, "0xC3 (é lead) is 2-byte char");
    assert_eq!(utf8_char_len(0xC0), 2, "0xC0 is 2-byte lead");
    assert_eq!(utf8_char_len(0xDF), 2, "0xDF is 2-byte lead");

    // 3-byte lead (0xE0..0xEF) → 3 bytes
    // '你' = 0xE4 0xBD 0xA0
    assert_eq!(utf8_char_len(0xE4), 3, "0xE4 (CJK lead) is 3-byte char");
    assert_eq!(utf8_char_len(0xE0), 3, "0xE0 is 3-byte lead");
    assert_eq!(utf8_char_len(0xEF), 3, "0xEF is 3-byte lead");

    // 4-byte lead (0xF0..0xFF) → 4 bytes
    // '🌍' = 0xF0 0x9F 0x8C 0x8D
    assert_eq!(utf8_char_len(0xF0), 4, "0xF0 (emoji lead) is 4-byte char");
    assert_eq!(utf8_char_len(0xF4), 4, "0xF4 is 4-byte lead");
    assert_eq!(utf8_char_len(0xFF), 4, "0xFF is 4-byte lead");
}

// -----------------------------------------------------------------------
// Coverage: snap_utf8_chunk_end for multi-byte characters (L1010-1011)
// -----------------------------------------------------------------------

/// `snap_utf8_chunk_end` must not split multi-byte UTF-8 characters.
/// When the budget is too small for even one complete character, it
/// must advance past the full character to avoid an infinite loop.
#[test]
fn snap_utf8_chunk_end_undersized_budget() {
    // '🌍' is 4 bytes (0xF0 0x9F 0x8C 0x8D). If max_bytes is 1-3,
    // the function cannot fit any character, so it must advance past
    // the entire 4-byte sequence to avoid an infinite loop.
    let emoji = "🌍".as_bytes();
    assert_eq!(emoji.len(), 4);

    // Budget of 1 byte — can't fit the 4-byte char, must advance past it
    let end = snap_utf8_chunk_end(emoji, 0, 1);
    assert_eq!(end, 4, "Budget too small for one char must advance past it");

    // Budget of 2 bytes — still can't fit
    let end = snap_utf8_chunk_end(emoji, 0, 2);
    assert_eq!(end, 4);

    // Budget of 3 bytes — still can't fit
    let end = snap_utf8_chunk_end(emoji, 0, 3);
    assert_eq!(end, 4);

    // Budget of 4 bytes — exactly fits
    let end = snap_utf8_chunk_end(emoji, 0, 4);
    assert_eq!(end, 4);

    // 3-byte char '你' (0xE4 0xBD 0xA0) with budget of 2
    let cjk = "".as_bytes();
    assert_eq!(cjk.len(), 3);
    let end = snap_utf8_chunk_end(cjk, 0, 2);
    assert_eq!(
        end, 3,
        "Budget of 2 can't fit 3-byte char, must advance past it"
    );

    // 2-byte char 'é' (0xC3 0xA9) with budget of 1
    let accent = "é".as_bytes();
    assert_eq!(accent.len(), 2);
    let end = snap_utf8_chunk_end(accent, 0, 1);
    assert_eq!(
        end, 2,
        "Budget of 1 can't fit 2-byte char, must advance past it"
    );
}

/// `snap_utf8_chunk_end` correctly snaps back to character boundaries
/// when the budget lands in the middle of a multi-byte sequence.
#[test]
fn snap_utf8_chunk_end_snaps_to_boundary() {
    // "Aé" = [0x41, 0xC3, 0xA9] — 'A' (1 byte) + 'é' (2 bytes)
    let data = "".as_bytes();
    assert_eq!(data.len(), 3);

    // Budget of 2: lands at byte 2 (0xA9, continuation byte of 'é').
    // Must snap back to byte 1 (start of 'é'), so chunk is just 'A'.
    let end = snap_utf8_chunk_end(data, 0, 2);
    assert_eq!(
        end, 1,
        "Must snap back to char boundary, excluding incomplete 'é'"
    );

    // Budget of 3: exactly fits both characters
    let end = snap_utf8_chunk_end(data, 0, 3);
    assert_eq!(end, 3, "Budget of 3 fits both 'A' and 'é'");
}

// -----------------------------------------------------------------------
// Coverage: very long single-word subjects
// -----------------------------------------------------------------------

/// A subject consisting of a single very long word (no spaces) must
/// still round-trip without inserted spaces. The builder satisfies RFC
/// 5322 Section 2.1.1 by switching unstructured long words onto RFC 2047
/// encoded-words instead of emitting an overlong line.
#[test]
fn build_very_long_single_word_subject_preserved() {
    let mut email = make_email();
    // 1100 ASCII chars with no spaces — too long for a single unfolded
    // header line, so the builder must encode rather than split it.
    email.subject = "X".repeat(1100);

    let built = build_message(&email).unwrap();

    // The subject must round-trip without corruption.
    let parsed = crate::parse_email(&built.raw).unwrap();
    let parsed_subject = parsed.subject.unwrap();
    assert_eq!(
        parsed_subject, email.subject,
        "Single-word subject must round-trip without inserted spaces"
    );
}

/// A very long address list should be folded at word boundaries
/// per RFC 5322 Section 2.2.3. Lines should stay under 78 chars
/// where possible (SHOULD limit) and never exceed 998 (MUST limit).
#[test]
fn build_very_long_address_list_folded() {
    let mut email = make_email();
    // 20 recipients with long addresses — the To header will be very long
    email.to = (0..20)
        .map(|i| Address {
            name: Some(format!("User Number {i:03}")),
            email: format!("user{i:03}@very-long-domain-name.example.com"),
        })
        .collect();

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    for (i, line) in s.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "Line {i} exceeds 998-char hard limit ({} chars) in long address list",
            line.len()
        );
    }

    // Verify all recipients made it into the envelope
    assert_eq!(built.envelope_recipients.len(), 20);
}

/// An encoded-word subject (RFC 2047) that is very long should be
/// folded correctly. Each `=?UTF-8?B?...?=` word is separated by
/// a space, and `write_header` should fold at those spaces.
///
/// RFC 2047 Section 2, RFC 5322 Section 2.2.3
#[test]
fn build_long_rfc2047_subject_folded() {
    let mut email = make_email();
    // Long non-ASCII subject — will be split into multiple encoded words,
    // and the header should be folded at encoded-word boundaries.
    email.subject = "日本語テスト ".repeat(50);

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    for (i, line) in s.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "Line {i} exceeds 998-char limit for RFC 2047 subject ({} chars)",
            line.len()
        );
    }

    // Verify the subject round-trips
    let parsed = crate::parse_email(&built.raw).unwrap();
    let original = email.subject.trim();
    let parsed_subject = parsed.subject.unwrap();
    assert_eq!(
        parsed_subject.trim(),
        original,
        "Long RFC 2047 subject must round-trip"
    );
}

/// RFC 2047 Section 2: "each line of a header field that contains one
/// or more 'encoded-word's is limited to 76 characters." The builder
/// must fold encoded-word headers at 76 chars, not the usual 78.
#[test]
fn rfc2047_encoded_word_lines_must_not_exceed_76_chars() {
    // Subject with non-ASCII forces RFC 2047 encoding.
    let mut email = make_email();
    email.subject = "日本語テスト ".repeat(30);

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Check every line that contains an encoded-word.
    for (i, line) in s.split("\r\n").enumerate() {
        if line.contains("=?") && line.contains("?=") {
            assert!(
                line.len() <= 76,
                "RFC 2047 Section 2: line {i} with encoded-word exceeds \
                 76 chars ({} chars): {line}",
                line.len()
            );
        }
    }

    // Round-trip the subject to ensure folding doesn't corrupt it.
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.subject.unwrap().trim(),
        email.subject.trim(),
        "Subject must survive RFC 2047 encode → fold → decode round-trip"
    );
}

/// RFC 2047 Section 2: encoded-word line limit also applies to
/// address headers with non-ASCII display names. "Reply-To: " is
/// 10 chars, so even a single encoded-word can push past 76.
#[test]
fn rfc2047_encoded_word_address_lines_must_not_exceed_76_chars() {
    let mut email = make_email();
    email.reply_to = vec![Address {
        name: Some("日本太郎さんの長い名前テスト用の表示名".into()),
        email: "taro@example.com".into(),
    }];
    email.body_text = Some("test".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    for (i, line) in s.split("\r\n").enumerate() {
        if line.contains("=?") && line.contains("?=") {
            assert!(
                line.len() <= 76,
                "RFC 2047 Section 2: line {i} with encoded-word exceeds \
                 76 chars ({} chars): {line}",
                line.len()
            );
        }
    }
}

// -----------------------------------------------------------------------
// Coverage: encode_rfc2047_if_needed with multi-byte characters
// -----------------------------------------------------------------------

/// `encode_rfc2047_if_needed` must handle 2-byte, 3-byte, and 4-byte
/// UTF-8 characters correctly, splitting at character boundaries when
/// the encoded-word exceeds 75 chars (RFC 2047 Section 2).
#[test]
fn encode_rfc2047_multibyte_chars() {
    // 2-byte characters: 'é' (U+00E9)
    let two_byte = "é".repeat(100);
    let encoded = encode_rfc2047_if_needed(&two_byte);
    assert!(
        encoded.contains("=?UTF-8?B?"),
        "Non-ASCII text must be RFC 2047 encoded"
    );
    // Each encoded word must be ≤75 chars (RFC 2047 Section 2)
    for word in encoded.split(' ') {
        if word.starts_with("=?") {
            assert!(
                word.len() <= 75,
                "Encoded word exceeds 75 chars ({} chars): {word}",
                word.len()
            );
        }
    }

    // 3-byte characters: '日' (U+65E5)
    let three_byte = "".repeat(100);
    let encoded = encode_rfc2047_if_needed(&three_byte);
    for word in encoded.split(' ') {
        if word.starts_with("=?") {
            assert!(
                word.len() <= 75,
                "3-byte char encoded word exceeds 75 chars ({} chars): {word}",
                word.len()
            );
        }
    }

    // 4-byte characters: '🌍' (U+1F30D)
    let four_byte = "🌍".repeat(100);
    let encoded = encode_rfc2047_if_needed(&four_byte);
    for word in encoded.split(' ') {
        if word.starts_with("=?") {
            assert!(
                word.len() <= 75,
                "4-byte char encoded word exceeds 75 chars ({} chars): {word}",
                word.len()
            );
        }
    }

    // Pure ASCII should pass through unchanged
    let ascii = "Hello World";
    assert_eq!(
        encode_rfc2047_if_needed(ascii),
        "Hello World",
        "Pure ASCII must not be encoded (RFC 2047 Section 5)"
    );
}

// -----------------------------------------------------------------------
// Coverage: body with QP encoding and CRLF, trailing whitespace
// integrated through build_message
// -----------------------------------------------------------------------

/// Full integration test: body text with lines >998 chars that also
/// contains CRLF sequences, trailing whitespace, and special chars.
/// Exercises the QP encoder's CRLF passthrough (L746-749), trailing
/// whitespace detection (L758), and hex encoding paths (L773-784).
///
/// RFC 2045 Section 6.7
#[test]
fn build_qp_body_with_crlf_and_trailing_whitespace() {
    let mut email = make_email();
    // Build a body that triggers QP encoding (>998 chars on one line)
    // and includes CRLF, trailing whitespace, and special chars.
    let mut body = String::new();
    // Very long first line to trigger QP
    body.push_str(&"B".repeat(1100));
    body.push_str("\r\n");
    // Line with trailing space before CRLF
    body.push_str("trailing space \r\n");
    // Line with trailing tab before CRLF
    body.push_str("trailing tab\t\r\n");
    // Line with = sign
    body.push_str("equals = sign\r\n");
    // Line with non-ASCII
    body.push_str("café résumé\r\n");
    email.body_text = Some(body);

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "Must use QP encoding for body with >998-char lines"
    );

    // No line should exceed 998 chars
    for (i, line) in s.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "Line {i} exceeds 998-char limit ({} chars)",
            line.len()
        );
    }
}

/// HTML body with lines >998 chars must also use quoted-printable.
///
/// RFC 2045 Section 2.8
#[test]
fn build_long_html_body_uses_quoted_printable() {
    let mut email = make_email();
    // Single long HTML line
    let long_html = format!("<p>{}</p>", "x".repeat(1100));
    email.body_html = Some(long_html);

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "Long HTML body lines must trigger QP encoding"
    );

    for (i, line) in s.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "HTML QP line {i} exceeds 998-char limit ({} chars)",
            line.len()
        );
    }
}

/// Multipart message (text + html + attachments) where both text parts
/// have long lines must use quoted-printable for both.
///
/// RFC 2045 Section 2.8, RFC 2046 Section 5.1.4
#[test]
fn build_multipart_with_long_lines_uses_qp() {
    let mut email = make_email();
    email.body_text = Some("T".repeat(1100));
    email.body_html = Some("H".repeat(1100));
    email.attachments = vec![OutgoingAttachment {
        filename: "file.bin".into(),
        content_type: "application/octet-stream".into(),
        data: vec![1, 2, 3],
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Count QP headers — should have 2 (one for text, one for html)
    let qp_count = s
        .matches("Content-Transfer-Encoding: quoted-printable")
        .count();
    assert_eq!(
        qp_count, 2,
        "Both text and HTML parts with long lines must use QP, got {qp_count}"
    );

    for (i, line) in s.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "Multipart QP line {i} exceeds 998-char limit ({} chars)",
            line.len()
        );
    }
}

/// Pure ASCII short lines uses `7bit` CTE
/// (RFC 2045 Section 2.7) — no need for quoted-printable overhead.
///
/// RFC 5321 Section 2.3.1: 7-bit US-ASCII is the baseline.
#[test]
fn build_seven_bit_ascii_uses_7bit_cte() {
    let mut email = make_email();
    email.body_text = Some("Short ASCII line".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: 7bit"),
        "SevenBit with pure ASCII must use 7bit CTE, got:\n{s}"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: 8bit"),
        "SevenBit must not produce 8bit encoding"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: quoted-printable"),
        "SevenBit with pure ASCII should not use quoted-printable"
    );
}

/// Non-ASCII body must produce QP-encoded content that round-trips
/// through `parse_email`.
///
/// RFC 2045 Section 6.7: quoted-printable encodes non-ASCII octets as
/// `=XX` so the transfer is 7-bit safe.
#[test]
fn build_seven_bit_encodes_non_ascii_body_round_trips() {
    let mut email = make_email();
    let body = "Héllo, José! 日本語テスト";
    email.body_text = Some(body.into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "SevenBit must use quoted-printable for non-ASCII body"
    );

    // All raw bytes after the CTE header must be 7-bit safe. We search
    // for the CTE header rather than the first \r\n\r\n separator so this
    // works correctly for multipart messages where the outer headers'
    // blank line precedes the first boundary, not the actual body content.
    let raw = &built.raw;
    let cte_needle = b"Content-Transfer-Encoding: quoted-printable\r\n\r\n";
    let body_start = raw
        .windows(cte_needle.len())
        .position(|w| w == cte_needle.as_slice())
        .expect("must contain CTE: quoted-printable header")
        + cte_needle.len();
    for (i, &byte) in raw[body_start..].iter().enumerate() {
        assert!(
            byte <= 127,
            "SevenBit body byte at offset {i} is non-ASCII: 0x{byte:02x}"
        );
    }

    // Round-trip: parse back and verify body text is recovered.
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_text.as_deref(),
        Some(body),
        "Non-ASCII body must round-trip through SevenBit QP encoding"
    );
}

/// Multipart/alternative message with pure ASCII parts must use `7bit`
/// CTE for both parts (RFC 2045 Section 2.7).
///
/// RFC 2045 Section 2.7, RFC 5321 Section 2.3.1
#[test]
fn build_seven_bit_multipart_ascii_both_parts_use_7bit() {
    let mut email = make_email();
    email.body_text = Some("Plain text".into());
    email.body_html = Some("<p>HTML</p>".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    let seven_bit_count = s.matches("Content-Transfer-Encoding: 7bit").count();
    assert_eq!(
        seven_bit_count, 2,
        "SevenBit multipart with ASCII must use 7bit for both parts, got {seven_bit_count}"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: 8bit"),
        "SevenBit must not produce any 8bit encoding"
    );
}

/// Non-ASCII multipart must QP-encode both text and HTML parts.
///
/// RFC 2045 Section 6.7, RFC 5321 Section 2.3.1
#[test]
fn build_seven_bit_multipart_non_ascii_both_parts_use_qp() {
    let mut email = make_email();
    email.body_text = Some("Héllo café".into());
    email.body_html = Some("<p>résumé</p>".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    let qp_count = s
        .matches("Content-Transfer-Encoding: quoted-printable")
        .count();
    assert_eq!(
        qp_count, 2,
        "SevenBit multipart with non-ASCII must QP-encode both parts, got {qp_count}"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: 8bit"),
        "SevenBit must not produce any 8bit encoding"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: 7bit"),
        "Non-ASCII content must not use 7bit CTE"
    );

    // Round-trip
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(parsed.body_text.as_deref(), Some("Héllo café"));
    assert_eq!(parsed.body_html.as_deref(), Some("<p>résumé</p>"));
}

/// Pure ASCII but long lines must use quoted-printable
/// (RFC 2045 Section 2.8 — line length limit).
#[test]
fn build_seven_bit_ascii_long_lines_uses_qp() {
    let mut email = make_email();
    let long_line = "A".repeat(1200);
    email.body_text = Some(long_line);

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "SevenBit with long ASCII lines must use QP, got:\n{s}"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: 7bit"),
        "Long lines cannot use 7bit CTE"
    );
}

/// Pure ASCII short lines use `7bit` CTE — the builder always produces
/// 7-bit safe output.
///
/// RFC 2045 Section 2.7
#[test]
fn build_ascii_uses_7bit_cte() {
    let mut email = make_email();
    email.body_text = Some("Pure ASCII".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: 7bit"),
        "Pure ASCII must use 7bit CTE, got:\n{s}"
    );
}

/// RFC 2045 Section 2.7 forbids NUL octets in `7bit` data, so text
/// containing NUL must be transfer-encoded via quoted-printable.
#[test]
fn build_text_with_nul_uses_quoted_printable() {
    let mut email = make_email();
    let body = "nul\0byte";
    email.body_text = Some(body.into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "Text containing NUL must not be emitted as raw 8bit: {s:?}"
    );
    assert!(
        !built.raw.contains(&0x00),
        "quoted-printable output must not contain raw NUL octets"
    );

    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_text.as_deref(),
        Some(body),
        "NUL-containing body must round-trip through quoted-printable"
    );
}

/// RFC 2045 Section 2.7 forbids NUL octets in raw `7bit` data — NUL
/// bytes in text must be QP-encoded.
#[test]
fn build_seven_bit_text_with_nul_uses_quoted_printable() {
    let mut email = make_email();
    let body = "nul\0byte";
    email.body_text = Some(body.into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "SevenBit text containing NUL must use quoted-printable: {s:?}"
    );
    assert!(
        !built.raw.contains(&0x00),
        "quoted-printable output must not contain raw NUL octets"
    );

    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_text.as_deref(),
        Some(body),
        "NUL-containing body must round-trip through quoted-printable"
    );
}

/// No body produces an empty text/plain part with `7bit` CTE — an
/// empty string is trivially ASCII-safe.
///
/// RFC 2045 Section 2.7, RFC 5321 Section 2.3.1
#[test]
fn build_seven_bit_empty_body_uses_7bit_cte() {
    let email = make_email();

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Transfer-Encoding: 7bit"),
        "SevenBit with empty body must use 7bit CTE, got:\n{s}"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: 8bit"),
        "SevenBit must not produce 8bit encoding"
    );
    assert!(
        !s.contains("Content-Transfer-Encoding: quoted-printable"),
        "Empty body should not need quoted-printable"
    );
}

/// RFC 5322 Section 3.6.2: `reply-to = "Reply-To:" address-list CRLF`
/// — Reply-To allows multiple addresses. `OutgoingEmail` must support
/// building messages with more than one Reply-To address.
#[test]
fn build_message_multiple_reply_to() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: Some("Sender".into()),
            email: "sender@example.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "to@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![
            Address {
                name: Some("Reply One".into()),
                email: "reply1@example.com".into(),
            },
            Address {
                name: Some("Reply Two".into()),
                email: "reply2@example.com".into(),
            },
        ],
        date: None,
        subject: "Test multiple Reply-To".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let raw = String::from_utf8_lossy(&built.raw);
    // Both Reply-To addresses must appear in the header
    assert!(
        raw.contains("reply1@example.com"),
        "First Reply-To address must appear in message: {raw}"
    );
    assert!(
        raw.contains("reply2@example.com"),
        "Second Reply-To address must appear in message: {raw}"
    );
    // Verify round-trip: parsed message must have both Reply-To addresses
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.reply_to.len(),
        2,
        "Parsed message must have 2 Reply-To addresses, got {:?}",
        parsed.reply_to
    );
}

/// RFC 5322 Section 3.6.8: optional-field = field-name ":" unstructured CRLF
/// — `OutgoingEmail` must support arbitrary extra headers for fields like
/// `List-Unsubscribe`, `X-Mailer`, etc.
#[test]
fn build_message_with_extra_headers() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "sender@example.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "to@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Test extra headers".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![
            (hdr("X-Mailer"), "TestMailer/1.0".into()),
            (hdr("List-Unsubscribe"), "<mailto:unsub@example.com>".into()),
        ],
    };
    let built = build_message(&email).unwrap();
    let raw = String::from_utf8_lossy(&built.raw);
    assert!(
        raw.contains("X-Mailer: TestMailer/1.0"),
        "X-Mailer header must appear in message: {raw}"
    );
    assert!(
        raw.contains("List-Unsubscribe:"),
        "List-Unsubscribe header must appear in message: {raw}"
    );
    assert!(
        raw.contains("mailto:unsub@example.com"),
        "List-Unsubscribe value must appear in message: {raw}"
    );
}

/// RFC 5322 Section 2.2: field-name = 1*ftext, where ftext = %d33-57 /
/// %d59-126 (printable ASCII excluding colon). Header names containing
/// colons, spaces, or control characters must be rejected at
/// construction time by [`HeaderName::new`].
#[test]
fn header_name_rejects_invalid_ftext() {
    // Colon in header name
    assert!(
        HeaderName::new("Invalid: Name").is_err(),
        "Header name with colon must be rejected (RFC 5322 Section 2.2)"
    );

    // Space in header name
    assert!(
        HeaderName::new("X Bad").is_err(),
        "Header name with space must be rejected (RFC 5322 Section 2.2)"
    );

    // Empty header name
    assert!(
        HeaderName::new("").is_err(),
        "Empty header name must be rejected (RFC 5322 Section 2.2)"
    );
}

/// RFC 5322 Section 3.4.1: addr-spec = local-part "@" domain — exactly
/// one `@`. An email like `user@domain@extra` must be rejected by the
/// builder to produce strictly conformant output.
#[test]
fn validate_address_rejects_multiple_at_signs() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "user@@domain.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "recipient@example.com".into(),
        }],
        cc: Vec::new(),
        bcc: Vec::new(),
        reply_to: Vec::new(),
        date: None,
        subject: "test".into(),
        body_text: Some("test".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: Vec::new(),
        extra_headers: Vec::new(),
    };
    assert!(
        build_message(&email).is_err(),
        "address with multiple '@' must be rejected (RFC 5322 Section 3.4.1)"
    );
}

/// RFC 5321 Section 4.1.2: domain must not start or end with a dot.
#[test]
fn validate_address_rejects_leading_trailing_dot_in_domain() {
    let make_email = |addr: &str| OutgoingEmail {
        from: vec![Address {
            name: None,
            email: addr.into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "recipient@example.com".into(),
        }],
        cc: Vec::new(),
        bcc: Vec::new(),
        reply_to: Vec::new(),
        date: None,
        subject: "test".into(),
        body_text: Some("test".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: Vec::new(),
        extra_headers: Vec::new(),
    };
    assert!(
        build_message(&make_email("user@.domain.com")).is_err(),
        "leading dot in domain must be rejected (RFC 5321 Section 4.1.2)"
    );
    assert!(
        build_message(&make_email("user@domain.com.")).is_err(),
        "trailing dot in domain must be rejected (RFC 5321 Section 4.1.2)"
    );
}

#[test]
fn spec_audit_extra_header_non_ascii_encoded() {
    // RFC 5322 Section 2.2: header field bodies must be US-ASCII.
    // Non-ASCII extra header values must be RFC 2047 encoded.
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "a@b.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "c@d.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Test".into(),
        body_text: Some("Body".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![(hdr("X-Custom"), "Héllo Wörld".into())],
    };
    let built = build_message(&email).unwrap();
    let raw_str = String::from_utf8_lossy(&built.raw);
    let header_section = raw_str.split("\r\n\r\n").next().unwrap();
    assert!(
        header_section.is_ascii(),
        "All header field bodies must be US-ASCII per RFC 5322 Section 2.2; \
         non-ASCII extra header value was not RFC 2047 encoded"
    );
}

/// Whitespace-only display names are not valid phrases under RFC 5322
/// Section 3.4 (`phrase = 1*word`, where `word = atom / quoted-string`).
/// `format_address` must treat them as absent and emit a bare email.
#[test]
fn format_address_whitespace_only_name_treated_as_absent() {
    let addr = Address {
        name: Some("   ".to_string()),
        email: "test@example.com".into(),
    };
    assert_eq!(format_address(&addr), "test@example.com");
}

/// RFC 5322 Section 2.2.3: `sanitize_header_value` must replace CR/LF with
/// spaces instead of stripping them, to avoid joining words without
/// separation (e.g., "Line1\nLine2" should become "Line1 Line2", not
/// "`Line1Line2`"). Legitimate spaces already present in the field body
/// must be preserved.
#[test]
fn sanitize_header_value_replaces_crlf_with_space() {
    // Bare LF between words
    assert_eq!(sanitize_header_value("Line1\nLine2"), "Line1 Line2");
    // Bare CR between words
    assert_eq!(sanitize_header_value("Line1\rLine2"), "Line1 Line2");
    // CRLF between words
    assert_eq!(sanitize_header_value("Line1\r\nLine2"), "Line1 Line2");
    // Multiple consecutive newlines should collapse to a single space
    assert_eq!(sanitize_header_value("A\n\n\nB"), "A B");
    // Existing spaces are preserved; only the control bytes are coalesced
    assert_eq!(sanitize_header_value("A\r\n \r\nB"), "A  B");
    // No CR/LF — should be unchanged
    assert_eq!(sanitize_header_value("Hello World"), "Hello World");
}

/// RFC 5322 Section 2.2.3: HTAB is valid WSP and must be preserved.
/// CR/LF are replaced with spaces, but existing SP/HTAB sequences pass
/// through unchanged.
#[test]
fn sanitize_header_value_preserves_tabs_strips_crlf() {
    // Multiple consecutive tabs are preserved (HTAB is valid WSP)
    assert_eq!(
        sanitize_header_value("Hello\t\t\tWorld"),
        "Hello\t\t\tWorld"
    );
    // CRLF is replaced with space, but following tabs are preserved
    assert_eq!(sanitize_header_value("A\r\n\t\tB"), "A \t\tB");
    // Mixed spaces and tabs are preserved exactly
    assert_eq!(sanitize_header_value("A\t \t B"), "A\t \t B");
}

/// RFC 5322 Section 2.2: header field bodies must contain only printable
/// US-ASCII characters (0x20–0x7E), SP, and HTAB.  ASCII control characters
/// (NUL 0x00, 0x01–0x08, 0x0B, 0x0C, 0x0E–0x1F, and DEL 0x7F) must be
/// replaced with spaces, just like CR/LF. Non-ASCII
/// characters (>= 0x80) must be preserved for RFC 6532 / RFC 2047 support.
#[test]
fn sanitize_header_value_strips_control_characters() {
    // NUL in the middle of a word
    assert_eq!(sanitize_header_value("Hello\x00World"), "Hello World");
    // Mixed control characters (SOH and DEL)
    assert_eq!(sanitize_header_value("A\x01B\x7FC"), "A B C");
    // VT (0x0B) and FF (0x0C)
    assert_eq!(sanitize_header_value("A\x0B\x0CB"), "A B");
    // Non-ASCII must be preserved (RFC 6532 / RFC 2047)
    assert_eq!(sanitize_header_value("Café"), "Café");
    // All low control characters (0x01–0x08, 0x0E–0x1F) should be replaced
    assert_eq!(sanitize_header_value("X\x02\x03\x04Y"), "X Y");
    // DEL (0x7F) alone
    assert_eq!(sanitize_header_value("A\x7FB"), "A B");
}

/// RFC 5322 Section 2.2.3: WSP is defined as SP or HTAB, so HTAB (0x09)
/// is a valid whitespace character in header field bodies and must be
/// preserved, not replaced with a space.  Only non-WSP control characters
/// should be stripped.
#[test]
fn sanitize_header_preserves_htab() {
    // A single HTAB between words must survive unchanged
    assert_eq!(sanitize_header_value("Hello\tWorld"), "Hello\tWorld");
    // HTAB at the start must survive
    assert_eq!(sanitize_header_value("\tIndented"), "\tIndented");
    // Mixed SP and HTAB must each be preserved (no collapsing HTAB into SP)
    assert_eq!(sanitize_header_value("A \tB"), "A \tB");
}

/// RFC 2045 Section 5 and RFC 2183 Section 2: attachment Content-Type
/// headers should include a `name` parameter as a fallback for email
/// clients that don't support Content-Disposition `filename`.
#[test]
fn attachment_content_type_includes_name_parameter() {
    let mut email = make_email();
    email.body_text = Some("text".into());
    email.attachments.push(OutgoingAttachment {
        filename: "report.pdf".into(),
        content_type: "application/pdf".into(),
        data: vec![0x25, 0x50, 0x44, 0x46], // %PDF
        is_inline: false,
        content_id: None,
    });

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        s.contains("Content-Type: application/pdf; name=\"report.pdf\""),
        "Content-Type header must include name parameter for attachments \
         (RFC 2045 Section 5). Got:\n{s}"
    );
}

/// RFC 5322 Section 3.4.1: local-part = dot-atom / quoted-string.
/// Addresses with quoted local parts like `"user name"@example.com`
/// must be accepted by `validate_address`.
#[test]
fn validate_address_accepts_quoted_local_part() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "\"user name\"@example.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "recipient@example.com".into(),
        }],
        cc: Vec::new(),
        bcc: Vec::new(),
        reply_to: Vec::new(),
        date: None,
        subject: "test".into(),
        body_text: Some("test".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: Vec::new(),
        extra_headers: Vec::new(),
    };
    assert!(
        build_message(&email).is_ok(),
        "address with quoted local part must be accepted (RFC 5322 Section 3.4.1)"
    );
}

/// Quoted local parts with special characters must also be accepted.
#[test]
fn validate_address_accepts_quoted_local_part_with_specials() {
    let addr = Address {
        name: None,
        email: "\"john..doe\"@example.com".into(),
    };
    assert!(
        validate_address(&addr).is_ok(),
        "quoted local part with consecutive dots must be accepted (RFC 5322 Section 3.4.1)"
    );
}

/// RFC 5322 Section 3.4.1 defines `domain-literal` for header addresses
/// independently of SMTP's RFC 5321 `address-literal` grammar.
/// A liberal header-domain like `[10,0,0,1]` must therefore parse and
/// build successfully in the message crate.
#[test]
fn validate_address_accepts_rfc5322_domain_literal() {
    let addr: Address = "user@[10,0,0,1]"
        .parse()
        .expect("RFC 5322 domain-literal must parse");

    let email = OutgoingEmail {
        from: vec![addr],
        sender: None,
        to: vec![Address {
            name: None,
            email: "recipient@example.com".into(),
        }],
        cc: Vec::new(),
        bcc: Vec::new(),
        reply_to: Vec::new(),
        date: None,
        subject: "test".into(),
        body_text: Some("test".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: Vec::new(),
        extra_headers: Vec::new(),
    };

    assert!(
        build_message(&email).is_ok(),
        "message builder must accept RFC 5322 domain-literals in header addresses"
    );
}

/// RFC 6532 Section 3.2 extends RFC 5322 `dtext` with UTF-8, so
/// internationalized domain-literals are valid in message header
/// addresses even though SMTP envelope paths remain stricter.
#[test]
fn validate_address_accepts_utf8_domain_literal() {
    let addr: Address = "user@[例え]"
        .parse()
        .expect("RFC 6532 UTF-8 domain-literal must parse");

    let email = OutgoingEmail {
        from: vec![addr],
        sender: None,
        to: vec![Address {
            name: None,
            email: "recipient@example.com".into(),
        }],
        cc: Vec::new(),
        bcc: Vec::new(),
        reply_to: Vec::new(),
        date: None,
        subject: "test".into(),
        body_text: Some("test".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: Vec::new(),
        extra_headers: Vec::new(),
    };

    assert!(
        build_message(&email).is_ok(),
        "message builder must accept UTF-8 domain-literals per RFC 6532 Section 3.2"
    );
}

/// Unquoted local parts with whitespace must still be rejected.
#[test]
fn validate_address_rejects_unquoted_local_with_whitespace() {
    let addr = Address {
        name: None,
        email: "user name@example.com".into(),
    };
    assert!(
        validate_address(&addr).is_err(),
        "unquoted local part with whitespace must be rejected"
    );
}

/// RFC 5322 Section 2.2: header field bodies must be US-ASCII.
/// The Content-Type `name` parameter for non-ASCII attachment filenames
/// must use an ASCII-safe value, not raw UTF-8 bytes. This applies to
/// MIME part headers inside multipart messages as well — RFC 2045
/// Section 4 inherits the US-ASCII requirement for all header fields.
#[test]
fn build_non_ascii_filename_content_type_name_is_ascii() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "résumé.pdf".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Find every Content-Type header line (including in MIME part headers)
    // and verify it contains only ASCII characters.
    for line in s.split("\r\n") {
        if line.starts_with("Content-Type:") && line.contains("name=") {
            assert!(
                line.is_ascii(),
                "Content-Type name parameter must be ASCII per RFC 5322 Section 2.2, \
                 but found non-ASCII: {line}"
            );
        }
    }
}

/// RFC 2231 Section 4: Content-Type `name*` must convey the full non-ASCII
/// filename for RFC 2231-aware clients, alongside the legacy ASCII `name`
/// fallback. Without `name*`, clients that read Content-Type but not
/// Content-Disposition lose the original filename.
#[test]
fn build_non_ascii_filename_content_type_has_name_star() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "résumé.pdf".into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Unfold headers for easier inspection.
    let unfolded = s.replace("\r\n ", " ").replace("\r\n\t", "\t");

    // Find the Content-Type header for the attachment part.
    let ct_line = unfolded
        .lines()
        .find(|l| l.starts_with("Content-Type: application/pdf"))
        .expect("Should have Content-Type for PDF attachment");

    // Must include name*=UTF-8'' with the full percent-encoded filename.
    assert!(
        ct_line.contains("name*=UTF-8''"),
        "RFC 2231 Section 4: Content-Type must include name* for non-ASCII \
         filenames, got: {ct_line}"
    );

    // The full filename must roundtrip through parse.
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some("résumé.pdf"),
        "Non-ASCII filename must roundtrip via Content-Type name*"
    );
}

/// RFC 2231 Section 3: very long non-ASCII filenames in Content-Type
/// must use continuation parameters (name*0*, name*1*, ...) to keep
/// lines within the 78-character recommendation.
#[test]
fn build_long_non_ascii_filename_content_type_has_name_star_continuation() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    let filename = "これはとても長いファイル名です_日本語のテスト_2024年度報告書_最終版.pdf";
    email.attachments = vec![OutgoingAttachment {
        filename: filename.into(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Unfold for inspection.
    let unfolded = s.replace("\r\n ", " ").replace("\r\n\t", "\t");

    // Must include continuation parameters for long filenames.
    let ct_line = unfolded
        .lines()
        .find(|l| l.starts_with("Content-Type: application/pdf"))
        .expect("Should have Content-Type for PDF attachment");

    // Either single name* or continuation name*0*
    assert!(
        ct_line.contains("name*=UTF-8''") || ct_line.contains("name*0*=UTF-8''"),
        "RFC 2231 Section 3-4: Content-Type must include name* or name*0* \
         for non-ASCII filenames, got: {ct_line}"
    );

    // Full filename must roundtrip.
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some(filename),
        "Long non-ASCII filename must roundtrip"
    );
}

/// Regression test: with `max_raw_bytes = 42`, every encoded word must stay
/// within 75 characters (RFC 2047 Section 2) even after `snap_utf8_chunk_end`
/// adjusts the chunk boundary for multi-byte UTF-8 characters.
///
/// The conservative limit of 42 raw bytes ensures that even if snap expands
/// a chunk by up to 3 bytes (to complete a 4-byte UTF-8 character), the
/// result (45 bytes max) still encodes to at most 60 base64 chars + 12
/// overhead = 72 chars, safely within the 75-char limit.
///
/// With the old `max_raw_bytes = 45`, chunks of 43-45 bytes produce 60
/// base64 chars + 12 overhead = 72 chars — which is within 75 but leaves
/// only a 3-char margin. This test enforces the tighter bound (max 68
/// chars per word with aligned chunks) to verify the conservative limit.
#[test]
fn encode_rfc2047_four_byte_boundary_length() {
    // 42 raw bytes → ceil(42/3)*4 = 56 base64 chars + 12 overhead = 68.
    // With snap backing up to a character boundary, the chunk can be
    // 40-42 bytes, all of which encode to at most 56 base64 chars.
    // The strict bound is 68 chars per encoded word.
    let max_expected_word_len = 68;

    // Try every alignment of 4-byte characters relative to the chunk
    // boundary. With N ASCII bytes followed by 4-byte emoji, the snap
    // function produces chunks of varying sizes depending on alignment.
    for ascii_prefix_len in 0..48 {
        // Build: N ASCII bytes + enough 4-byte emoji to exceed one chunk
        let mut input = "x".repeat(ascii_prefix_len);
        // Append 30 copies of U+1F30D (🌍, 4 bytes each = 120 bytes)
        for _ in 0..30 {
            input.push('\u{1F30D}');
        }

        let encoded = encode_rfc2047_if_needed(&input);

        for word in encoded.split(' ') {
            if word.starts_with("=?") {
                assert!(
                    word.len() <= max_expected_word_len,
                    "RFC 2047 Section 2: encoded word is {} chars (max {max_expected_word_len}) \
                     with ascii_prefix_len={ascii_prefix_len}: {word}",
                    word.len()
                );
            }
        }
    }
}

/// RFC 5322 Section 3.6: standard headers have specific occurrence limits.
/// `extra_headers` must not duplicate headers the builder already emits.
#[test]
fn extra_headers_rejects_standard_header_names() {
    let standard_names = [
        "From",
        "To",
        "Cc",
        "Bcc",
        "Reply-To",
        "Subject",
        "Date",
        "Message-ID",
        "MIME-Version",
        "Content-Type",
        "Content-Transfer-Encoding",
        "In-Reply-To",
        "References",
    ];

    for name in &standard_names {
        let mut email = make_email();
        email.body_text = Some("body".into());
        email.extra_headers = vec![(hdr(name), "duplicate".into())];

        let result = build_message(&email);
        assert!(
            result.is_err(),
            "extra_headers should reject standard header '{name}' (RFC 5322 Section 3.6)"
        );
    }
}

/// RFC 5322 Section 3.6: case-insensitive check — "from" == "From".
#[test]
fn extra_headers_rejects_standard_names_case_insensitive() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(hdr("from"), "dup".into())];

    let result = build_message(&email);
    assert!(
        result.is_err(),
        "extra_headers should reject 'from' case-insensitively (RFC 5322 Section 3.6)"
    );
}

/// Non-standard headers in `extra_headers` should still be accepted.
#[test]
fn extra_headers_accepts_custom_headers() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(hdr("X-Custom"), "value".into())];

    let result = build_message(&email);
    assert!(result.is_ok(), "custom headers should be accepted");
    let s = raw_str(&result.unwrap());
    assert!(s.contains("X-Custom: value"));
}

/// Content-ID values containing CRLF or other garbage must be rejected
/// rather than emitted as malformed msg-id syntax.
///
/// RFC 2392 uses the RFC 5322 `msg-id` syntax, so a caller-provided
/// `Content-ID` that is no longer a valid msg-id body after trimming must
/// fail fast instead of being sanitized into an invalid header value.
#[test]
fn content_id_crlf_injection_rejected() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "a@b.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "c@d.com".into(),
        }],
        subject: "test".into(),
        body_html: Some("<img src=\"cid:img@ex.com\">".into()),
        body_text: None,
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        in_reply_to: vec![],
        references: vec![],
        extra_headers: vec![],
        attachments: vec![OutgoingAttachment {
            filename: "logo.png".into(),
            content_type: "image/png".into(),
            data: b"PNG".to_vec(),
            is_inline: true,
            content_id: Some("img@ex.com>\r\nBcc: attacker@evil.com".into()),
        }],
    };
    let err = build_message(&email).unwrap_err();
    assert!(
        err.to_string().contains("Content-ID"),
        "invalid Content-ID must be rejected with a Content-ID-specific error: {err}"
    );
}

/// multipart/related Content-Type must include the `type` parameter
/// per RFC 2387 Section 3.1.
#[test]
fn multipart_related_includes_type_parameter() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "a@b.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "c@d.com".into(),
        }],
        subject: "test".into(),
        body_html: Some("<img src=\"cid:logo@ex.com\">".into()),
        body_text: None,
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        in_reply_to: vec![],
        references: vec![],
        extra_headers: vec![],
        attachments: vec![OutgoingAttachment {
            filename: "logo.png".into(),
            content_type: "image/png".into(),
            data: b"PNG".to_vec(),
            is_inline: true,
            content_id: Some("logo@ex.com".into()),
        }],
    };
    let built = build_message(&email).unwrap();
    let s = String::from_utf8_lossy(&built.raw);
    assert!(
        s.contains("type=\"text/html\"") || s.contains("type=\"multipart/alternative\""),
        "multipart/related must include type parameter per RFC 2387 Section 3.1: {s}"
    );
}

/// In-Reply-To must support multiple message-ids, wrapping each one
/// individually in angle brackets (RFC 5322 Section 3.6.4).
#[test]
fn in_reply_to_multiple_message_ids() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "a@b.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "c@d.com".into(),
        }],
        subject: "test".into(),
        body_text: Some("body".into()),
        body_html: None,
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        in_reply_to: vec![mid("id1@host.com"), mid("id2@host.com")],
        references: vec![],
        extra_headers: vec![],
        attachments: vec![],
    };
    let built = build_message(&email).unwrap();
    let s = String::from_utf8_lossy(&built.raw);
    assert!(
        s.contains("<id1@host.com> <id2@host.com>"),
        "In-Reply-To must support multiple msg-ids per RFC 5322 Section 3.6.4: {s}"
    );
}

/// RFC 5322 Section 3.6.4 limits generated `msg-id` values to
/// `dot-atom-text` on the left-hand side. RFC 5322 Appendix A notes that
/// `no-fold-quote` was removed from modern `msg-id` syntax, so the builder
/// must not emit quoted `id-left` values even if a caller injects them via
/// `MessageId::new_unchecked`.
#[test]
fn in_reply_to_quoted_id_left_skipped() {
    let mut email = make_email();
    email.body_text = Some("text".into());
    email.in_reply_to = vec![mid("\"user@inner\"@example.com")];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    assert!(
        !s.contains("In-Reply-To:"),
        "quoted obsolete msg-id must be dropped from In-Reply-To per RFC 5322 Section 3.6.4: {s}"
    );
}

// --- RFC 5322 Section 3.6.4: msg-id requires "@" ---
// msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS]
// Tokens without "@" are not valid message-ids and must be skipped
// by the encoder (Postel's law: be conservative in what you send).

#[test]
fn spec_audit_in_reply_to_valid_msgid() {
    // Baseline: a valid message-id (contains @) is emitted correctly.
    let mut email = make_email();
    email.body_text = Some("text".into());
    email.in_reply_to = vec![mid("abc@example.com")];
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    assert!(
        s.contains("In-Reply-To: <abc@example.com>"),
        "Valid message-id must be emitted in angle brackets: {s}"
    );
}

#[test]
fn spec_audit_in_reply_to_invalid_msgid_skipped() {
    // A token without "@" is not a valid msg-id per RFC 5322 Section 3.6.4
    // and must be silently skipped.
    let mut email = make_email();
    email.body_text = Some("text".into());
    email.in_reply_to = vec![mid("invalid-no-at")];
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    assert!(
        !s.contains("In-Reply-To:"),
        "In-Reply-To with no valid msg-ids must not be emitted: {s}"
    );
}

#[test]
fn spec_audit_references_mixed_valid_invalid() {
    // Only valid message-ids (containing @) should appear in References.
    let mut email = make_email();
    email.body_text = Some("text".into());
    email.references = vec![
        mid("good@example.com"),
        mid("invalid-no-at"),
        mid("also-bad"),
        mid("better@host.org"),
    ];
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    assert!(
        s.contains("<good@example.com>"),
        "Valid msg-id must be emitted: {s}"
    );
    assert!(
        s.contains("<better@host.org>"),
        "Valid msg-id must be emitted: {s}"
    );
    assert!(
        !s.contains("invalid-no-at"),
        "Invalid token without @ must be skipped: {s}"
    );
    assert!(
        !s.contains("also-bad"),
        "Invalid token without @ must be skipped: {s}"
    );
}

#[test]
fn spec_audit_in_reply_to_all_invalid_omits_header() {
    // When ALL tokens lack "@", no In-Reply-To header should be emitted.
    let mut email = make_email();
    email.body_text = Some("text".into());
    email.in_reply_to = vec![mid("no-at-one"), mid("no-at-two")];
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    assert!(
        !s.contains("In-Reply-To:"),
        "In-Reply-To must be omitted when all tokens are invalid: {s}"
    );
}

/// RFC 5322 Section 3.6.4: `msg-id = "<" id-left "@" id-right ">"`.
/// Both `id-left` and `id-right` must be non-empty. Message-IDs like
/// `foo@` (empty id-right) or `@bar` (empty id-left) are malformed
/// and must be skipped by the builder.
#[test]
fn spec_audit_msgid_empty_id_left_or_right_skipped() {
    // Empty id-right: "foo@"
    let mut email = make_email();
    email.body_text = Some("text".into());
    email.in_reply_to = vec![mid("foo@")];
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    assert!(
        !s.contains("In-Reply-To:"),
        "msg-id with empty id-right must be skipped \
         (RFC 5322 Section 3.6.4): {s}"
    );

    // Empty id-left: "@bar.com"
    let mut email2 = make_email();
    email2.body_text = Some("text".into());
    email2.references = vec![mid("@bar.com")];
    let built2 = build_message(&email2).unwrap();
    let s2 = raw_str(&built2);
    assert!(
        !s2.contains("References:"),
        "msg-id with empty id-left must be skipped \
         (RFC 5322 Section 3.6.4): {s2}"
    );
}

// --- RFC 2046 Section 5.2.1: message/* encoding restrictions ---
// message/rfc822 (and message/* in general) MUST NOT use content-transfer-
// encodings other than 7bit, 8bit, or binary. The builder must not
// base64-encode these parts.

#[test]
fn spec_audit_message_rfc822_attachment_uses_7bit_encoding() {
    // RFC 2046 Section 5.2.1: message/rfc822 parts MUST NOT be encoded
    // with base64 or quoted-printable. The builder must use 7bit (or 8bit
    // for non-ASCII data) and write the attachment data verbatim.
    let rfc822_body = b"From: nested@example.com\r\nTo: other@example.com\r\nSubject: inner\r\n\r\nInner body\r\n";
    let mut email = make_email();
    email.body_text = Some("outer body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "forwarded.eml".into(),
        content_type: "message/rfc822".into(),
        data: rfc822_body.to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Must NOT use base64 encoding
    assert!(
        !s.contains("Content-Transfer-Encoding: base64"),
        "message/rfc822 MUST NOT use base64 per RFC 2046 Section 5.2.1: {s}"
    );
    // Must use 7bit encoding (all bytes are ASCII)
    assert!(
        s.contains("Content-Transfer-Encoding: 7bit"),
        "message/rfc822 with ASCII data must use 7bit encoding: {s}"
    );
    // Data must appear verbatim (not base64-encoded)
    assert!(
        s.contains("From: nested@example.com"),
        "message/rfc822 data must be written verbatim: {s}"
    );
    assert!(
        s.contains("Inner body"),
        "message/rfc822 body must be written verbatim: {s}"
    );
}

#[test]
fn spec_audit_message_rfc822_non_ascii_uses_8bit_encoding() {
    // RFC 2046 Section 5.2.1: when message/rfc822 data contains non-ASCII
    // bytes, the encoding must be 8bit (not base64).
    let rfc822_body = "From: nested@example.com\r\nTo: other@example.com\r\nSubject: =?UTF-8?B?w7xiZXI=?=\r\n\r\nK\u{f6}rper\r\n";
    let mut email = make_email();
    email.body_text = Some("outer body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "forwarded.eml".into(),
        content_type: "message/rfc822".into(),
        data: rfc822_body.as_bytes().to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        !s.contains("Content-Transfer-Encoding: base64"),
        "message/rfc822 MUST NOT use base64 per RFC 2046 Section 5.2.1: {s}"
    );
    assert!(
        s.contains("Content-Transfer-Encoding: 8bit"),
        "message/rfc822 with non-ASCII data must use 8bit encoding: {s}"
    );
    // Data must appear verbatim
    assert!(
        s.contains("K\u{f6}rper"),
        "message/rfc822 data must be written verbatim: {s}"
    );
}

#[test]
fn spec_audit_message_rfc822_rejects_utf8_headers() {
    // RFC 2046 Section 5.2.1 requires message/rfc822 header fields to
    // remain US-ASCII, with RFC 2047 used for non-ASCII text. RFC 6532
    // Section 3.7 defines message/global for encapsulated messages with
    // raw UTF-8 header values.
    let rfc822_body = "From: nested@example.com\r\nSubject: caf\u{00E9}\r\n\r\nASCII body\r\n";
    let mut email = make_email();
    email.body_text = Some("outer body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "forwarded.eml".into(),
        content_type: "message/rfc822".into(),
        data: rfc822_body.as_bytes().to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let err =
        build_message(&email).expect_err("message/rfc822 with raw UTF-8 headers must be rejected");
    match err {
        Error::InvalidAttachment(msg) => {
            assert!(
                msg.contains("message/global"),
                "error should direct callers to message/global, got: {msg}"
            );
        }
        other => panic!("expected InvalidAttachment error, got {other:?}"),
    }
}

#[test]
fn spec_audit_message_rfc822_requires_from_subject_or_date() {
    // RFC 2046 Section 5.2.1 relaxes top-level message requirements for
    // encapsulated message/rfc822 bodies, but still requires at least one
    // of From, Subject, or Date to be present in the embedded header block.
    let rfc822_body = b"To: other@example.com\r\n\r\nInner body\r\n";
    let mut email = make_email();
    email.body_text = Some("outer body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "forwarded.eml".into(),
        content_type: "message/rfc822".into(),
        data: rfc822_body.to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let err = build_message(&email).expect_err(
        "message/rfc822 without From, Subject, or Date must be rejected per RFC 2046 Section 5.2.1",
    );
    match err {
        Error::InvalidAttachment(msg) => {
            assert!(
                msg.contains("From") && msg.contains("Subject") && msg.contains("Date"),
                "error should mention the required header set, got: {msg}"
            );
        }
        other => panic!("expected InvalidAttachment error, got {other:?}"),
    }
}

#[test]
fn spec_audit_message_rfc822_rejects_bare_lf_body() {
    let mut email = make_email();
    email.body_text = Some("outer body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "forwarded.eml".into(),
        content_type: "message/rfc822".into(),
        data: b"From: nested@example.com\nSubject: inner\n\nInner body\n".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let err = build_message(&email)
        .expect_err("message/rfc822 with bare LF must be rejected before emitting 7bit/8bit");
    match err {
        Error::InvalidAttachment(msg) => {
            assert!(
                msg.contains("bare LF"),
                "error should explain the CRLF violation, got: {msg}"
            );
        }
        other => panic!("expected InvalidAttachment error, got {other:?}"),
    }
}

#[test]
fn spec_audit_message_rfc822_rejects_nul_bytes() {
    let mut email = make_email();
    email.body_text = Some("outer body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "forwarded.eml".into(),
        content_type: "message/rfc822".into(),
        data: b"From: nested@example.com\r\nSubject: inner\r\n\r\nbody\x00\r\n".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let err = build_message(&email)
        .expect_err("message/rfc822 with NUL bytes must be rejected before emitting 8bit");
    match err {
        Error::InvalidAttachment(msg) => {
            assert!(
                msg.contains("NUL"),
                "error should explain the NUL violation, got: {msg}"
            );
        }
        other => panic!("expected InvalidAttachment error, got {other:?}"),
    }
}

#[test]
fn spec_audit_message_partial_rejects_non_ascii_bytes() {
    let mut email = make_email();
    email.body_text = Some("outer body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "fragment.eml".into(),
        content_type: "message/partial; id=\"frag-1\"; number=1; total=2".into(),
        data: b"From: nested@example.com\r\nSubject: inner\r\n\r\nK\xc3\xb6rper\r\n".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let err = build_message(&email).expect_err(
        "message/partial must reject non-ASCII bytes because RFC 2046 Section 5.2.2 requires 7bit only",
    );
    match err {
        Error::InvalidAttachment(msg) => {
            assert!(
                msg.contains("7bit"),
                "error should explain the 7bit-only rule, got: {msg}"
            );
        }
        other => panic!("expected InvalidAttachment error, got {other:?}"),
    }
}

#[test]
fn spec_audit_message_external_body_rejects_non_ascii_bytes() {
    let mut email = make_email();
    email.body_text = Some("outer body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "external-body.eml".into(),
        content_type: "message/external-body; access-type=URL; URL=\"https://example.test/ref\""
            .into(),
        data: b"Content-Type: text/plain; charset=UTF-8\r\n\r\nK\xc3\xb6rper\r\n".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let err = build_message(&email).expect_err(
        "message/external-body must reject non-ASCII bytes because RFC 2046 Section 5.2.3 requires 7bit only",
    );
    match err {
        Error::InvalidAttachment(msg) => {
            assert!(
                msg.contains("7bit"),
                "error should explain the 7bit-only rule, got: {msg}"
            );
        }
        other => panic!("expected InvalidAttachment error, got {other:?}"),
    }
}

#[test]
fn spec_audit_message_type_case_insensitive() {
    // The content type check for message/* must be case-insensitive
    // per RFC 2045 Section 5.1.
    let rfc822_body = b"From: a@b.com\r\nSubject: test\r\n\r\nbody\r\n";
    let mut email = make_email();
    email.body_text = Some("outer".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "msg.eml".into(),
        content_type: "Message/RFC822".into(),
        data: rfc822_body.to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    assert!(
        !s.contains("Content-Transfer-Encoding: base64"),
        "Message/RFC822 (mixed case) MUST NOT use base64: {s}"
    );
}

/// RFC 5321 Section 4.1.2: Domain = sub-domain *("." sub-domain) — each
/// sub-domain must be non-empty, so consecutive dots ("..") in the domain
/// indicate an empty label and must be rejected.
#[test]
fn test_validate_address_rejects_consecutive_dots_in_domain() {
    let cases = [
        "user@exam..ple.com",
        "user@..example.com",
        "user@example..com",
        "user@a..b..c.com",
    ];
    for email in &cases {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        let result = validate_address(&addr);
        assert!(
            result.is_err(),
            "expected rejection for consecutive dots in domain: {email}"
        );
    }
}

/// RFC 5321 domain labels inherit the DNS 63-octet per-label limit.
/// The builder already enforces SMTP-style mailbox validation, so it must
/// reject addresses whose domain contains an overlong label instead of
/// emitting an undeliverable addr-spec.
#[test]
fn test_validate_address_rejects_overlong_domain_label() {
    let overlong = format!("user@{}.example", "a".repeat(64));
    let addr = Address {
        name: None,
        email: overlong,
    };

    let err = validate_address(&addr).expect_err(
        "domain labels longer than 63 octets must be rejected during builder validation",
    );
    match err {
        Error::InvalidAddress(msg) => assert!(
            msg.contains("63-octet") || msg.contains("63 octet"),
            "error should explain the 63-octet domain label limit, got: {msg}"
        ),
        other => panic!("expected InvalidAddress for overlong label, got {other:?}"),
    }
}

/// RFC 5321 Section 4.1.2: `Dot-string = Atom *("." Atom)` — each atom
/// between dots must be non-empty, so consecutive dots (`..`), leading
/// dots, and trailing dots are invalid in unquoted local-parts.
/// Quoted local-parts (`"..."`) have different rules and must still allow
/// consecutive dots.
#[test]
fn test_validate_address_rejects_consecutive_dots_in_local_part() {
    // Unquoted local-parts with consecutive dots must be rejected.
    let cases = vec![
        "us..er@example.com",
        "user..@example.com",
        "..user@example.com",
    ];
    for email in &cases {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        assert!(
            validate_address(&addr).is_err(),
            "expected rejection for unquoted local-part with consecutive dots: {email}"
        );
    }

    // Quoted local-part with consecutive dots is valid per RFC 5322 Section 3.2.4.
    let quoted_addr = Address {
        name: None,
        email: "\"us..er\"@example.com".to_string(),
    };
    assert!(
        validate_address(&quoted_addr).is_ok(),
        "quoted local-part with consecutive dots should be accepted"
    );
}

/// Regression: quoted local-parts with unescaped inner double-quotes
/// must be rejected per RFC 5322 Section 3.2.4.
///
/// `quoted-string = DQUOTE *( qtext / quoted-pair ) DQUOTE`
/// where `qtext` excludes `"` and `\`, and `quoted-pair = "\" (VCHAR / WSP)`.
/// An unescaped `"` inside the quoted-string is a syntax error.
#[test]
fn validate_address_rejects_malformed_quoted_local() {
    // Unescaped inner quote: `"a"b"@example.com`
    let addr = Address {
        name: None,
        email: "\"a\"b\"@example.com".into(),
    };
    assert!(
        validate_address(&addr).is_err(),
        "quoted local-part with unescaped inner double-quote must be rejected \
         (RFC 5322 Section 3.2.4)"
    );
}

/// Properly escaped quoted local-parts must still be accepted.
#[test]
fn validate_address_accepts_properly_escaped_quoted_local() {
    // Escaped inner quote: `"a\"b"@example.com`
    let addr = Address {
        name: None,
        email: r#""a\"b"@example.com"#.into(),
    };
    assert!(
        validate_address(&addr).is_ok(),
        "quoted local-part with properly escaped inner quote must be accepted \
         (RFC 5322 Section 3.2.4)"
    );
}

/// Quoted local-parts with bare backslash (not followed by VCHAR/WSP)
/// must be rejected per RFC 5322 Section 3.2.4.
#[test]
fn validate_address_rejects_trailing_backslash_in_quoted_local() {
    // Trailing backslash: `"abc\"@example.com` — the backslash escapes
    // the closing quote, so there's no real closing quote.
    let addr = Address {
        name: None,
        email: "\"abc\\\"@example.com".into(),
    };
    assert!(
        validate_address(&addr).is_err(),
        "quoted local-part with backslash escaping the closing quote must be rejected \
         (RFC 5322 Section 3.2.4)"
    );
}

// ===== Edge-case bug-hunting tests =====

/// RFC 5322 Section 3.4: an all-whitespace display name is not a valid
/// `phrase` (`1*word`), so it must be treated as absent. The Display
/// impl should output just the email, not `"   " <a@b.com>`.
#[test]
fn edge_address_all_whitespace_display_name() {
    let addr = Address {
        name: Some("   ".to_string()),
        email: "a@b.com".to_string(),
    };
    let formatted = format!("{addr}");
    assert_eq!(
        formatted, "a@b.com",
        "All-whitespace display name must be treated as absent \
         per RFC 5322 Section 3.4"
    );
}

/// RFC 5322 Section 2.1: subject containing CR/LF must be sanitized
/// to prevent header injection. A subject like "Hello\r\nBcc: evil"
/// must NOT produce a separate Bcc header line in the output.
#[test]
fn edge_subject_crlf_injection_sanitized() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "a@b.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "c@d.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Hello\r\nBcc: evil@hacker.com".into(),
        body_text: Some("test".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let raw = String::from_utf8_lossy(&built.raw);
    // The CRLF must be stripped so "Bcc:" does NOT appear as a
    // separate header line (i.e. preceded by CRLF).
    assert!(
        !raw.contains("\r\nBcc:"),
        "CR/LF in subject must be sanitized to prevent header injection \
         (RFC 5322 Section 2.1). Got:\n{raw}"
    );
}

/// RFC 5322 Section 2.1: `extra_headers` containing CR/LF must also be
/// sanitized. An extra header with an injected CRLF must not produce
/// additional headers.
#[test]
fn edge_extra_header_crlf_injection() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "a@b.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "c@d.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Normal".into(),
        body_text: Some("test".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![(hdr("X-Custom"), "value\r\nBcc: evil@hacker.com".into())],
    };
    let built = build_message(&email).unwrap();
    let raw = String::from_utf8_lossy(&built.raw);
    // The injected CRLF must be stripped so "Bcc:" does NOT appear
    // as a separate header line.
    assert!(
        !raw.contains("\r\nBcc:"),
        "CR/LF in extra_headers must be sanitized (RFC 5322 Section 2.1). \
         Got:\n{raw}"
    );
}

/// RFC 5322 Section 3.4: a display name that consists only of a tab
/// character should be treated as absent.
#[test]
fn edge_address_tab_only_display_name() {
    let addr = Address {
        name: Some("\t".to_string()),
        email: "a@b.com".to_string(),
    };
    let formatted = format!("{addr}");
    assert_eq!(
        formatted, "a@b.com",
        "Tab-only display name must be treated as absent"
    );
}

/// RFC 5322 Section 2.1: display name containing CRLF must be
/// sanitized in the built message to prevent header injection.
#[test]
fn edge_display_name_crlf_injection() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: Some("Alice\r\nBcc: evil@hacker.com".into()),
            email: "a@b.com".into(),
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "c@d.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Test".into(),
        body_text: Some("test".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let raw = String::from_utf8_lossy(&built.raw);
    // The CRLF in the display name must be stripped so "Bcc:" does NOT
    // appear as a separate header line.
    assert!(
        !raw.contains("\r\nBcc:"),
        "CR/LF in display name must be sanitized (RFC 5322 Section 2.1). \
         Got:\n{raw}"
    );
}

/// RFC 5322 Section 3.2.4: `qtext = %d33 / %d35-91 / %d93-126`.
/// Control characters (0x00-0x08, 0x0A-0x1F) and DEL (0x7F) are NOT
/// valid qtext. Generators MUST NOT produce obsolete constructs
/// (RFC 5322 Section 4). The builder must reject these bytes in
/// quoted local-parts to produce strictly conformant output.
#[test]
fn validate_address_rejects_control_chars_in_quoted_local() {
    // NUL (0x00) in quoted local-part
    let addr = Address {
        name: None,
        email: "\"\x00user\"@example.com".to_string(),
    };
    assert!(
        validate_address(&addr).is_err(),
        "quoted local-part with NUL (0x00) must be rejected \
         (RFC 5322 Section 3.2.4: qtext does not include control characters)"
    );

    // BEL (0x07) in quoted local-part
    let addr = Address {
        name: None,
        email: "\"\x07bell\"@example.com".to_string(),
    };
    assert!(
        validate_address(&addr).is_err(),
        "quoted local-part with BEL (0x07) must be rejected \
         (RFC 5322 Section 3.2.4)"
    );

    // LF (0x0A) in quoted local-part
    let addr = Address {
        name: None,
        email: "\"line\nfeed\"@example.com".into(),
    };
    assert!(
        validate_address(&addr).is_err(),
        "quoted local-part with LF (0x0A) must be rejected \
         (RFC 5322 Section 3.2.4)"
    );

    // DEL (0x7F) in quoted local-part
    let addr = Address {
        name: None,
        email: "\"del\x7F\"@example.com".to_string(),
    };
    assert!(
        validate_address(&addr).is_err(),
        "quoted local-part with DEL (0x7F) must be rejected \
         (RFC 5322 Section 3.2.4)"
    );
}

/// RFC 5322 Section 3.2.3 / Section 3.4.1: an unquoted local-part is
/// a `dot-atom`, and each atom must contain only `atext` characters:
///
/// ```text
/// atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" /
///         "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" /
///         "`" / "{" / "|" / "}" / "~"
/// ```
///
/// Characters like `(`, `)`, `<`, `>`, `,`, `;`, `:`, `\`, `"`,
/// `[`, `]` are NOT valid in unquoted local-parts and must be
/// rejected by the builder (conservative in what we send).
#[test]
fn validate_address_rejects_non_atext_in_unquoted_local() {
    let specials = vec![
        ("user(comment)@example.com", '('),
        ("user)bad@example.com", ')'),
        ("user<admin>@example.com", '<'),
        ("user>test@example.com", '>'),
        ("user,name@example.com", ','),
        ("user;name@example.com", ';'),
        ("user:name@example.com", ':'),
        ("user\\name@example.com", '\\'),
        ("user\"name@example.com", '"'),
        ("user[name@example.com", '['),
        ("user]name@example.com", ']'),
        ("user name@example.com", ' '),
    ];
    for (email, ch) in &specials {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        assert!(
            validate_address(&addr).is_err(),
            "unquoted local-part with '{ch}' must be rejected \
             per RFC 5322 Section 3.2.3 (atext): {email}"
        );
    }
}

/// RFC 5322 Section 3.2.3: valid `atext` characters in unquoted
/// local-parts must continue to be accepted after adding the
/// atext validation.
#[test]
fn validate_address_accepts_valid_atext_local() {
    let cases = vec![
        "user@example.com",
        "user.name@example.com",
        "user+tag@example.com",
        "user-name@example.com",
        "user_name@example.com",
        "user!name@example.com",
        "user#name@example.com",
        "user$name@example.com",
        "user%name@example.com",
        "user&name@example.com",
        "user'name@example.com",
        "user*name@example.com",
        "user/name@example.com",
        "user=name@example.com",
        "user?name@example.com",
        "user^name@example.com",
        "user`name@example.com",
        "user{name@example.com",
        "user|name@example.com",
        "user}name@example.com",
        "user~name@example.com",
    ];
    for email in &cases {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        assert!(
            validate_address(&addr).is_ok(),
            "valid atext local-part must be accepted: {email}"
        );
    }
}

/// RFC 5322 Section 3.4.1 `domain-literal` is liberal enough that the
/// familiar RFC 5321-style IPv4/IPv6 address-literals are a valid subset.
/// The message validator must therefore continue to accept them.
#[test]
fn validate_address_accepts_address_literals() {
    let cases = vec![
        "user@[127.0.0.1]",
        "user@[192.168.1.1]",
        "user@[IPv6:::1]",
        "user@[IPv6:2001:db8::1]",
    ];
    for email in &cases {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        assert!(
            validate_address(&addr).is_ok(),
            "RFC 5321-style address-literal must be accepted as a valid \
             RFC 5322 domain-literal: {email}"
        );
    }
}

/// RFC 5322 Section 3.4.1 / RFC 6532 Section 3.2: malformed
/// `domain-literal` syntax must still be rejected. The liberal grammar
/// allows many bracketed forms that SMTP would reject, but it still does
/// not allow unbalanced brackets, whitespace, or backslash in `dtext`.
#[test]
fn validate_address_rejects_invalid_address_literals() {
    let cases = vec![
        "user@[127.0.0.1",
        "user@[127.0.0.1]]",
        "user@[bad literal]",
        "user@[bad\\literal]",
        "user@[tag:bad value]",
    ];
    for email in &cases {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        assert!(
            validate_address(&addr).is_err(),
            "invalid RFC 5322 domain-literal syntax must be rejected: {email}"
        );
    }
}

/// RFC 5322 Section 2.2.3: `force_fold_word` must not insert folds
/// inside an unbreakable token. When `line_len` is already 995 (near
/// the limit) and a word is appended, the function should fold BEFORE
/// the word so it starts on a fresh line, preserving the token intact.
///
/// This test calls `force_fold_word` directly with `line_len = 995`,
/// simulating a line with only 3 bytes of remaining capacity. The word
/// is 104 bytes (4-byte emoji + 100 ASCII chars). The function inserts
/// a fold before the word, then emits it as-is on the new line.
#[test]
fn force_fold_preserves_word_integrity_with_multibyte_utf8() {
    let word = "\u{1F389}".to_string() + &"a".repeat(100);
    let bytes = word.as_bytes();
    let mut output = Vec::new();

    // Simulate existing line content: 995 bytes already on the line.
    output.extend_from_slice(&vec![b'X'; 995]);

    let final_line_len = force_fold_word(&mut output, bytes, 995);

    let result = String::from_utf8(output).expect("output should be valid UTF-8");
    let lines: Vec<&str> = result.split("\r\n").collect();
    // The word must appear intact on the second line (after folding).
    assert_eq!(lines.len(), 2, "must fold once: before the word");
    assert_eq!(lines[0].len(), 995, "first line retains original content");
    // Second line: leading space + the full word.
    assert_eq!(
        &lines[1][1..],
        word,
        "word must appear intact without internal folds"
    );
    assert_eq!(
        final_line_len,
        1 + bytes.len(),
        "line_len must track the new line correctly"
    );
}

// ── RFC 5321 Section 4.1.2: domain character validation ──

/// RFC 5321 Section 4.1.2: Domain = sub-domain *("." sub-domain),
/// sub-domain = Let-dig [Ldh-str]. Characters that are not
/// alphanumeric or hyphens must be rejected in non-literal domains.
/// Specials like `(`, `)`, `<`, `>`, `,`, `;`, `@`, `"`, `\` are
/// NOT valid in domains and must be rejected by the validator.
#[test]
fn validate_address_rejects_invalid_domain_characters() {
    let invalid_domains = vec![
        "user@exam(ple.com",
        "user@exam)ple.com",
        "user@exam<ple.com",
        "user@exam>ple.com",
        "user@exam,ple.com",
        "user@exam;ple.com",
        "user@exam@ple.com", // caught by multiple-@ check, but included for completeness
        "user@exam\"ple.com",
        "user@exam\\ple.com",
        "user@exam ple.com",  // space (already caught, but included)
        "user@exam\tple.com", // tab (already caught, but included)
    ];
    for email in &invalid_domains {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        assert!(
            validate_address(&addr).is_err(),
            "domain with invalid character must be rejected per RFC 5321 Section 4.1.2: {email}"
        );
    }
}

/// Same as above but for quoted local-part branch: the domain
/// validation must also reject invalid domain characters when the
/// local-part is a quoted-string.
#[test]
fn validate_address_rejects_invalid_domain_characters_quoted_local() {
    let invalid_domains = vec![
        r#""user"@exam(ple.com"#,
        r#""user"@exam)ple.com"#,
        r#""user"@exam<ple.com"#,
        r#""user"@exam>ple.com"#,
        r#""user"@exam,ple.com"#,
        r#""user"@exam;ple.com"#,
    ];
    for email in &invalid_domains {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        assert!(
            validate_address(&addr).is_err(),
            "domain with invalid character must be rejected per RFC 5321 Section 4.1.2 \
             (quoted local-part branch): {email}"
        );
    }
}

/// Valid domains must continue to be accepted after the fix.
#[test]
fn validate_address_accepts_valid_domains() {
    let valid_emails = vec![
        "user@example.com",
        "user@sub.example.com",
        "user@example-host.com",
        "user@a.b.c.d",
        "user@host123.example.org",
        "user@123.456",
        // RFC 6531 Section 3.3: internationalized domain names (U-labels)
        "usuario@domínio.com",
        "user@münchen.de",
        "user@例え.jp",
    ];
    for email in &valid_emails {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        assert!(
            validate_address(&addr).is_ok(),
            "valid domain must be accepted per RFC 5321 Section 4.1.2: {email}"
        );
    }
}

/// RFC 5322 Section 3.4.1: dot-atom and domain-literal forms coexist, so
/// bracketed domains without whitespace or backslashes must remain valid
/// after the header-address fix.
#[test]
fn validate_address_accepts_domain_literals_after_fix() {
    let valid_emails = vec![
        "user@[127.0.0.1]",
        "user@[192.168.1.1]",
        "user@[IPv6:::1]",
        "user@[IPv6:2001:db8::1]",
        "user@[IPv6:not-an-ip]",
        "user@[IPv6:]",
    ];
    for email in &valid_emails {
        let addr = Address {
            name: None,
            email: (*email).to_string(),
        };
        assert!(
            validate_address(&addr).is_ok(),
            "domain-literal must be accepted per RFC 5322 Section 3.4.1: {email}"
        );
    }
}

// ── RFC 5322 Section 3.6.2: Sender header support for multi-From ──

/// RFC 5322 Section 3.6.2: when From contains multiple mailboxes, the
/// Sender header MUST be present. Building without it must return
/// `Error::MissingSender`.
#[test]
fn build_multi_from_without_sender_returns_error() {
    let email = OutgoingEmail {
        from: vec![
            Address {
                name: Some("Alice".into()),
                email: "alice@example.com".into(),
            },
            Address {
                name: Some("Bob".into()),
                email: "bob@example.com".into(),
            },
        ],
        sender: None,
        to: vec![Address {
            name: None,
            email: "rcpt@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Multi from".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let result = build_message(&email);
    assert!(
        matches!(result, Err(Error::MissingSender)),
        "multi-From without Sender must return MissingSender \
         (RFC 5322 Section 3.6.2), got: {result:?}"
    );
}

/// RFC 5322 Section 3.6.2: when From contains multiple mailboxes and
/// Sender is provided, the built message must contain both From and
/// Sender headers. From must list all addresses; Sender must list
/// exactly one.
#[test]
fn build_multi_from_with_sender_emits_both_headers() {
    let email = OutgoingEmail {
        from: vec![
            Address {
                name: Some("Alice".into()),
                email: "alice@example.com".into(),
            },
            Address {
                name: Some("Bob".into()),
                email: "bob@example.com".into(),
            },
        ],
        sender: Some(Address {
            name: Some("Alice".into()),
            email: "alice@example.com".into(),
        }),
        to: vec![Address {
            name: None,
            email: "rcpt@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Multi from with sender".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let raw = raw_str(&built);

    // From header must list both addresses
    assert!(
        raw.contains("alice@example.com") && raw.contains("bob@example.com"),
        "From header must contain both addresses: {raw}"
    );
    // Sender header must be present
    assert!(
        raw.contains("Sender: Alice <alice@example.com>"),
        "Sender header must be emitted for multi-From \
         (RFC 5322 Section 3.6.2): {raw}"
    );
}

/// RFC 5322 Section 3.6.2: when From contains a single address,
/// Sender SHOULD NOT be present. If provided and identical to From,
/// we omit it. If different, we emit it.
#[test]
fn build_single_from_with_same_sender_omits_sender() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: Some("Alice".into()),
            email: "alice@example.com".into(),
        }],
        sender: Some(Address {
            name: Some("Alice".into()),
            email: "alice@example.com".into(),
        }),
        to: vec![Address {
            name: None,
            email: "rcpt@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Single from same sender".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let raw = raw_str(&built);

    // Sender header must NOT appear when it matches the single From
    // (RFC 5322 Section 3.6.2: "the sender field SHOULD NOT be present")
    assert!(
        !raw.contains("\r\nSender:"),
        "Sender header should be omitted when identical to single From \
         (RFC 5322 Section 3.6.2): {raw}"
    );
}

/// RFC 5322 Section 3.6.2: `Sender` should only be omitted when the
/// single `From` mailbox specification and the `Sender` mailbox
/// specification are identical. A changed display-name makes them
/// different mailbox specifications even if the addr-spec matches.
#[test]
fn build_single_from_with_same_addr_spec_but_different_sender_name_emits_sender() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: Some("Alice Example".into()),
            email: "alice@example.com".into(),
        }],
        sender: Some(Address {
            name: Some("Alice via Assistant".into()),
            email: "alice@example.com".into(),
        }),
        to: vec![Address {
            name: None,
            email: "rcpt@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Single from sender display-name differs".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let raw = raw_str(&built);

    assert!(
        raw.contains("Sender: Alice via Assistant <alice@example.com>"),
        "Sender header must be emitted when the mailbox specification differs \
         even if the addr-spec matches (RFC 5322 Section 3.6.2): {raw}"
    );
}

/// RFC 5322 Section 3.6.2: single From with a different Sender must
/// emit the Sender header.
#[test]
fn build_single_from_with_different_sender_emits_sender() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: Some("Alice".into()),
            email: "alice@example.com".into(),
        }],
        sender: Some(Address {
            name: Some("Secretary".into()),
            email: "secretary@example.com".into(),
        }),
        to: vec![Address {
            name: None,
            email: "rcpt@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Single from different sender".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let raw = raw_str(&built);

    assert!(
        raw.contains("Sender: Secretary <secretary@example.com>"),
        "Sender header must be emitted when different from single From \
         (RFC 5322 Section 3.6.2): {raw}"
    );
}

/// RFC 5322 Section 3.6.2: empty From (no addresses) must return
/// `Error::MissingFrom`.
#[test]
fn build_empty_from_returns_error() {
    let email = OutgoingEmail {
        from: vec![],
        sender: None,
        to: vec![Address {
            name: None,
            email: "rcpt@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "No from".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let result = build_message(&email);
    assert!(
        matches!(result, Err(Error::MissingFrom)),
        "empty From must return MissingFrom (RFC 5322 Section 3.6.2), \
         got: {result:?}"
    );
}

/// RFC 5322 Section 3.6.2: multi-From round-trip — build and parse back,
/// verifying both From addresses and the Sender are preserved.
#[test]
fn build_multi_from_round_trip() {
    let email = OutgoingEmail {
        from: vec![
            Address {
                name: Some("Alice".into()),
                email: "alice@example.com".into(),
            },
            Address {
                name: Some("Bob".into()),
                email: "bob@example.com".into(),
            },
        ],
        sender: Some(Address {
            name: Some("Alice".into()),
            email: "alice@example.com".into(),
        }),
        to: vec![Address {
            name: None,
            email: "rcpt@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "Multi from round-trip".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    // Both From addresses must be parsed back
    assert_eq!(parsed.from.len(), 2, "parsed From must contain 2 addresses");
    assert_eq!(parsed.from[0].email, "alice@example.com");
    assert_eq!(parsed.from[1].email, "bob@example.com");

    // Sender must be parsed back
    assert!(
        parsed.sender.is_some(),
        "parsed Sender must be present for multi-From"
    );
    assert_eq!(parsed.sender.as_ref().unwrap().email, "alice@example.com");
}

/// RFC 5322 Section 3.6.2: Sender address must be validated.
#[test]
fn build_invalid_sender_address_returns_error() {
    let email = OutgoingEmail {
        from: vec![
            Address {
                name: None,
                email: "alice@example.com".into(),
            },
            Address {
                name: None,
                email: "bob@example.com".into(),
            },
        ],
        sender: Some(Address {
            name: None,
            email: "not-valid".into(),
        }),
        to: vec![Address {
            name: None,
            email: "rcpt@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "test".into(),
        body_text: Some("Hello".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };
    let result = build_message(&email);
    assert!(
        matches!(result, Err(Error::InvalidAddress(_))),
        "invalid Sender address must return InvalidAddress, got: {result:?}"
    );
}

/// RFC 2046 Section 5.1.1: boundary MUST NOT appear within the
/// encapsulated material. The fallback path in `generate_boundary_not_in`
/// must check the counter-based boundary against content, not blindly
/// return it.
#[test]
fn generate_boundary_not_in_never_returns_boundary_present_in_content() {
    use std::fmt::Write;

    // Build content that contains a range of fallback boundaries.
    // We embed the exact fallback pattern for many counter values so that
    // if the function returns any of them unchecked, the assertion fails.
    let current = MSG_ID_COUNTER.load(Ordering::Relaxed);
    let mut content = String::new();
    // Cover a wide range around the current counter value so we catch
    // both the random-path boundaries and fallback-path boundaries.
    for i in current..current + 200 {
        let _ = writeln!(content, "----=_Part_fallback_{i:016x}");
    }
    let content_bytes = content.as_bytes();

    let boundary = generate_boundary_not_in(content_bytes);
    assert!(
        !contains_boundary(content_bytes, &boundary),
        "generate_boundary_not_in returned a boundary that appears in the content: {boundary}"
    );
}

/// RFC 5322 Section 3.6: Sender must appear at most once.
/// Adding "Sender" via `extra_headers` when `OutgoingEmail.sender` is set
/// must be rejected to prevent duplicate Sender headers.
#[test]
fn extra_headers_rejects_sender_header() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    // Set the sender field so the builder emits a Sender header automatically.
    email.sender = Some(Address {
        name: Some("Secretary".into()),
        email: "secretary@example.com".into(),
    });
    // Also smuggle a Sender via extra_headers — this must be rejected.
    email.extra_headers = vec![(hdr("Sender"), "evil@example.com".into())];

    let result = build_message(&email);
    assert!(
        result.is_err(),
        "extra_headers must reject 'Sender' because it is a standard header \
         managed by the builder (RFC 5322 Section 3.6)"
    );
}

/// Regression test: when all attachments are inline (`is_inline=true`,
/// `content_id=Some`) but there is no HTML body, the attachments must
/// still appear in the built message. Previously, `has_inline` was
/// gated on `has_html`, and `has_regular` was empty (all went to the
/// inline partition), so `has_attachments` was false and attachments
/// were silently dropped.
#[test]
fn inline_attachment_without_html_not_dropped() {
    let mut email = make_email();
    email.body_text = Some("Plain text body".into());
    email.body_html = None; // no HTML

    email.attachments = vec![OutgoingAttachment {
        filename: "logo.png".into(),
        content_type: "image/png".into(),
        data: vec![0x89, 0x50, 0x4E, 0x47], // PNG magic bytes
        is_inline: true,
        content_id: Some("logo001@example.com".into()),
    }];

    let built = build_message(&email).unwrap();
    let raw = raw_str(&built);

    // The attachment must be present in the built message
    assert!(
        raw.contains("logo.png"),
        "inline attachment filename must appear in the message even without HTML body"
    );

    // Parse it back and verify the attachment is present
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.attachments.len(),
        1,
        "parsed message must contain the inline attachment"
    );
    assert_eq!(parsed.attachments[0].filename.as_deref(), Some("logo.png"));
}

/// Regression test: a non-ASCII subject whose RFC 2047 encoded-word is
/// long enough to force a fold before the first token must not acquire
/// a spurious leading space after round-tripping through build + parse.
///
/// The builder folds `Subject:\r\n =?UTF-8?B?...?=` and the parser's
/// continuation-line handling was preserving the leading whitespace as
/// part of the decoded value. RFC 5322 Section 2.2 says the field body
/// starts after optional whitespace following the colon, so the leading
/// space must be stripped.
#[test]
fn rfc2047_subject_no_spurious_leading_space_after_fold() {
    let mut email = make_email();
    // Non-ASCII subject long enough that "Subject: " (9 chars) +
    // encoded word exceeds the RFC 2047 76-char limit, forcing a fold.
    // Each UTF-8 character is 3 bytes, base64 expands ~4/3, plus 12
    // chars overhead for =?UTF-8?B?...?=. 20 CJK chars should do it:
    // 20 * 3 = 60 bytes -> 80 base64 chars + 12 overhead = 92 chars > 76.
    let subject = "\u{4F60}\u{597D}\u{4E16}\u{754C}\u{4F60}\u{597D}\
                    \u{4E16}\u{754C}\u{4F60}\u{597D}\u{4E16}\u{754C}\
                    \u{4F60}\u{597D}\u{4E16}\u{754C}\u{4F60}\u{597D}\
                    \u{4E16}\u{754C}";
    email.subject = subject.to_string();
    email.body_text = Some("body".into());

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    let parsed_subject = parsed.subject.unwrap();
    assert!(
        !parsed_subject.starts_with(' '),
        "parsed subject must not have a leading space; got: {parsed_subject:?}"
    );
    assert_eq!(
        parsed_subject, subject,
        "round-tripped subject must match original"
    );
}

/// Long non-ASCII filenames must use RFC 2231 continuation parameters
/// to avoid producing header lines that exceed the 998-character hard
/// limit (RFC 5322 Section 2.1.1). Without continuation, the
/// `filename*=UTF-8''<percent-encoded>` parameter can become a single
/// word exceeding 998 chars, and `force_fold_word` inserts `\r\n ` that
/// corrupts the parameter value (the space becomes part of the decoded
/// filename after RFC 5322 Section 2.2.3 unfolding).
///
/// RFC 2231 Section 3: "Long MIME media type or disposition parameter
/// values [...] can be split into smaller segments".
#[test]
fn build_long_non_ascii_filename_lines_within_limit() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    // 400 CJK characters → each is 3 UTF-8 bytes → 1200 bytes.
    // Each byte percent-encodes to 3 chars → up to 3600 chars encoded.
    // filename*=UTF-8''<3600 chars> far exceeds the 998-char hard limit.
    let long_name: String = "".repeat(400);
    let filename = format!("{long_name}.txt");
    email.attachments = vec![OutgoingAttachment {
        filename: filename.clone(),
        content_type: "application/octet-stream".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).expect("build must succeed");

    // Every line in the output must be ≤ 998 characters (excluding CRLF).
    // RFC 5322 Section 2.1.1: "Each line of characters MUST be no more
    // than 998 characters [...] excluding the CRLF."
    let raw = raw_str(&built);
    for (i, line) in raw.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "line {} is {} chars (max 998): {:?}",
            i + 1,
            line.len(),
            &line[..line.len().min(120)],
        );
    }

    // The encoded filename must round-trip through the parser.
    let parsed = crate::parse_email(&built.raw).expect("parse must succeed");
    assert_eq!(parsed.attachments.len(), 1);
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some(filename.as_str()),
        "Long non-ASCII filename must round-trip through RFC 2231 \
         continuation parameters"
    );
}

/// RFC 2231 Section 3 continuation parameters: the builder must split
/// long encoded filenames into numbered sections (`filename*0*=`,
/// `filename*1*=`, etc.) and the parser must reassemble them.
#[test]
fn build_long_non_ascii_filename_uses_continuation() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    let long_name: String = "é".repeat(200);
    let filename = format!("{long_name}.pdf");
    email.attachments = vec![OutgoingAttachment {
        filename: filename.clone(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).expect("build must succeed");
    let raw = raw_str(&built);

    // With 200 'é' chars (each → %C3%A9 = 6 chars = 1200 chars encoded),
    // the encoded filename far exceeds a single parameter's capacity.
    // The builder must use continuation parameters.
    assert!(
        raw.contains("filename*0*=UTF-8''"),
        "Long filename must use RFC 2231 continuation (filename*0*=), got: \
         {raw}",
    );

    // Round-trip
    let parsed = crate::parse_email(&built.raw).expect("parse must succeed");
    assert_eq!(parsed.attachments.len(), 1);
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some(filename.as_str()),
    );
}

/// RFC 2183 page 3 says disposition parameter values longer than 78
/// characters "MUST be encoded" using the RFC 2231 continuation
/// mechanism. A long ASCII filename that still fits under the RFC 5322
/// 998-octet hard line limit must therefore use `filename*0*=...`,
/// not a plain `filename="..."` quoted-string.
#[test]
fn build_medium_long_ascii_filename_uses_rfc2231_in_content_disposition() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    let filename = format!("{}.txt", "a".repeat(90));
    email.attachments = vec![OutgoingAttachment {
        filename: filename.clone(),
        content_type: "application/octet-stream".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).expect("build must succeed");
    let raw = raw_str(&built);

    assert!(
        raw.contains("Content-Disposition: attachment;\r\n filename*0*=UTF-8''")
            || raw.contains("Content-Disposition: attachment; filename*0*=UTF-8''"),
        "long ASCII Content-Disposition filename must use RFC 2231 continuation: {raw}"
    );
    assert!(
        !raw.contains(&format!(
            "Content-Disposition: attachment; filename=\"{filename}\""
        )),
        "long ASCII Content-Disposition filename must not use plain quoted-string: {raw}"
    );

    let parsed = crate::parse_email(&built.raw).expect("parse must succeed");
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some(filename.as_str())
    );
}

/// RFC 2231 Section 3 applies equally to media type parameters.
/// `Content-Type: ...; name="..."` must switch to `name*0*=...` when the
/// ASCII filename exceeds the 78-character limit from RFC 2183.
#[test]
fn build_medium_long_ascii_filename_uses_rfc2231_in_content_type_name() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    let filename = format!("{}.pdf", "b".repeat(90));
    email.attachments = vec![OutgoingAttachment {
        filename: filename.clone(),
        content_type: "application/pdf".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).expect("build must succeed");
    let raw = raw_str(&built);

    assert!(
        raw.contains("Content-Type: application/pdf;\r\n name*0*=UTF-8''")
            || raw.contains("Content-Type: application/pdf; name*0*=UTF-8''"),
        "long ASCII Content-Type name parameter must use RFC 2231 continuation: {raw}"
    );
    assert!(
        !raw.contains(&format!(
            "Content-Type: application/pdf; name=\"{filename}\""
        )),
        "long ASCII Content-Type name parameter must not use plain quoted-string: {raw}"
    );
}

/// Long ASCII filenames must also switch to RFC 2231 continuation syntax
/// when a single `filename="..."` parameter would exceed the RFC 5322
/// hard line limit. RFC 2231 Section 3 applies to long parameter values
/// regardless of whether they contain non-ASCII octets.
#[test]
fn build_long_ascii_filename_lines_within_limit() {
    let mut email = make_email();
    email.body_text = Some("Body".into());
    let long_name = "a".repeat(1200);
    let filename = format!("{long_name}.txt");
    email.attachments = vec![OutgoingAttachment {
        filename: filename.clone(),
        content_type: "application/octet-stream".into(),
        data: b"data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).expect("build must succeed");

    let raw = raw_str(&built);
    for (i, line) in raw.split("\r\n").enumerate() {
        assert!(
            line.len() <= 998,
            "line {} is {} chars (max 998): {:?}",
            i + 1,
            line.len(),
            &line[..line.len().min(120)],
        );
    }

    let parsed = crate::parse_email(&built.raw).expect("parse must succeed");
    assert_eq!(parsed.attachments.len(), 1);
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some(filename.as_str()),
        "Long ASCII filename must round-trip through RFC 2231 \
         continuation parameters"
    );
}

/// Regression test: `is_valid_msg_id` must reject message-IDs containing
/// whitespace, control characters, or angle brackets, which would break
/// the `<msg-id>` wire syntax per RFC 5322 Section 3.6.4.
#[test]
fn test_msg_id_validation_rejects_bad_chars() {
    let mut email = make_email();
    email.body_text = Some("test".into());

    // Mix of invalid and valid message-IDs supplied via in_reply_to.
    email.in_reply_to = vec![
        mid("hello world@example.com"), // space in id-left
        mid("test@exam ple.com"),       // space in id-right
        mid("test\x01@domain.com"),     // control char in id-left
        mid("a<b@domain.com"),          // angle bracket in id-left
        mid("unique123@domain.com"),    // valid
        mid("abc.def@example.org"),     // valid
    ];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Only the two valid IDs should survive.
    assert!(
        s.contains("<unique123@domain.com>"),
        "valid msg-id must be present"
    );
    assert!(
        s.contains("<abc.def@example.org>"),
        "valid msg-id must be present"
    );

    // Invalid IDs must NOT appear in the output.
    assert!(
        !s.contains("hello world@example.com"),
        "msg-id with space in id-left must be rejected"
    );
    assert!(
        !s.contains("exam ple.com"),
        "msg-id with space in id-right must be rejected"
    );
    assert!(
        !s.contains("test\x01@domain.com"),
        "msg-id with control char must be rejected"
    );
    assert!(
        !s.contains("a<b@domain.com"),
        "msg-id with angle bracket must be rejected"
    );
}

/// RFC 2047 Section 2: the 76-character line limit applies only to lines
/// that contain actual encoded-words (`=?charset?encoding?text?=`).
/// Plain text that coincidentally contains the substrings `=?` and `?=`
/// is NOT an encoded-word and must use the standard 78-char fold limit
/// (RFC 5322 Section 2.1.1).
///
/// Regression: `write_header` previously used a loose heuristic
/// (`value.contains("=?") && value.contains("?=")`) which triggered
/// false positives on ordinary text, folding at 76 instead of 78.
#[test]
fn write_header_no_false_positive_encoded_word_detection() {
    // Value with literal "=?" and "?=" that are NOT RFC 2047 encoded-words.
    // Carefully constructed so that "Subject: " (9) + words up to "?="
    // produces line_len = 73, then the next word "bbb" (sep+len = 4)
    // gives 77: exceeds the 76-char limit but fits within 78.
    let plain_value = "aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii jjjj kkkk =? lll ?= bbb pppp";

    let mut output = Vec::new();
    write_header(&mut output, "Subject", plain_value);
    let header = String::from_utf8(output).unwrap();

    let first_line = header.split("\r\n").next().unwrap();
    assert!(
        first_line.len() == 77,
        "RFC 2047 Section 2: plain text with literal '=?' and '?=' must \
         fold at 78, not 76. First line should be 77 chars but is {} chars: {:?}",
        first_line.len(),
        first_line,
    );

    // Sanity: a real encoded-word SHOULD use the 76-char limit.
    // Same structure but with a valid =?UTF-8?B?...?= token.
    let encoded_value =
        "aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii =?UTF-8?B?dGVzdA==?= jj kkkk llll";

    let mut output2 = Vec::new();
    write_header(&mut output2, "Subject", encoded_value);
    let header2 = String::from_utf8(output2).unwrap();
    let first_line_enc = header2.split("\r\n").next().unwrap();
    assert!(
        first_line_enc.len() <= 76,
        "RFC 2047 Section 2: lines with real encoded-words must fold at ≤76. \
         First line is {} chars: {:?}",
        first_line_enc.len(),
        first_line_enc,
    );
}

/// RFC 2046 Section 5.1.1: "The boundary delimiter MUST NOT appear within
/// the encapsulated material." `generate_boundary_not_in` must always
/// return a boundary that does not collide with the content, even when
/// the content contains boundary-like patterns.
///
/// Regression: the final fallback path previously returned a counter-based
/// boundary without verifying it against the content.
#[test]
fn generate_boundary_not_in_never_collides() {
    // Content with several boundary-like patterns embedded
    let content = b"Here is some text with ----=_Part_fallback_0000000000000001 \
        and ----=_Part_ mixed in for good measure";
    let boundary = generate_boundary_not_in(content);
    assert!(
        !contains_boundary(content, &boundary),
        "RFC 2046 Section 5.1.1: generated boundary must not appear in \
         the content. Got: {boundary:?}"
    );
}

/// RFC 2046 Section 5.1.1: when content happens to contain the exact
/// boundary string that would have been generated, the function must
/// generate a different one.
#[test]
fn generate_boundary_not_in_avoids_existing_boundary() {
    // Generate a boundary first, then embed it in content and regenerate.
    let first = generate_boundary_not_in(b"");
    let content = format!("Body text contains {first} in the middle");
    let second = generate_boundary_not_in(content.as_bytes());
    assert_ne!(
        first, second,
        "must generate a different boundary when the first collides"
    );
    assert!(
        !contains_boundary(content.as_bytes(), &second),
        "RFC 2046 Section 5.1.1: regenerated boundary must not appear in content"
    );
}

#[test]
fn msg_id_rejects_specials_rfc5322_section_3_6_4() {
    // RFC 5322 Section 3.6.4: msg-id = "<" id-left "@" id-right ">"
    // id-left must be dot-atom-text; id-right may be dot-atom-text or
    // no-fold-literal. Characters like (, ), :, ;, ,, SP, DQUOTE, and
    // "\" are not valid in dot-atom-text and must be rejected.

    // These should be rejected (contain specials not in atext):
    assert!(
        !is_valid_msg_id("user(comment)@example.com"),
        "parentheses are specials"
    );
    assert!(
        !is_valid_msg_id("user:name@example.com"),
        "colon is a special"
    );
    assert!(
        !is_valid_msg_id("user;name@example.com"),
        "semicolon is a special"
    );
    assert!(
        !is_valid_msg_id("user,name@example.com"),
        "comma is a special"
    );
    assert!(
        !is_valid_msg_id("user name@example.com"),
        "space not allowed"
    );
    assert!(
        !is_valid_msg_id("user\"name@example.com"),
        "double-quote is a special"
    );
    assert!(
        !is_valid_msg_id("user\\name@example.com"),
        "backslash is a special"
    );

    // dot-atom-text: no leading, trailing, or consecutive dots
    assert!(!is_valid_msg_id(".user@example.com"), "leading dot");
    assert!(
        !is_valid_msg_id("user.@example.com"),
        "trailing dot in id-left"
    );
    assert!(
        !is_valid_msg_id("user@.example.com"),
        "leading dot in id-right"
    );
    assert!(
        !is_valid_msg_id("user@example.com."),
        "trailing dot in id-right"
    );
    assert!(
        !is_valid_msg_id("user..name@example.com"),
        "consecutive dots"
    );
    assert!(
        !is_valid_msg_id("user@example..com"),
        "consecutive dots in id-right"
    );

    // These should be accepted (valid atext + dots):
    assert!(is_valid_msg_id("user@example.com"));
    assert!(is_valid_msg_id("user.name@example.com"));
    assert!(is_valid_msg_id("abc123+def@host.example.org"));
    assert!(is_valid_msg_id("a!b#c$d%e&f@g.h"));
    assert!(is_valid_msg_id("user@[127.0.0.1]"));
    assert!(is_valid_msg_id("user@[IPv6:2001:db8::1]"));
}

/// RFC 6531 Section 3.3: internationalized local-parts containing
/// non-ASCII (UTF-8) characters must be accepted by `validate_address`.
#[test]
fn test_validate_address_allows_non_ascii_local_part_rfc6531() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "josé@example.com".into(),
        }],
        to: vec![Address {
            name: None,
            email: "user@example.com".into(),
        }],
        subject: "test".into(),
        body_text: Some("hello".into()),
        body_html: None,
        attachments: vec![],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        sender: None,
        date: None,
        in_reply_to: vec![],
        references: vec![],
        extra_headers: vec![],
    };
    // Must not return InvalidAddress for non-ASCII local-part
    assert!(
        build_message(&email).is_ok(),
        "RFC 6531 Section 3.3: non-ASCII local-part should be accepted"
    );
}

#[test]
fn test_format_address_quotes_encoded_word_lookalike() {
    // RFC 2047 Section 5: a display name that literally looks like an
    // encoded-word must be quoted to prevent the parser from decoding it.
    let addr = Address {
        name: Some("=?UTF-8?B?SGVsbG8=?=".into()),
        email: "user@example.com".into(),
    };
    let email = OutgoingEmail {
        from: vec![addr],
        to: vec![Address {
            name: None,
            email: "dest@example.com".into(),
        }],
        subject: "test".into(),
        body_text: Some("hello".into()),
        body_html: None,
        attachments: vec![],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        sender: None,
        date: None,
        in_reply_to: vec![],
        references: vec![],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();
    // Round-trip must preserve the literal display name
    assert_eq!(
        parsed.from[0].name.as_deref(),
        Some("=?UTF-8?B?SGVsbG8=?="),
        "display name containing encoded-word syntax must round-trip unchanged"
    );
}

/// RFC 6532 Section 3.5: msg-id allows UTF-8 characters in
/// internationalized messages. Non-ASCII message-IDs must not be
/// silently dropped from In-Reply-To or References headers.
#[test]
fn test_non_ascii_message_id_in_reply_to_rfc6532() {
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: "user@example.com".into(),
        }],
        to: vec![Address {
            name: None,
            email: "dest@example.com".into(),
        }],
        subject: "test".into(),
        body_text: Some("hello".into()),
        body_html: None,
        attachments: vec![],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        sender: None,
        date: None,
        in_reply_to: vec![mid("réponse@example.com")],
        references: vec![mid("référence@example.com")],
        extra_headers: vec![],
    };
    let built = build_message(&email).unwrap();
    let raw = String::from_utf8_lossy(&built.raw);
    // Non-ASCII message-IDs must not be silently dropped
    assert!(
        raw.contains("<réponse@example.com>"),
        "In-Reply-To must include non-ASCII message-ID per RFC 6532 Section 3.5"
    );
    assert!(
        raw.contains("<référence@example.com>"),
        "References must include non-ASCII message-ID per RFC 6532 Section 3.5"
    );
}

/// RFC 2047 Section 5: a Subject (or extra header) whose value is pure
/// ASCII but contains a pattern that looks like an encoded-word
/// (`=?charset?encoding?text?=`) must not be emitted verbatim. If it
/// is, the parser will decode the encoded-word on read-back, causing
/// round-trip data loss. The builder must RFC 2047-encode such values
/// so the literal text survives parsing.
#[test]
fn subject_with_encoded_word_lookalike_round_trips() {
    let mut email = make_email();
    email.subject = "=?UTF-8?Q?test?= literal".into();
    email.body_text = Some("body".into());

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(
        parsed.subject.as_deref(),
        Some("=?UTF-8?Q?test?= literal"),
        "Subject containing encoded-word syntax must round-trip unchanged \
         (RFC 2047 Section 5)"
    );
}

/// Same as above but for extra headers: an extra header value that
/// contains encoded-word syntax must be protected by RFC 2047 encoding
/// so the literal text survives a build-then-parse round-trip.
#[test]
fn extra_header_with_encoded_word_lookalike_round_trips() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(hdr("X-Custom"), "=?UTF-8?B?SGVsbG8=?= world".into())];

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    // Parser lowercases header names (RFC 5322 Section 2.2: field
    // names are case-insensitive).
    let custom = parsed
        .extra_headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("X-Custom"))
        .map(|(_, v)| v.as_str());
    assert_eq!(
        custom,
        Some("=?UTF-8?B?SGVsbG8=?= world"),
        "Extra header containing encoded-word syntax must round-trip unchanged \
         (RFC 2047 Section 5)"
    );
}

// =================================================================
// Workspace audit: edge-case probe tests
// =================================================================

/// RFC 2231 Section 3-4: build a message with a long non-ASCII filename,
/// then parse it back. The filename uses RFC 2231 continuation parameters
/// during encoding and must survive the round-trip intact.
#[test]
fn audit_rfc2231_round_trip_long_non_ascii_filename() {
    let long_name = "файл_с_очень_длинным_именем_который_будет_закодирован_через_rfc2231.pdf";
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.attachments = vec![OutgoingAttachment {
        filename: long_name.into(),
        content_type: "application/pdf".into(),
        data: b"fake pdf".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(parsed.attachments.len(), 1);
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some(long_name),
        "RFC 2231 filename round-trip failed"
    );
}

/// RFC 2047 Section 2: build a message with a non-ASCII subject requiring
/// RFC 2047 Base64 encoding, then parse it back. The subject must
/// survive the round-trip intact.
#[test]
fn audit_rfc2047_round_trip_non_ascii_subject() {
    let subject = "日本語のテスト件名: Ärger mit Ümlauten";
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.subject = subject.into();

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.subject.as_deref(),
        Some(subject),
        "RFC 2047 subject round-trip failed"
    );
}

/// RFC 5322 Section 3.6.3: a message with only BCC recipients (no To
/// or Cc) is valid. BCC must appear in the envelope but NOT in headers.
#[test]
fn audit_bcc_only_message_valid() {
    let mut email = make_email();
    email.to.clear();
    email.bcc = vec![Address {
        name: None,
        email: "hidden@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = String::from_utf8_lossy(&built.raw);

    assert!(!s.contains("Bcc:"), "BCC header must not appear in message");
    assert!(
        !s.contains("hidden@example.com"),
        "BCC address must not appear in headers"
    );
    assert!(
        built
            .envelope_recipients
            .contains(&"hidden@example.com".to_string()),
        "BCC must be in envelope recipients"
    );
}

/// RFC 5322 Section 3.6.3: a message with only CC recipients (no To)
/// is valid. The Cc header should be present, and no To header should
/// appear.
#[test]
fn audit_cc_only_message_valid() {
    let mut email = make_email();
    email.to.clear();
    email.cc = vec![Address {
        name: None,
        email: "cc@example.com".into(),
    }];

    let built = build_message(&email).unwrap();
    let s = String::from_utf8_lossy(&built.raw);

    assert!(s.contains("Cc: cc@example.com"), "Cc header missing");
    assert!(
        !s.contains("\r\nTo:"),
        "To header should not appear when no To recipients"
    );
}

/// RFC 2045 Section 2.7: pure ASCII text must produce
/// `Content-Transfer-Encoding: 7bit`.
#[test]
fn audit_seven_bit_encoding_ascii_uses_7bit() {
    let mut email = make_email();
    email.body_text = Some("Pure ASCII text here".into());

    let built = build_message(&email).unwrap();
    let s = String::from_utf8_lossy(&built.raw);
    assert!(
        s.contains("Content-Transfer-Encoding: 7bit"),
        "Pure ASCII with SevenBit should use 7bit CTE, got: {s}"
    );
}

/// RFC 2045 Section 6.7: non-ASCII text must produce
/// `Content-Transfer-Encoding: quoted-printable`.
#[test]
fn audit_seven_bit_encoding_non_ascii_uses_qp() {
    let mut email = make_email();
    email.body_text = Some("Héllo Wörld with non-ASCII".into());

    let built = build_message(&email).unwrap();
    let s = String::from_utf8_lossy(&built.raw);
    assert!(
        s.contains("Content-Transfer-Encoding: quoted-printable"),
        "Non-ASCII with SevenBit should use quoted-printable CTE, got: {s}"
    );
}

/// Comprehensive round-trip: build a complex message with non-ASCII
/// subject (RFC 2047), non-ASCII display names (RFC 2047), text + HTML
/// bodies, threading headers (RFC 5322 Section 3.6.4), and a non-ASCII
/// attachment filename (RFC 2231). Parse it back and verify all fields.
#[test]
fn audit_full_complex_round_trip() {
    let mut email = make_email();
    email.from = vec![Address {
        name: Some("José García".into()),
        email: "jose@example.com".into(),
    }];
    email.to = vec![Address {
        name: Some("Müller".into()),
        email: "muller@example.com".into(),
    }];
    email.subject = "Ärger mit Ümlauten — a test".into();
    email.body_text = Some("Plain text body with UTF-8: café".into());
    email.body_html = Some("<p>HTML body with UTF-8: café</p>".into());
    email.in_reply_to = vec![mid("parent@example.com")];
    email.references = vec![mid("root@example.com"), mid("parent@example.com")];
    email.attachments = vec![OutgoingAttachment {
        filename: "données.txt".into(),
        content_type: "text/plain".into(),
        data: b"file data".to_vec(),
        is_inline: false,
        content_id: None,
    }];

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    // Subject
    assert_eq!(
        parsed.subject.as_deref(),
        Some("Ärger mit Ümlauten — a test"),
        "Subject round-trip failed"
    );
    // Bodies
    assert_eq!(
        parsed.body_text.as_deref(),
        Some("Plain text body with UTF-8: café"),
        "body_text round-trip failed"
    );
    assert_eq!(
        parsed.body_html.as_deref(),
        Some("<p>HTML body with UTF-8: café</p>"),
        "body_html round-trip failed"
    );
    // Addresses
    assert_eq!(parsed.from[0].email, "jose@example.com");
    assert_eq!(
        parsed.from[0].name.as_deref(),
        Some("José García"),
        "From display name round-trip failed"
    );
    assert_eq!(parsed.to[0].email, "muller@example.com");
    // Threading
    assert_eq!(parsed.in_reply_to, vec!["parent@example.com"]);
    assert_eq!(
        parsed.references,
        vec!["root@example.com", "parent@example.com"]
    );
    // Attachment
    assert_eq!(parsed.attachments.len(), 1);
    assert_eq!(
        parsed.attachments[0].filename.as_deref(),
        Some("données.txt"),
        "Attachment filename round-trip failed"
    );
}

/// Boundary strings containing RFC 2045 special characters (`+`, `/`,
/// `.`, `=`) must be correctly handled by the parser's boundary
/// detection (RFC 2046 Section 5.1.1).
#[test]
fn audit_boundary_with_special_chars() {
    let raw = b"From: a@b.com\r\n\
                 Content-Type: multipart/mixed; boundary=\"=_Part+/test.boundary\"\r\n\
                 \r\n\
                 --=_Part+/test.boundary\r\n\
                 Content-Type: text/plain\r\n\
                 \r\n\
                 Hello\r\n\
                 --=_Part+/test.boundary--";
    let parsed = crate::parse_email(raw).unwrap();
    assert_eq!(parsed.body_text.as_deref(), Some("Hello"));
}

/// Body text containing literal `=?charset?encoding?text?=` syntax must
/// be preserved as-is — RFC 2047 encoded-words only apply to header
/// field bodies, not message body content (RFC 2047 Section 1).
#[test]
fn audit_body_with_encoded_word_syntax_preserved() {
    let mut email = make_email();
    email.body_text = Some("The value is =?UTF-8?B?dGVzdA==?= literally".into());

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.body_text.as_deref(),
        Some("The value is =?UTF-8?B?dGVzdA==?= literally"),
        "Body with =? syntax should be preserved literally"
    );
}

/// RFC 5322 Section 3.6.2: when From has multiple addresses, Sender
/// must be present. Both From addresses and the Sender must survive
/// the build→parse round trip.
#[test]
fn audit_multiple_from_with_sender_round_trip() {
    let mut email = make_email();
    email.from = vec![
        Address {
            name: Some("Alice".into()),
            email: "alice@example.com".into(),
        },
        Address {
            name: Some("Bob".into()),
            email: "bob@example.com".into(),
        },
    ];
    email.sender = Some(Address {
        name: None,
        email: "alice@example.com".into(),
    });
    email.body_text = Some("body".into());

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    assert_eq!(
        parsed.from.len(),
        2,
        "Both From addresses must be preserved"
    );
    assert_eq!(parsed.from[0].email, "alice@example.com");
    assert_eq!(parsed.from[1].email, "bob@example.com");
    assert!(parsed.sender.is_some(), "Sender must be present");
    assert_eq!(parsed.sender.as_ref().unwrap().email, "alice@example.com");
}

/// RFC 5322 Section 2.2.3: header folding with HTAB continuation must
/// be correctly unfolded by the parser.
#[test]
fn audit_header_folding_with_htab_continuation() {
    let raw = b"From: sender@example.com\r\n\
                 Subject: Hello\r\n\t World\r\n\
                 Date: Thu, 13 Feb 2025 15:47:33 +0000\r\n\
                 \r\n\
                 body";
    let parsed = crate::parse_email(raw).unwrap();
    assert!(
        parsed.subject.as_deref().unwrap().contains("World"),
        "Subject must include continuation value after HTAB fold"
    );
}

/// RFC 2047 Section 5 / RFC 5322 Section 2.2: extra header values
/// containing non-ASCII characters must be RFC 2047 encoded in the
/// raw output, since header field bodies must be US-ASCII.
#[test]
fn build_extra_header_non_ascii_is_rfc2047_encoded() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(hdr("X-Custom"), "Caf\u{e9} r\u{e9}sum\u{e9}".into())];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The raw output must contain RFC 2047 encoded-word syntax
    // (RFC 2047 Section 2: encoded-word = "=?" charset "?" encoding "?" encoded-text "?=")
    assert!(
        s.contains("X-Custom: =?UTF-8?B?"),
        "Non-ASCII extra header value must be RFC 2047 Base64 encoded \
         (RFC 2047 Section 5, RFC 5322 Section 2.2): {s}"
    );
    assert!(
        s.contains("?="),
        "RFC 2047 encoded word must have closing delimiter: {s}"
    );
    // The raw output must NOT contain the literal non-ASCII bytes
    // in the header line (they would violate RFC 5322 Section 2.2).
    let header_line = s
        .lines()
        .find(|l| l.starts_with("X-Custom:"))
        .expect("X-Custom header must be present");
    assert!(
        header_line.is_ascii(),
        "Extra header line must be pure ASCII after RFC 2047 encoding \
         (RFC 5322 Section 2.2): {header_line}"
    );
}

/// RFC 2047 Section 5 / RFC 5322 Section 2.2: extra headers with
/// non-ASCII values must round-trip through build -> parse correctly.
/// The builder RFC 2047-encodes, and the parser decodes back to the
/// original Unicode text.
#[test]
fn build_extra_header_non_ascii_round_trip() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    let original_value = "Caf\u{e9} r\u{e9}sum\u{e9}";
    email.extra_headers = vec![(hdr("X-Custom"), original_value.into())];

    let built = build_message(&email).unwrap();
    let parsed = crate::parse_email(&built.raw).unwrap();

    // The parser must decode the RFC 2047 encoded-word back to the
    // original Unicode value (RFC 2047 Section 6.1).
    let custom = parsed
        .extra_headers
        .iter()
        .find(|(k, _)| k == "x-custom")
        .expect("x-custom header must be present in parsed extra_headers");
    assert_eq!(
        custom.1, original_value,
        "Non-ASCII extra header must round-trip through RFC 2047 encode/decode: \
         expected {original_value:?}, got {:?}",
        custom.1
    );
}

/// RFC 2047 Section 5 forbids encoded-words in structured field bodies
/// such as `Return-Path`; RFC 6532 Sections 3.2 and 3.6 permit direct
/// UTF-8 instead for internationalized headers.
#[test]
fn build_structured_extra_header_preserves_utf8_without_rfc2047() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Return-Path"), "<us\u{00E9}r@example.com>".into()),
        (
            hdr("Received"),
            "from mx.example by inbox.example; Fri, 21 Nov 1997 09:55:06 -0600".into(),
        ),
    ];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    let header_line = s
        .lines()
        .find(|l| l.starts_with("Return-Path:"))
        .expect("Return-Path header must be present");
    assert!(
        header_line.contains("<us\u{00E9}r@example.com>"),
        "Structured Return-Path must preserve raw UTF-8, not rewrite the field body: {header_line}"
    );
    assert!(
        !header_line.contains("=?UTF-8?"),
        "Structured Return-Path must not use RFC 2047 encoded-words (RFC 2047 Section 5): {header_line}"
    );
}

/// RFC 2047 Section 5 forbids encoded-words in address-field bodies such
/// as `Resent-From`; RFC 6532 Sections 3.2 and 3.6 permit direct UTF-8
/// instead. The builder must not RFC 2047-encode the entire field body.
#[test]
fn build_structured_resent_from_extra_header_preserves_utf8_without_rfc2047() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "Jos\u{00E9} <jose@example.com>".into()),
    ];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    let header_line = s
        .lines()
        .find(|l| l.starts_with("Resent-From:"))
        .expect("Resent-From header must be present");
    assert!(
        header_line.contains("Jos\u{00E9} <jose@example.com>"),
        "Structured Resent-From must preserve raw UTF-8 address syntax, not rewrite the field body: {header_line}"
    );
    assert!(
        !header_line.contains("=?UTF-8?"),
        "Structured Resent-From must not use RFC 2047 encoded-words (RFC 2047 Section 5): {header_line}"
    );
}

/// RFC 5322 Section 3.6.7 / RFC 5321 Section 4.4: trace fields are a
/// `[Return-Path] 1*Received` block prepended to the message, with
/// `Return-Path` at the beginning of the trace block.
#[test]
fn return_path_extra_header_is_prepended_before_generated_headers() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Return-Path"), "<bounce@example.com>".into()),
        (
            hdr("Received"),
            "from mx.example by inbox.example; Fri, 21 Nov 1997 09:55:06 -0600".into(),
        ),
    ];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    let header_lines: Vec<&str> = s
        .split("\r\n")
        .take_while(|line| !line.is_empty())
        .collect();

    assert_eq!(
        header_lines.first().copied(),
        Some("Return-Path: <bounce@example.com>"),
        "Return-Path must be emitted before From/Date/Message-ID per RFC 5321 Section 4.4: {header_lines:?}"
    );
    assert!(
        header_lines
            .get(1)
            .is_some_and(|line| line.starts_with("Received: from mx.example by inbox.example;")),
        "Received must immediately follow Return-Path in the prepended trace block: {header_lines:?}"
    );
}

/// RFC 5322 Section 3.6.7 defines trace as `[Return-Path] 1*Received`,
/// so a standalone `Return-Path` header is invalid.
#[test]
fn return_path_extra_header_requires_received_header() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(hdr("Return-Path"), "<bounce@example.com>".into())];

    let err = build_message(&email)
        .expect_err("Return-Path without Received must be rejected per RFC 5322 Section 3.6.7");

    assert!(
        matches!(err, Error::InvalidTraceHeader(ref message) if message.contains("Return-Path") && message.contains("Received")),
        "expected InvalidTraceHeader error mentioning Return-Path and Received, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.7 allows at most one optional `Return-Path`
/// field in the trace block.
#[test]
fn return_path_extra_header_rejects_duplicates() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Return-Path"), "<bounce-1@example.com>".into()),
        (
            hdr("Received"),
            "from mx.example by inbox.example; Fri, 21 Nov 1997 09:55:06 -0600".into(),
        ),
        (hdr("Return-Path"), "<bounce-2@example.com>".into()),
    ];

    let err = build_message(&email)
        .expect_err("duplicate Return-Path headers must be rejected per RFC 5322 Section 3.6.7");

    assert!(
        matches!(err, Error::InvalidTraceHeader(ref message) if message.contains("at most one Return-Path")),
        "expected InvalidTraceHeader error mentioning duplicate Return-Path, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.7 defines `path` as an angle-addr (or null path),
/// so `Return-Path` must not accept arbitrary unbracketed text.
#[test]
fn return_path_extra_header_rejects_invalid_path() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Return-Path"), "not-an-angle-addr".into()),
        (
            hdr("Received"),
            "from mx.example by inbox.example; Fri, 21 Nov 1997 09:55:06 -0600".into(),
        ),
    ];

    let err = build_message(&email)
        .expect_err("invalid Return-Path path must be rejected per RFC 5322 Section 3.6.7");

    assert!(
        matches!(err, Error::InvalidTraceHeader(ref message) if message.contains("Return-Path")),
        "expected InvalidTraceHeader error mentioning Return-Path, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.7 requires every `Received` field to end with a
/// semicolon plus `date-time`.
#[test]
fn received_extra_header_requires_semicolon_date_time() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(hdr("Received"), "from mx.example by inbox.example".into())];

    let err = build_message(&email)
        .expect_err("Received without '; date-time' must be rejected per RFC 5322 Section 3.6.7");

    assert!(
        matches!(err, Error::InvalidTraceHeader(ref message) if message.contains("Received")),
        "expected InvalidTraceHeader error mentioning Received, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.7 requires the `Received` tail after the final
/// semicolon to be a syntactically valid `date-time`.
#[test]
fn received_extra_header_rejects_invalid_date_time() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(
        hdr("Received"),
        "from mx.example by inbox.example; not-a-date".into(),
    )];

    let err = build_message(&email)
        .expect_err("Received with invalid date-time must be rejected per RFC 5322 Section 3.6.7");

    assert!(
        matches!(err, Error::InvalidTraceHeader(ref message) if message.contains("Received")),
        "expected InvalidTraceHeader error mentioning Received, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6: when resent fields are present, the resent
/// block must be prepended ahead of the original header block.
#[test]
fn resent_extra_headers_are_prepended_before_original_headers() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "Jos\u{00E9} <jose@example.com>".into()),
    ];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);
    let header_lines: Vec<&str> = s
        .split("\r\n")
        .take_while(|line| !line.is_empty())
        .collect();

    let resent_date_pos = header_lines
        .iter()
        .position(|line| line.starts_with("Resent-Date:"))
        .expect("Resent-Date header must be present");
    let resent_from_pos = header_lines
        .iter()
        .position(|line| line.starts_with("Resent-From:"))
        .expect("Resent-From header must be present");
    let from_pos = header_lines
        .iter()
        .position(|line| line.starts_with("From:"))
        .expect("From header must be present");
    let date_pos = header_lines
        .iter()
        .position(|line| line.starts_with("Date:"))
        .expect("Date header must be present");

    assert!(
        resent_date_pos < from_pos && resent_from_pos < date_pos,
        "Resent block must be prepended before the original headers per RFC 5322 Section 3.6.6: {header_lines:?}"
    );
}

/// RFC 5322 Section 4.5.6 treats obsolete `Resent-Reply-To` as resent
/// trace information, so it belongs in the prepended resent block rather
/// than the ordinary optional-field section. RFC 2047 Section 5 also
/// forbids encoded-words in this structured address field.
#[test]
fn resent_reply_to_extra_header_is_grouped_and_preserves_raw_utf8() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "Alice <alice@example.com>".into()),
        (
            hdr("Resent-Reply-To"),
            "Rel\u{00E9} Desk <relay@example.com>".into(),
        ),
    ];

    let built = build_message(&email)
        .expect("obsolete Resent-Reply-To should be accepted as part of the resent block");
    let s = raw_str(&built);
    let header_lines: Vec<&str> = s
        .split("\r\n")
        .take_while(|line| !line.is_empty())
        .collect();

    let resent_reply_to_pos = header_lines
        .iter()
        .position(|line| line.starts_with("Resent-Reply-To:"))
        .expect("Resent-Reply-To header must be present");
    let from_pos = header_lines
        .iter()
        .position(|line| line.starts_with("From:"))
        .expect("From header must be present");
    let resent_reply_to_line = header_lines[resent_reply_to_pos];

    assert!(
        resent_reply_to_pos < from_pos,
        "Resent-Reply-To must be prepended with the resent block per RFC 5322 Section 4.5.6: {header_lines:?}"
    );
    assert!(
        resent_reply_to_line.contains("Rel\u{00E9} Desk <relay@example.com>"),
        "Resent-Reply-To must preserve raw UTF-8 address syntax instead of rewriting the field body: {resent_reply_to_line}"
    );
    assert!(
        !resent_reply_to_line.contains("=?UTF-8?"),
        "Resent-Reply-To must not use RFC 2047 encoded-words in a structured address field: {resent_reply_to_line}"
    );
}

/// RFC 5322 Section 3.6.6: if any resent field is present, `Resent-Date`
/// and `Resent-From` are both required.
#[test]
fn resent_extra_headers_require_resent_date_and_from() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(hdr("Resent-From"), "Jos\u{00E9} <jose@example.com>".into())];

    let err = build_message(&email)
        .expect_err("partial resent blocks must be rejected per RFC 5322 Section 3.6.6");

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Date") && message.contains("Resent-From")),
        "expected InvalidResentHeader error mentioning required resent fields, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6 / field occurrence table: when `Resent-From`
/// contains more than one mailbox, `Resent-Sender` becomes mandatory,
/// just like `Sender` for a multi-mailbox `From` field.
#[test]
fn resent_extra_headers_with_multiple_from_mailboxes_require_resent_sender() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (
            hdr("Resent-From"),
            "Alice <alice@example.com>, Bob <bob@example.com>".into(),
        ),
    ];

    let err = build_message(&email).expect_err(
        "multi-mailbox Resent-From must require Resent-Sender per RFC 5322 Section 3.6.6",
    );

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Sender")),
        "expected InvalidResentHeader error mentioning Resent-Sender, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6: each resent block corresponds to one resending
/// event, so later `Resent-Date` fields start a new block that must carry
/// its own required `Resent-From`.
#[test]
fn resent_extra_headers_validate_each_block_for_required_fields() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "Alice <alice@example.com>".into()),
        (hdr("Resent-Date"), "Sat, 22 Nov 1997 10:00:00 -0600".into()),
        (hdr("Resent-To"), "Bob <bob@example.com>".into()),
    ];

    let err = build_message(&email).expect_err(
        "each resent block must include both Resent-Date and Resent-From per RFC 5322 Section 3.6.6",
    );

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Date") && message.contains("Resent-From")),
        "expected InvalidResentHeader error mentioning required per-block resent fields, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6: the `Resent-Sender` requirement is evaluated
/// per resent block, not against only the last `Resent-From` field seen.
#[test]
fn resent_extra_headers_validate_each_block_for_resent_sender() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (
            hdr("Resent-From"),
            "Alice <alice@example.com>, Bob <bob@example.com>".into(),
        ),
        (hdr("Resent-Date"), "Sat, 22 Nov 1997 10:00:00 -0600".into()),
        (hdr("Resent-From"), "Carol <carol@example.com>".into()),
    ];

    let err = build_message(&email).expect_err(
        "multi-mailbox Resent-From in any resent block must require Resent-Sender per RFC 5322 Section 3.6.6",
    );

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Sender")),
        "expected InvalidResentHeader error mentioning per-block Resent-Sender, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6: `Resent-Date` uses the `date-time` syntax
/// and must not be emitted with an invalid field body.
#[test]
fn resent_extra_headers_reject_invalid_resent_date() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "not-a-date".into()),
        (hdr("Resent-From"), "Alice <alice@example.com>".into()),
    ];

    let err = build_message(&email)
        .expect_err("invalid Resent-Date must be rejected per RFC 5322 Section 3.6.6");

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Date")),
        "expected InvalidResentHeader error mentioning Resent-Date, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6: `Resent-From` uses `mailbox-list` syntax and
/// must contain at least one mailbox.
#[test]
fn resent_extra_headers_reject_invalid_resent_from() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "not-an-address".into()),
    ];

    let err = build_message(&email)
        .expect_err("invalid Resent-From must be rejected per RFC 5322 Section 3.6.6");

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-From")),
        "expected InvalidResentHeader error mentioning Resent-From, got {err:?}"
    );
}

/// RFC 5322 Section 4.5.6 defines obsolete `Resent-Reply-To` as an
/// `address-list`, so malformed values must be rejected instead of being
/// emitted as arbitrary unstructured text.
#[test]
fn resent_extra_headers_reject_invalid_resent_reply_to() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "Alice <alice@example.com>".into()),
        (hdr("Resent-Reply-To"), "not-an-address".into()),
    ];

    let err = build_message(&email)
        .expect_err("invalid Resent-Reply-To must be rejected per RFC 5322 Section 4.5.6");

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Reply-To")),
        "expected InvalidResentHeader error mentioning Resent-Reply-To, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6: `Resent-Sender` uses `mailbox` syntax and
/// therefore must contain exactly one mailbox.
#[test]
fn resent_extra_headers_reject_invalid_resent_sender() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (
            hdr("Resent-From"),
            "Alice <alice@example.com>, Bob <bob@example.com>".into(),
        ),
        (
            hdr("Resent-Sender"),
            "Carol <carol@example.com>, Dave <dave@example.com>".into(),
        ),
    ];

    let err = build_message(&email)
        .expect_err("invalid Resent-Sender must be rejected per RFC 5322 Section 3.6.6");

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Sender")),
        "expected InvalidResentHeader error mentioning Resent-Sender, got {err:?}"
    );
}

/// RFC 5322 Sections 3.6.3 and 3.6.6: `Resent-Bcc` reuses `Bcc` syntax,
/// so a non-empty field body must be an `address-list` rather than
/// arbitrary text.
#[test]
fn resent_extra_headers_reject_invalid_resent_bcc() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "Alice <alice@example.com>".into()),
        (hdr("Resent-Bcc"), "not-an-address".into()),
    ];

    let err = build_message(&email)
        .expect_err("invalid Resent-Bcc must be rejected per RFC 5322 Section 3.6.6");

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Bcc")),
        "expected InvalidResentHeader error mentioning Resent-Bcc, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6: `Resent-Message-ID` uses `msg-id` syntax and
/// must not be emitted with malformed content.
#[test]
fn resent_extra_headers_reject_invalid_resent_message_id() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "Alice <alice@example.com>".into()),
        (hdr("Resent-Message-ID"), "<missing-at-sign>".into()),
    ];

    let err = build_message(&email)
        .expect_err("invalid Resent-Message-ID must be rejected per RFC 5322 Section 3.6.6");

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Message-ID")),
        "expected InvalidResentHeader error mentioning Resent-Message-ID, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6 requires each contiguous resent block to be
/// grouped as one resending event. A `Resent-Sender` that appears before a
/// later `Resent-Date` belongs to the earlier block and must not satisfy a
/// later multi-mailbox `Resent-From`.
#[test]
fn resent_extra_headers_do_not_let_earlier_sender_satisfy_later_block() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "Alice <alice@example.com>".into()),
        (hdr("Resent-Sender"), "Relay <relay@example.com>".into()),
        (hdr("Resent-Date"), "Sat, 22 Nov 1997 10:00:00 -0600".into()),
        (
            hdr("Resent-From"),
            "Bob <bob@example.com>, Carol <carol@example.com>".into(),
        ),
    ];

    let err = build_message(&email)
        .expect_err("a later multi-mailbox Resent-From must not borrow an earlier Resent-Sender");

    assert!(
        matches!(err, Error::InvalidResentHeader(ref message) if message.contains("Resent-Sender")),
        "expected InvalidResentHeader error mentioning later-block Resent-Sender, got {err:?}"
    );
}

/// RFC 5322 Section 3.6.6 does not require `Resent-Date` to appear first
/// within a resent block, so a grouped block with a later `Resent-Date`
/// is still valid as long as the block contains the required fields.
#[test]
fn resent_extra_headers_allow_valid_noncanonical_field_order_within_block() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![
        (hdr("Resent-To"), "Bob <bob@example.com>".into()),
        (hdr("Resent-Date"), "Fri, 21 Nov 1997 09:55:06 -0600".into()),
        (hdr("Resent-From"), "Alice <alice@example.com>".into()),
    ];

    let built = build_message(&email)
        .expect("valid resent block ordering should not require Resent-Date first");
    let text = String::from_utf8_lossy(&built.raw);

    assert!(
        text.contains("Resent-To: Bob <bob@example.com>\r\n"),
        "resent block should preserve the caller-provided field order: {text}"
    );
    assert!(
        text.contains("Resent-Date: Fri, 21 Nov 1997 09:55:06 -0600\r\n"),
        "resent block should emit Resent-Date even when it is not the first field: {text}"
    );
    assert!(
        text.contains("Resent-From: Alice <alice@example.com>\r\n"),
        "resent block should emit Resent-From for a valid noncanonical ordering: {text}"
    );
}

/// RFC 5322 Section 2.2 / builder sanitization: extra header values
/// containing CRLF sequences (potential header injection) must be
/// sanitized so that the CRLF does not appear in the output, preventing
/// injection of additional headers.
#[test]
fn build_extra_header_crlf_injection_sanitized() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    // Attempt CRLF injection: value contains \r\n followed by a
    // fake header that would be interpreted as a separate header
    // if not sanitized.
    email.extra_headers = vec![(hdr("X-Safe"), "value\r\nX-Injected: evil".into())];

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The injected header must not appear as a separate header line.
    assert!(
        !s.contains("\r\nX-Injected:"),
        "CRLF injection must be sanitized — injected header must not appear \
         as a separate line (RFC 5322 Section 2.2): {s}"
    );
    // The X-Safe header must still be present.
    assert!(
        s.contains("X-Safe:"),
        "Original header name must survive sanitization: {s}"
    );
}

/// RFC 5322 Section 3.6.5: a whitespace-only unstructured field body is
/// valid data. The builder must preserve it through a build-parse
/// round-trip instead of collapsing it to empty.
#[test]
fn whitespace_only_subject_round_trip() {
    let mut email = make_email();
    email.subject = "  \t  ".into();

    // Builder must not panic on whitespace-only subject.
    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The raw output must contain a Subject header line.
    assert!(
        s.contains("Subject:"),
        "Builder must emit a Subject header even for whitespace-only input \
         (RFC 5322 Section 3.6.5)"
    );

    // Round-trip: parse the built message and verify subject.
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.subject.as_deref(),
        Some("  \t  "),
        "Whitespace-only subject must preserve legal WSP exactly \
         (RFC 5322 Section 3.6.5)"
    );
}

/// RFC 5322 Section 3.6.5: leading WSP in an unstructured field body is
/// part of the field body and must survive a build-parse round-trip.
#[test]
fn leading_whitespace_subject_preserves_content() {
    let mut email = make_email();
    email.subject = "  Hello".into();

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // The raw output must contain the Subject header with the content.
    assert!(
        s.contains("Subject:"),
        "Builder must emit a Subject header (RFC 5322 Section 3.6.5)"
    );
    assert!(
        s.contains("Hello"),
        "Subject content must appear in the raw output"
    );

    // Round-trip: parse the built message.
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert_eq!(
        parsed.subject.as_deref(),
        Some("  Hello"),
        "Leading whitespace is part of the Subject field body and must be \
         preserved through the round-trip (RFC 5322 Section 3.6.5)"
    );
}

/// RFC 2047 Section 2: "Each line of a header field that contains one or
/// more 'encoded-word's is limited to 76 characters."
///
/// A very long non-ASCII display name in the From header produces many
/// encoded-words. The builder must fold them so that no output line
/// containing an encoded-word exceeds 76 characters.
///
/// This also verifies the round-trip: `parse_email` must recover the
/// original display name from the folded RFC 2047 encoded header.
#[test]
fn rfc2047_very_long_non_ascii_from_display_name_lines_within_76_chars() {
    let long_name = "".repeat(120);
    let mut email = make_email();
    email.from = vec![Address {
        name: Some(long_name.clone()),
        email: "sender@example.com".into(),
    }];
    email.body_text = Some("test body".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Every line containing an encoded-word must be ≤76 chars
    // (RFC 2047 Section 2).
    for (i, line) in s.split("\r\n").enumerate() {
        if line.contains("=?") && line.contains("?=") {
            assert!(
                line.len() <= 76,
                "RFC 2047 Section 2: From header line {i} with encoded-word \
                 exceeds 76 chars ({} chars): {line}",
                line.len()
            );
        }
    }

    // Round-trip: parse_email must recover the original display name.
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert!(
        !parsed.from.is_empty(),
        "Parsed message must have at least one From address"
    );
    assert_eq!(
        parsed.from[0].name.as_deref().unwrap(),
        long_name,
        "From display name must survive RFC 2047 encode → fold → decode round-trip"
    );
    assert_eq!(parsed.from[0].email, "sender@example.com");
}

/// RFC 2047 Section 2: encoded-word line limit applies to Reply-To
/// headers as well. "Reply-To: " is 10 chars of prefix, which leaves
/// only 66 chars for the first encoded-word token on that line.
///
/// A very long non-ASCII display name must be folded so that every
/// output line with an encoded-word is ≤76 characters.
#[test]
fn rfc2047_very_long_non_ascii_reply_to_display_name_lines_within_76_chars() {
    let long_name = "".repeat(120);
    let mut email = make_email();
    email.reply_to = vec![Address {
        name: Some(long_name.clone()),
        email: "reply@example.com".into(),
    }];
    email.body_text = Some("test body".into());

    let built = build_message(&email).unwrap();
    let s = raw_str(&built);

    // Every line containing an encoded-word must be ≤76 chars
    // (RFC 2047 Section 2).
    for (i, line) in s.split("\r\n").enumerate() {
        if line.contains("=?") && line.contains("?=") {
            assert!(
                line.len() <= 76,
                "RFC 2047 Section 2: Reply-To header line {i} with \
                 encoded-word exceeds 76 chars ({} chars): {line}",
                line.len()
            );
        }
    }

    // Round-trip: parse_email must recover the original display name.
    let parsed = crate::parse_email(&built.raw).unwrap();
    assert!(
        !parsed.reply_to.is_empty(),
        "Parsed message must have at least one Reply-To address"
    );
    assert_eq!(
        parsed.reply_to[0].name.as_deref().unwrap(),
        long_name,
        "Reply-To display name must survive RFC 2047 encode → fold → decode round-trip"
    );
    assert_eq!(parsed.reply_to[0].email, "reply@example.com");
}

/// RFC 2046 Section 5.2.1: message/* attachments with conforming line
/// lengths (≤998 octets) must be accepted and written with 7bit or 8bit
/// Content-Transfer-Encoding.
#[test]
fn message_rfc822_attachment_valid_lines_accepted() {
    let mut email = make_email();
    email.body_text = Some("test body".into());

    // Build a message/rfc822 attachment with lines within the 998-octet
    // limit (RFC 5322 Section 2.1.1).
    let inner_msg = "From: inner@example.com\r\n\
                     Date: Thu, 13 Feb 2025 15:47:33 +0000\r\n\
                     Subject: Inner\r\n\
                     \r\n\
                     Normal body line\r\n";
    email.attachments.push(OutgoingAttachment {
        filename: "forwarded.eml".into(),
        content_type: "message/rfc822".into(),
        data: inner_msg.as_bytes().to_vec(),
        is_inline: false,
        content_id: None,
    });

    let result = build_message(&email);
    assert!(
        result.is_ok(),
        "message/rfc822 attachment with conforming line lengths must be \
         accepted (RFC 2046 Section 5.2.1): {result:?}"
    );

    // Verify the attachment is encoded as 7bit (all ASCII)
    let raw = raw_str(&result.unwrap());
    assert!(
        raw.contains("Content-Transfer-Encoding: 7bit"),
        "Pure-ASCII message/rfc822 should use 7bit CTE"
    );
}

/// RFC 2046 Section 5.2.1: message/* MUST NOT use base64 or
/// quoted-printable; only 7bit, 8bit, or binary are permitted.
/// RFC 2045 Section 2.8: 8bit content must have lines ≤998 octets.
///
/// When message/* attachment data contains lines exceeding 998 octets,
/// the builder cannot re-encode (base64/QP forbidden) so it must
/// reject the attachment with an error.
#[test]
fn message_rfc822_attachment_overlong_line_rejected() {
    let mut email = make_email();
    email.body_text = Some("test body".into());

    // Build a message/rfc822 attachment whose body contains a line
    // exceeding 998 octets (the hard limit from RFC 5322 Section 2.1.1).
    let overlong_line = "X".repeat(1000);
    let inner_msg = format!(
        "From: inner@example.com\r\n\
         Date: Thu, 13 Feb 2025 15:47:33 +0000\r\n\
         Subject: Inner\r\n\
         \r\n\
         {overlong_line}\r\n"
    );
    email.attachments.push(OutgoingAttachment {
        filename: "forwarded.eml".into(),
        content_type: "message/rfc822".into(),
        data: inner_msg.into_bytes(),
        is_inline: false,
        content_id: None,
    });

    let result = build_message(&email);
    assert!(
        result.is_err(),
        "RFC 2046 Section 5.2.1 / RFC 2045 Section 2.8: message/* \
         attachment with lines >998 octets must be rejected because \
         base64/quoted-printable encoding is forbidden for message/* types"
    );
}

/// RFC 6532 Section 3.7 registers `message/global` with "Any
/// content-transfer-encoding is permitted", unlike RFC 2046
/// Section 5.2.1's restrictions for `message/rfc822`.
///
/// A `message/global` attachment with an overlong encapsulated line
/// should therefore be encoded safely instead of being rejected.
#[test]
fn message_global_attachment_overlong_line_is_base64_encoded() {
    let mut email = make_email();
    email.body_text = Some("test body".into());

    let overlong_line = "é".repeat(600);
    let inner_msg = format!(
        "From: inner@example.com\r\n\
         Subject: café\r\n\
         \r\n\
         {overlong_line}\r\n"
    );
    email.attachments.push(OutgoingAttachment {
        filename: "forwarded.global".into(),
        content_type: "message/global".into(),
        data: inner_msg.into_bytes(),
        is_inline: false,
        content_id: None,
    });

    let built = build_message(&email).expect(
        "message/global attachments may use base64 when the embedded message \
         is not 7bit/8bit-safe (RFC 6532 Section 3.7)",
    );
    let raw = raw_str(&built);

    assert!(
        raw.contains("Content-Type: message/global"),
        "message/global content type must be preserved: {raw}"
    );
    assert!(
        raw.contains("Content-Transfer-Encoding: base64"),
        "message/global with overlong lines should use base64 per RFC 6532 Section 3.7: {raw}"
    );
    assert!(
        !raw.contains(&overlong_line),
        "base64-encoded message/global attachment must not write the overlong line verbatim"
    );
}

// ---- Bug regression tests ----

/// RFC 6531 Section 3.3 extends RFC 5322 Section 3.2.4 to allow UTF-8
/// characters in quoted local-parts of internationalized email addresses.
/// A quoted local-part like `"用户"@example.com` must be accepted.
#[test]
fn validate_address_allows_utf8_in_quoted_local_part() {
    let addr = Address {
        name: None,
        email: "\"用户\"@example.com".into(),
    };
    let result = validate_address(&addr);
    assert!(
        result.is_ok(),
        "RFC 6531 Section 3.3: UTF-8 bytes must be allowed in quoted \
         local-parts, but got: {result:?}"
    );
}

/// RFC 5322 Section 3.4.1: quoted local-parts may contain `@` inside the
/// quotes. The address `"user@company"@example.com` has local-part
/// `"user@company"` and domain `example.com`. The builder must not reject
/// this as "multiple '@' characters".
#[test]
fn validate_address_allows_at_in_quoted_local_part() {
    let addr = Address {
        name: None,
        email: "\"user@company\"@example.com".into(),
    };
    let result = validate_address(&addr);
    assert!(
        result.is_ok(),
        "RFC 5322 Section 3.4.1: '@' is valid qtext inside a quoted \
         local-part, but got: {result:?}"
    );
}

/// RFC 2231 Sections 3-4 extend MIME parameter names beyond plain RFC 2045
/// tokens, allowing attributes such as `title*=` and `title*0*=`.
/// Attachment `Content-Type` validation must preserve these parameters
/// instead of falling back to `application/octet-stream`.
#[test]
fn attachment_content_type_preserves_rfc2231_extended_param_names() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.attachments.push(OutgoingAttachment {
        filename: "report.bin".into(),
        content_type: "application/x-example; title*=UTF-8''caf%C3%A9".into(),
        data: b"payload".to_vec(),
        is_inline: false,
        content_id: None,
    });

    let built = build_message(&email)
        .expect("RFC 2231 extended parameter names on attachment Content-Type must be accepted");
    let raw = raw_str(&built);

    assert!(
        raw.contains("Content-Type: application/x-example; title*=UTF-8''caf%C3%A9;"),
        "attachment Content-Type with RFC 2231 extended parameter names must keep the \
         extended attribute instead of falling back: {raw}"
    );
    assert!(
        raw.contains("name=\"report.bin\""),
        "attachment Content-Type should still add the builder's name= parameter: {raw}"
    );
    assert!(
        !raw.contains("Content-Type: application/octet-stream"),
        "attachment Content-Type must not fall back to application/octet-stream: {raw}"
    );
}

/// RFC 2045 Section 5.1 says MIME structured header fields allow RFC 822
/// comments with no semantic meaning. A valid attachment `Content-Type`
/// that includes comments must therefore still be accepted and preserved,
/// rather than falling back to `application/octet-stream`.
#[test]
fn attachment_content_type_allows_rfc2045_comments() {
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.attachments.push(OutgoingAttachment {
        filename: "report.bin".into(),
        content_type: "application/x-example (audit note); title*=UTF-8''caf%C3%A9 (Plain text)"
            .into(),
        data: b"payload".to_vec(),
        is_inline: false,
        content_id: None,
    });

    let built = build_message(&email)
        .expect("RFC 2045 Section 5.1 commented Content-Type must be accepted for attachments");
    let raw = raw_str(&built);
    let unfolded = raw.replace("\r\n ", " ").replace("\r\n\t", " ");

    assert!(
        unfolded.contains(
            "Content-Type: application/x-example (audit note); title*=UTF-8''caf%C3%A9 (Plain text);"
        ),
        "attachment Content-Type comments must be preserved instead of falling back: {raw}"
    );
    assert!(
        unfolded.contains("name=\"report.bin\""),
        "builder should still append the name= parameter after the commented Content-Type: {raw}"
    );
    assert!(
        !raw.contains("Content-Type: application/octet-stream"),
        "commented attachment Content-Type must not fall back to application/octet-stream: {raw}"
    );
}

#[test]
fn extra_headers_allow_top_level_content_disposition() {
    // RFC 2183 Section 2.10: Content-Disposition is permitted on the
    // main body of an RFC 5322 message, not only on subparts.
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(
        hdr("Content-Disposition"),
        "attachment; filename=\"message.eml\"".into(),
    )];

    let built = build_message(&email).expect("top-level Content-Disposition should be accepted");
    let raw = String::from_utf8(built.raw).expect("message bytes must be valid UTF-8");

    assert!(
        raw.contains("Content-Disposition: attachment; filename=\"message.eml\"\r\n"),
        "top-level Content-Disposition must be preserved on the main message per RFC 2183 Section 2.10: {raw}"
    );
}

#[test]
fn extra_headers_allow_top_level_content_id() {
    // RFC 2045 Section 7 allows Content-ID on MIME entities generally,
    // including the top-level message body.
    let mut email = make_email();
    email.body_text = Some("body".into());
    email.extra_headers = vec![(hdr("Content-ID"), "<test@example.com>".into())];

    let built = build_message(&email).expect("top-level Content-ID should be accepted");
    let raw = String::from_utf8(built.raw).expect("message bytes must be valid UTF-8");

    assert!(
        raw.contains("Content-ID: <test@example.com>\r\n"),
        "top-level Content-ID must be preserved on the main MIME entity per RFC 2045 Section 7: {raw}"
    );
}

/// RFC 5322 Sections 2.1.1, 2.2.3, and 3.6.4: builders must not emit an
/// overlong `In-Reply-To` line when a single `msg-id` token is too large
/// to fold legally. Because `msg-id` contains no FWS, the only correct
/// behavior is to reject the message instead of emitting an invalid line.
#[test]
fn build_rejects_overlong_in_reply_to_msg_id_token() {
    let overlong_msg_id = format!("{}@{}", "a".repeat(400), "b".repeat(600));
    let mut email = make_email();
    email.in_reply_to = vec![mid(&overlong_msg_id)];

    let err = build_message(&email)
        .expect_err("overlong single msg-id token must be rejected before writing");

    assert!(
        matches!(err, Error::HeaderLineTooLong(ref message) if message.contains("In-Reply-To")
            && message.contains("998")
            && message.contains("RFC 5322 Sections 2.1.1 and 2.2.3")),
        "expected HeaderLineTooLong error about impossible-to-fold In-Reply-To token, got {err:?}"
    );
}

/// RFC 5322 Section 2.2.3: WSP is defined as SP / HTAB. Both are legal
/// in header field bodies. `write_header` must preserve HTAB characters
/// rather than silently converting them to spaces during folding.
#[test]
fn write_header_preserves_htab_in_subject() {
    let mut email = make_email();
    email.subject = "Hello\tWorld".into();
    let built = build_message(&email).unwrap();
    let raw = std::str::from_utf8(&built.raw).unwrap();
    // Find the Subject header line (may be folded across multiple lines,
    // so unfold first per RFC 5322 Section 2.2.3).
    let subject_line = raw
        .lines()
        .find(|l| l.starts_with("Subject:"))
        .expect("Subject header must be present");
    assert!(
        subject_line.contains('\t'),
        "HTAB must be preserved in Subject header, got: {subject_line:?}"
    );
}

/// RFC 5322 Sections 2.1.1, 2.2.3, and 3.6.2: builders must not emit an
/// overlong `From` line when a single mailbox token is too large to fold
/// legally. The correct behavior is to reject the message instead of
/// producing invalid output.
#[test]
fn build_rejects_overlong_from_address_token() {
    let long_local = "a".repeat(500);
    let long_domain = vec!["b".repeat(63); 8].join(".") + ".com";
    let email_addr = format!("{long_local}@{long_domain}");
    let email = OutgoingEmail {
        from: vec![Address {
            name: None,
            email: email_addr,
        }],
        sender: None,
        to: vec![Address {
            name: None,
            email: "to@example.com".into(),
        }],
        cc: vec![],
        bcc: vec![],
        reply_to: vec![],
        date: None,
        subject: "test".into(),
        body_text: Some("body".into()),
        body_html: None,
        in_reply_to: vec![],
        references: vec![],
        attachments: vec![],
        extra_headers: vec![],
    };

    let err = build_message(&email)
        .expect_err("overlong single mailbox token must be rejected before writing");

    assert!(
        matches!(err, Error::HeaderLineTooLong(ref message) if message.contains("From")
            && message.contains("998")
            && message.contains("RFC 5322 Sections 2.1.1 and 2.2.3")),
        "expected HeaderLineTooLong error about impossible-to-fold From token, got {err:?}"
    );
}

#[test]
fn extract_domain_quoted_local_part_with_at() {
    // RFC 5322 Section 3.4.1: quoted local-parts may contain @.
    // extract_domain must find the @ after the closing quote.
    assert_eq!(
        extract_domain("\"user@company\"@example.com"),
        Some("example.com")
    );
    // Regular case still works
    assert_eq!(extract_domain("user@example.com"), Some("example.com"));
    // No @
    assert_eq!(extract_domain("noatsign"), None);
    // Empty domain
    assert_eq!(extract_domain("user@"), None);
}

#[test]
fn generate_message_id_preserves_domain_literals() {
    // RFC 5322 Section 3.6.4: id-right = dot-atom-text / no-fold-literal.
    // A domain-literal such as an IPv6 address must stay bracketed rather
    // than being flattened into an invalid dot-atom.
    let id = generate_message_id("[IPv6:2001:db8::1]");
    assert!(
        id.ends_with("@[IPv6:2001:db8::1]"),
        "Message-ID must preserve a no-fold-literal id-right: {id}"
    );

    // Regular dot-atom domains are still preserved unchanged.
    let id2 = generate_message_id("example.com");
    assert!(id2.ends_with("@example.com"));
}

/// RFC 5322 Section 3.6.4 permits `id-right = no-fold-literal`, so
/// threading headers must preserve valid domain-literal message-ids.
#[test]
fn build_in_reply_to_accepts_domain_literal_msg_id() {
    let mut email = make_email();
    email.in_reply_to = vec![mid("reply@[IPv6:2001:db8::1]")];

    let built = build_message(&email).expect("build should accept a valid domain-literal msg-id");
    let raw = String::from_utf8_lossy(&built.raw);
    assert!(
        raw.contains("In-Reply-To: <reply@[IPv6:2001:db8::1]>\r\n"),
        "In-Reply-To must preserve a valid no-fold-literal msg-id: {raw}"
    );
}

/// RFC 2392 uses RFC 5322 `msg-id` syntax for Content-ID, including
/// domain-literal id-right values allowed by RFC 5322 Section 3.6.4.
#[test]
fn build_content_id_accepts_domain_literal_msg_id() {
    let mut email = make_email();
    email.body_html = Some("<img src=\"cid:part@[IPv6:2001:db8::1]\">".into());
    email.attachments = vec![OutgoingAttachment {
        filename: "image.png".into(),
        content_type: "image/png".into(),
        data: vec![0x89, b'P', b'N', b'G'],
        is_inline: true,
        content_id: Some("part@[IPv6:2001:db8::1]".into()),
    }];

    let built =
        build_message(&email).expect("build should accept a valid domain-literal Content-ID");
    let raw = String::from_utf8_lossy(&built.raw);
    assert!(
        raw.contains("Content-ID: <part@[IPv6:2001:db8::1]>\r\n"),
        "Content-ID must preserve a valid no-fold-literal msg-id: {raw}"
    );
}

#[test]
fn format_address_encodes_control_chars_in_display_name() {
    // RFC 5322 Section 2.2: header field bodies must be printable US-ASCII.
    // RFC 5322 Section 3.2.3: atext excludes control characters.
    // HTAB (0x09) is valid WSP per RFC 5322 Section 2.2.
    // Control characters (0x00-0x1F except HTAB, 0x7F) must be RFC 2047
    // encoded. Previously, format_address only checked for non-ASCII bytes,
    // allowing control chars through unencoded.
    let addr = crate::types::Address {
        name: Some("Bell\x07Char".to_string()),
        email: "user@example.com".to_string(),
    };
    let formatted = format_address(&addr);
    // The display name contains a control character (BEL = 0x07),
    // so it must be RFC 2047 encoded, not emitted raw.
    assert!(
        formatted.contains("=?UTF-8?B?"),
        "display name with control chars must be RFC 2047 encoded, got: {formatted}"
    );
    assert!(
        formatted.contains("<user@example.com>"),
        "email must be angle-bracketed: {formatted}"
    );
}

/// Regression: `resent_field_kind()` must not panic on unknown field names.
/// The caller guards with `is_resent_extra_header()`, but the function itself
/// is `pub(super)` and must return an error instead of panicking via
/// `unreachable!()` (workspace rule: errors, not panics).
#[test]
fn resent_field_kind_unknown_field_returns_error() {
    let result = resent_field_kind("X-Not-A-Resent-Field", 0);
    assert!(
        result.is_err(),
        "unknown resent field must return Err, not panic"
    );
}

/// Valid resent field names must still resolve correctly after the
/// `unreachable!()` → `Result` migration.
#[test]
fn resent_field_kind_valid_fields_resolve() {
    assert!(resent_field_kind("Resent-Date", 0).is_ok());
    assert!(resent_field_kind("resent-from", 2).is_ok());
    assert!(resent_field_kind("RESENT-TO", 0).is_ok());
    assert!(resent_field_kind("resent-message-id", 0).is_ok());
}