seer-core 0.56.0

Core library for Seer domain name utilities
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
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Utc};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::sync::LazyLock;

use super::parsers::{push_bounded, MAX_NAMESERVERS, MAX_STATUSES};

/// Compiles one `Label: value` pattern per label, matching anywhere on a
/// line: `(?i)<label>:[ \t]*(.+)`. Labels are regex fragments; a list's order
/// is its priority ([`extract_field_with_patterns`] takes the first match).
///
/// The label is separated from its value by `[ \t]*` (horizontal whitespace
/// only), never `\s*`: `\s` also matches `\r`/`\n`, so an EMPTY field
/// (`Name Server: \r\n`, `DNSSEC:\n`) would swallow the line break and capture
/// the NEXT line as its value (`DNSSEC: URL of the ICANN Whois Inaccuracy
/// Complaint Form: …`). Registries that genuinely put the value on the
/// following line (NASK `REGISTRAR:\n<name>`, DNS Belgium
/// `Registrar:\n\tName: <name>`) are handled explicitly by
/// [`extract_section_value`] instead.
pub(super) fn field_patterns(labels: &[&str]) -> Vec<Regex> {
    labels
        .iter()
        .map(|label| compile(&format!(r"(?i){label}:[ \t]*(.+)")))
        .collect()
}

/// Like [`field_patterns`], but anchored to the start of a line (indentation
/// allowed), for labels that also end a longer one (`Organization:` inside
/// `Admin Organization:`) or would otherwise match inside prose.
pub(super) fn line_field_patterns(labels: &[&str]) -> Vec<Regex> {
    labels
        .iter()
        .map(|label| compile(&format!(r"(?im)^[ \t]*{label}:[ \t]*(.+)$")))
        .collect()
}

/// Rewrites padded labels into the plain `Label: value` form every pattern
/// here expects: dot leaders before the colon (Traficom .fi/.ax, KazNIC .kz:
/// `created..........: 16.2.1999`) or after it (NIC Togo .tg:
/// `Registrar:..........NETMASTER SARL`), and blanks before the colon (NIC
/// Monaco .mc: `Expires on         : 2027-01-08`). Only a label at the start
/// of a line is touched, so values and prose keep their dots and spacing.
pub(super) fn normalize_label_padding(raw: &str) -> std::borrow::Cow<'_, str> {
    static_regex! {
        LABEL_PADDING = r"(?m)^([ \t]*[A-Za-z][A-Za-z0-9 /()_-]*?)(?:\.{2,}[ \t]*|[ \t]+):";
        TRAILING_LEADER = r"(?m)^([ \t]*[A-Za-z][A-Za-z0-9 /()_-]*?):\.{2,}";
    }
    match LABEL_PADDING.replace_all(raw, "$1:") {
        std::borrow::Cow::Borrowed(b) => TRAILING_LEADER.replace_all(b, "$1: "),
        std::borrow::Cow::Owned(o) => {
            std::borrow::Cow::Owned(TRAILING_LEADER.replace_all(&o, "$1: ").into_owned())
        }
    }
}

fn compile(pattern: &str) -> Regex {
    Regex::new(pattern).expect("valid WHOIS field regex")
}

static REGISTRAR_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    field_patterns(&[
        "Registrar",
        "Registrar Name",
        "Sponsoring Registrar",
        // RESTENA (.lu)
        "registrar-name",
        // TWNIC (.tw)
        "Registration Service Provider",
    ])
});

static REGISTRANT_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    let mut patterns = field_patterns(&[
        "Registrant Name",
        "Registrant",
        // .ae: `Registrant Contact Name:`; Tecnisys (.st) `registrant-name:`.
        // After the plain label: auDA (.au) prints both, and its
        // `Registrant:` is the holder, the contact name a person.
        "Registrant Contact Name",
        "registrant-name",
    ]);
    // Registro.br (.br): `owner:` (not `owner-c:` / `ownerid:`)
    patterns.extend(line_field_patterns(&["owner"]));
    patterns
});

/// Section headings a registrant's name sits under (see
/// [`extract_section_value`]): TWNIC/METU/BNNIC/KazNIC `Registrant`,
/// Traficom/`.sn` `Holder`, NIC.SM `Owner`, ATI (.tn) `Owner Contact`.
const REGISTRANT_HEADINGS: &[&str] = &[
    "registrant",
    "holder",
    "domain holder",
    "owner",
    "owner contact",
];

static ORGANIZATION_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    let mut patterns = field_patterns(&[
        "Registrant Organization",
        // .ae: `Registrant Contact Organisation:`; Tecnisys (.st)
        // `registrant-organization:`; THNIC (.th) `Domain Holder Organization:`
        "Registrant Contact Organisation",
        "Registrant Organisation",
        "registrant-organization",
        "Domain Holder Organization",
    ]);
    // The bare/ambiguous org labels are line-anchored so they cannot match the
    // "Organization:" inside "Admin Organization:" / "Tech Organization:" and
    // thereby attribute another contact's org to the registrant.
    patterns.extend(line_field_patterns(&[
        "Organization",
        "org-name",
        "Org Name",
        // HKIRC (.hk): `Company English Name (It should be the same as …): X`
        r"Company English Name(?: \([^)]*\))?",
        // hoster.by (.by): `Org:` heads the reply, before any contact.
        "Org",
    ]));
    patterns
});

static CREATION_DATE_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    let mut patterns = field_patterns(&[
        "Creation Date",
        "Created Date",
        "Created On",
        "Created",
        "Registration Date",
        "Domain Registration Date",
        // HKIRC (.hk): `Domain Name Commencement Date: 06-04-2004`
        "Commencement Date",
        // NIC.BO (.bo)
        "Fecha de registro",
    ]);
    // Punktum (.dk) style `Registered:           2018-01-25`, and French
    // registries (ANINF .ga) `Date de création:`.
    patterns.extend(line_field_patterns(&[
        "Registered",
        "Date de création",
        // UG registry (.ug), MoldData (.md): `Registered On: 2004-08-03`
        "Registered On",
        // NIC Togo (.tg): `Activation:.........2023-03-02`
        "Activation",
    ]));
    // TWNIC (.tw): `Record created on 2005-10-27 17:02:34 (UTC+8)`, no colon.
    patterns.push(compile(r"(?im)^[ \t]*Record created on[ \t]+(.+)$"));
    patterns
});

static EXPIRATION_DATE_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    let mut patterns = field_patterns(&[
        "(?:Registry )?Expir(?:y|ation) Date",
        "Expiration Date",
        "Expires On",
        "Expires",
        "Expiry Date",
        "paid-till",
        // NIC.BO (.bo)
        "Fecha de vencimiento",
    ]);
    // French registries (ANINF .ga): `Date d'expiration:`
    patterns.extend(line_field_patterns(&[
        "Date d'expiration",
        // SK-NIC (.sk)
        "Valid Until",
        // THNIC (.th): `Exp date: 16 Jul 2027`
        "Exp date",
        // NIC Togo (.tg)
        "Expiration",
        // Register.si (.si)
        "expire",
    ]));
    // TWNIC (.tw): `Record expires on 2027-10-31 12:47:54 (UTC+8)`, no colon.
    patterns.push(compile(r"(?im)^[ \t]*Record expires on[ \t]+(.+)$"));
    patterns
});

static UPDATED_DATE_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    let mut patterns = field_patterns(&[
        "Updated Date",
        "Last Updated On",
        "Last Modified",
        "Last Update",
        "Modified",
        // BNNIC (.bn)
        "Modified Date",
        // hoster.by (.by)
        "Update Date",
    ]);
    // French registries (ANINF .ga): `Dernière modification:` — contact
    // blocks repeat this label; extract_field_with_patterns takes the first
    // match, which is the domain-level line.
    patterns.extend(line_field_patterns(&[
        "Dernière modification",
        // Norid (.no)
        "Last updated",
        // UG registry (.ug)
        "Information Last Updated",
        // RNIDS (.rs)
        "Modification date",
        // SK-NIC (.sk); line-anchored and last so it never outranks a
        // specific label.
        "Updated",
        // RIPE-style objects (nic.at, Registro.br, .gf/.mq): the domain's
        // `changed:` comes before any contact object's. FRED/AFNIC replies,
        // whose contacts come first, have their own parsers.
        "changed",
    ]));
    patterns
});

static DNSSEC_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| field_patterns(&["DNSSEC", "DNSSEC Status"]));

static NAMESERVER_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    let mut patterns = field_patterns(&["Name Server", "Nameserver", "nserver"]);
    patterns.push(compile(r"(?im)^NS:[ \t]+(.+)$"));
    // Punktum (.dk) lists nameservers as `Hostname:` lines under a
    // `Nameservers` heading (line-anchored to avoid hostname mentions inside
    // prose); French registries (ANINF .ga) use `Serveur de noms:` lines.
    // A bare `DNS:` label is NOT a nameserver everywhere (Punktum prints the
    // domain itself as `DNS:`), so NIC México's `DNS:` lines are read only
    // inside a heading block by `extract_nameserver_block`.
    patterns.extend(line_field_patterns(&[
        "Hostname",
        "Serveur de noms",
        // NIC Togo (.tg): `Name Server (DB):...ns1.nic.tg`
        r"Name Server \(DB\)",
        // TMNIC (.tm): `NS 1   : dns01.nic.tm` (padding normalized away);
        // its glue continuation lines start with `:` and are not matched.
        r"NS \d+",
    ]));
    patterns
});

static REGISTRANT_EMAIL_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    field_patterns(&[
        "Registrant Email",
        "Registrant E-mail",
        // CNNIC (.cn)
        "Registrant Contact Email",
    ])
});

static REGISTRANT_PHONE_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| field_patterns(&["Registrant Phone", "Registrant Tel"]));

static REGISTRANT_ADDRESS_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| field_patterns(&["Registrant Street", "Registrant Address"]));

static REGISTRANT_COUNTRY_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| field_patterns(&["Registrant Country"]));

// Admin/tech labels are line-anchored: gTLD-style replies also print
// `Registrar Admin Email:` etc. (the registrar's own contacts, .ps), which an
// unanchored `Admin Email:` would match first.
static ADMIN_NAME_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| line_field_patterns(&["Admin Name", "Administrative Contact Name"]));

static ADMIN_ORG_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| line_field_patterns(&["Admin Organization"]));

static ADMIN_EMAIL_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| line_field_patterns(&["Admin Email", "Admin E-mail"]));

static ADMIN_PHONE_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| line_field_patterns(&["Admin Phone", "Admin Tel"]));

static TECH_NAME_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| line_field_patterns(&["Tech Name", "Technical Contact Name"]));

static TECH_ORG_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| line_field_patterns(&["Tech Organization"]));

static TECH_EMAIL_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| line_field_patterns(&["Tech Email", "Tech E-mail"]));

static TECH_PHONE_PATTERNS: LazyLock<Vec<Regex>> =
    LazyLock::new(|| line_field_patterns(&["Tech Phone", "Tech Tel"]));

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WhoisResponse {
    pub domain: String,
    pub registrar: Option<String>,
    pub registrant: Option<String>,
    pub organization: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registrant_email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registrant_phone: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registrant_address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registrant_country: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub admin_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub admin_organization: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub admin_email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub admin_phone: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tech_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tech_organization: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tech_email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tech_phone: Option<String>,
    pub creation_date: Option<DateTime<Utc>>,
    pub expiration_date: Option<DateTime<Utc>>,
    pub updated_date: Option<DateTime<Utc>>,
    pub nameservers: Vec<String>,
    pub status: Vec<String>,
    pub dnssec: Option<String>,
    pub whois_server: String,
    // Suppressed from default serialization: the raw response is up to 1 MB of
    // attacker-controlled content from third-party registries/registrars. It
    // leaking into API/MCP JSON output creates a prompt-injection vector for
    // downstream LLM consumers. The field is still populated internally for
    // is_available() / indicates_not_found() scanning and for callers that
    // access it directly via struct field.
    //
    // `default` is required alongside `skip_serializing`: without it, a
    // round-trip through serialized JSON (e.g. lookup history persistence,
    // the lookup cache) fails to deserialize with "missing field
    // `raw_response`", because—unlike `Option`—a bare `String` is not
    // defaulted on absence. The skip keeps it out of the JSON; the default
    // lets it read back as empty.
    #[serde(skip_serializing, default)]
    pub raw_response: String,
}

impl WhoisResponse {
    /// Parses a WHOIS response with the registry-specific parser for the
    /// domain's TLD, falling back to the generic parser otherwise.
    pub fn parse(domain: &str, whois_server: &str, raw: &str) -> Self {
        super::parsers::parse(domain, whois_server, raw)
    }

    /// The generic regex-based parser: the fallback for every TLD without a
    /// registry-specific parser (see [`parse`](Self::parse)).
    pub fn parse_internal(domain: &str, whois_server: &str, raw: &str) -> Self {
        let original = raw;
        let normalized = normalize_label_padding(raw);
        let raw: &str = &normalized;
        let registrar = extract_field_with_patterns(raw, &REGISTRAR_PATTERNS)
            .or_else(|| extract_section_value(raw, &["registrar"]));
        let registrant = extract_field_with_patterns(raw, &REGISTRANT_PATTERNS)
            .or_else(|| extract_section_value(raw, REGISTRANT_HEADINGS));
        let organization = extract_field_with_patterns(raw, &ORGANIZATION_PATTERNS);
        let registrant_email = extract_field_with_patterns(raw, &REGISTRANT_EMAIL_PATTERNS);
        let registrant_phone = extract_field_with_patterns(raw, &REGISTRANT_PHONE_PATTERNS);
        let registrant_address = extract_field_with_patterns(raw, &REGISTRANT_ADDRESS_PATTERNS);
        let registrant_country = extract_field_with_patterns(raw, &REGISTRANT_COUNTRY_PATTERNS);
        let admin_name = extract_field_with_patterns(raw, &ADMIN_NAME_PATTERNS);
        let admin_organization = extract_field_with_patterns(raw, &ADMIN_ORG_PATTERNS);
        let admin_email = extract_field_with_patterns(raw, &ADMIN_EMAIL_PATTERNS);
        let admin_phone = extract_field_with_patterns(raw, &ADMIN_PHONE_PATTERNS);
        let tech_name = extract_field_with_patterns(raw, &TECH_NAME_PATTERNS);
        let tech_organization = extract_field_with_patterns(raw, &TECH_ORG_PATTERNS);
        let tech_email = extract_field_with_patterns(raw, &TECH_EMAIL_PATTERNS);
        let tech_phone = extract_field_with_patterns(raw, &TECH_PHONE_PATTERNS);
        // Extract the raw date strings first so the registry's date order can
        // be inferred from any unambiguous one before parsing the ambiguous
        // ones (issue #47). A registry is internally consistent, so the order
        // revealed by one date applies to all dates in the response.
        // SWITCH (.ch/.li) puts the value on the line after the header.
        let creation_str = extract_field_with_patterns(raw, &CREATION_DATE_PATTERNS)
            .or_else(|| extract_section_value(raw, &["first registration date"]));
        let expiration_str = extract_field_with_patterns(raw, &EXPIRATION_DATE_PATTERNS);
        let updated_str = extract_field_with_patterns(raw, &UPDATED_DATE_PATTERNS);
        let date_order = infer_date_order(
            [&creation_str, &expiration_str, &updated_str]
                .into_iter()
                .flatten()
                .map(String::as_str),
        )
        .unwrap_or(DateOrder::DayFirst);
        let creation_date = creation_str
            .as_deref()
            .and_then(|s| parse_date_with_order(s, date_order));
        let expiration_date = expiration_str
            .as_deref()
            .and_then(|s| parse_date_with_order(s, date_order));
        let updated_date = updated_str
            .as_deref()
            .and_then(|s| parse_date_with_order(s, date_order));
        let nameservers = extract_nameservers(raw);
        let status = extract_status_top_level(raw);
        let dnssec = extract_field_with_patterns(raw, &DNSSEC_PATTERNS);

        WhoisResponse {
            domain: domain.to_string(),
            registrar,
            registrant,
            organization,
            registrant_email,
            registrant_phone,
            registrant_address,
            registrant_country,
            admin_name,
            admin_organization,
            admin_email,
            admin_phone,
            tech_name,
            tech_organization,
            tech_email,
            tech_phone,
            creation_date,
            expiration_date,
            updated_date,
            nameservers,
            status,
            dnssec,
            whois_server: whois_server.to_string(),
            raw_response: original.to_string(),
        }
    }

    /// True when a registrar or a registration date was extracted — what a
    /// registrar referral must carry to replace the registry's record.
    pub(crate) fn has_registration_fields(&self) -> bool {
        self.registrar.is_some() || self.creation_date.is_some() || self.expiration_date.is_some()
    }

    /// "Thin" = no positive registration signal at all: no registrar, no
    /// creation/expiry date, and no delegated nameservers. A thin body is what
    /// blocked or RDAP-first registries return for an unregistered domain.
    ///
    /// Nameservers count as registration data because some registries never
    /// publish a registrar or dates over port 43: DENIC (.de, which has no
    /// RDAP) returns only `Nserver`/`Status`/`Changed`, so without them every
    /// registered .de domain read as thin and was reported as "registry detail
    /// unavailable, retry shortly" with its WHOIS data discarded. Shared by
    /// [`is_available`](Self::is_available), the availability fallback ladder
    /// and the smart-lookup routes so they cannot drift.
    pub(crate) fn is_thin(&self) -> bool {
        !self.has_registration_fields() && self.nameservers.is_empty()
    }

    /// True when any registration field at all was extracted: the
    /// [`is_thin`](Self::is_thin) fields or a status.
    pub(crate) fn has_any_registry_field(&self) -> bool {
        !self.is_thin() || !self.status.is_empty()
    }

    /// Returns true if the response contains the core registration fields
    /// that registries typically provide (registrar, dates, nameservers).
    /// When true, following the registrar referral can be skipped since the
    /// additional detail (contact info) is usually GDPR-redacted anyway.
    ///
    /// Some registries (NIC.LV, SIDN/.nl) intentionally omit creation/expiry
    /// from their WHOIS, so accept a non-empty `status` field as an
    /// alternative registry signal alongside registrar + nameservers — this
    /// avoids a wasted referral attempt on every lookup for those TLDs.
    pub fn has_core_data(&self) -> bool {
        let has_dates_or_status = self.creation_date.is_some()
            || self.expiration_date.is_some()
            || !self.status.is_empty();
        self.registrar.is_some() && has_dates_or_status && !self.nameservers.is_empty()
    }

    /// Returns true when the registry's WHOIS server replied with a
    /// service-level "this TLD is not served here" / malformed-query sentinel
    /// instead of domain data — i.e. there is no usable port-43 WHOIS for this
    /// query. This is common for Identity Digital RDAP-only TLDs (.email,
    /// .life, .ninja, …) whose `whois.nic.<tld>` host answers "TLD is not
    /// supported." to every query and whose RDAP advertises `port43: null`.
    ///
    /// Distinct from [`is_available`](Self::is_available) (the domain is
    /// unregistered) and from a thin-but-valid record: it only fires when no
    /// registration field was extracted AND the body matches a known
    /// service-error sentinel at the start of a line.
    pub fn registry_unavailable(&self) -> bool {
        // Only meaningful when we extracted no registration data at all — a
        // record with a registrar / dates / nameservers / status is real data,
        // never a service error.
        if self.has_any_registry_field() {
            return false;
        }
        // Match known service-error sentinels at the start of a (trimmed) line,
        // mirroring `indicates_not_found`'s anchoring to avoid false positives
        // from TOS boilerplate that may quote these phrases.
        const SERVICE_ERROR_SENTINELS: &[&str] = &[
            "tld is not supported",
            "this tld is not",
            "malformed request",
            "invalid query",
            "no whois server is known",
            // Freenom's leftover .gq server: "This TLD has no whois server."
            "this tld has no whois server",
            "this server does not",
        ];
        // Registries retiring port-43 WHOIS under ICANN's RDAP transition
        // (e.g. GMO Registry, May 2026) answer every query with a prose
        // retirement notice; the phrase can sit mid-sentence, so it is
        // matched with contains() rather than the line-start sentinels.
        const SERVICE_RETIRED_PHRASES: &[&str] =
            &["whois service has been retired", "whois has been retired"];
        let lower = self.raw_response.to_lowercase();
        lower.lines().any(|line| {
            let t = line.trim_start();
            SERVICE_ERROR_SENTINELS.iter().any(|s| t.starts_with(s))
                || SERVICE_RETIRED_PHRASES.iter().any(|s| t.contains(s))
        })
    }

    pub fn is_available(&self) -> bool {
        // A response carrying concrete registration data is registered, full
        // stop — never let an unanchored substring match (a "not found" /
        // "object not found" fragment buried in an abuse-contact line, notice,
        // or registrant value) flip a registered domain to "available". This
        // guards the H6 false-positive class without having to anchor every
        // pattern (which would regress legitimate mid-line phrasings like
        // TWNIC "Domain not found." or HKIRC "...has not been registered.").
        if !self.is_thin() {
            return false;
        }

        // Scan the full response line-by-line (excluding empty lines). Some
        // registries (TWNIC, JPRS, NIC.br) prepend 3-4 notice lines before the
        // "no match" line, which would escape a small take(N) window.
        //
        // Comment markers are STRIPPED rather than skipped: many ccTLD
        // registries print the verdict itself on a comment line (AFNIC
        // "%% NOT FOUND", NORID "% No match", CZ.NIC "%ERROR:101: no entries
        // found", RESTENA "% No such domain" — captured live 2026-07). The
        // word-count gate and the non-availability veto below still shield
        // against TOS prose on those same comment lines.
        //
        // Stream the scan line-by-line — avoids the ~1 MB `Vec<&str>` +
        // ~1 MB joined `String` the previous implementation allocated for
        // every call. Each line's lowercase form is a fresh small `String`
        // (the size of one line, not the whole body) which is dropped at
        // the end of the iteration.
        for line in self.raw_response.lines() {
            let content = line.trim().trim_start_matches(['%', '#']).trim_start();
            if content.is_empty() {
                continue;
            }
            // Normalize internal whitespace (tabs, runs of spaces) to single
            // spaces before matching. Registries like DNS Belgium print
            // "Status:\tAVAILABLE" with a tab, which would otherwise slip
            // past space-delimited patterns such as "status: available".
            let lower = content.to_lowercase();
            let words: Vec<&str> = lower.split_whitespace().collect();
            let normalized = words.join(" ");
            // A line that negates or refuses availability is never an
            // availability indicator, even when it contains an availability
            // substring (e.g. "available for registration" inside "not
            // available for registration", or "no data found" inside a
            // rate-limit banner). Skip it BEFORE the positive match so the
            // unanchored contains() cannot invert a refused/reserved name into
            // "available" (issue #45).
            if is_non_availability_line(&normalized) {
                continue;
            }
            // Sentence-form verdicts (KISA, EDUCAUSE, NASK) run past the word
            // gate; they are matched anchored at line start instead, which a
            // footer merely *quoting* the phrase mid-sentence cannot satisfy.
            if AVAILABILITY_SENTENCE_PATTERNS
                .iter()
                .any(|p| normalized.starts_with(p))
            {
                return true;
            }
            // Availability indicators are short status lines — the longest
            // known registry phrasing ("No information was found matching
            // that query.") is 7 words. Anything longer is prose (a TOS or
            // notice footer) that may merely quote a phrase like "not found"
            // or "does not exist"; skipping it avoids flipping a registered
            // (but thin, fieldless) response to "available". The H6 guard
            // above already covers responses that DO carry registration data.
            if words.len() > MAX_STATUS_LINE_WORDS {
                continue;
            }
            if AVAILABILITY_PATTERNS.iter().any(|p| normalized.contains(p)) {
                return true;
            }
            // SIDN (.nl) / SETAR (.aw) style "<domain> is free": suffix-anchored
            // so prose like "registration is free of charge" cannot match.
            if normalized.ends_with(" is free") {
                return true;
            }
        }
        false
    }

    /// Checks if the response indicates the registrar doesn't have data for this domain.
    /// This is different from is_available() - the domain may exist at the registry level
    /// but the referral registrar may not have data for it.
    ///
    /// Matches patterns only at the start of a (trimmed) line to avoid false
    /// positives from TOS footer boilerplate that may quote these phrases.
    pub fn indicates_not_found(&self) -> bool {
        let lower = self.raw_response.to_lowercase();
        lower.lines().any(|line| {
            let t = line.trim_start();
            NOT_FOUND_PATTERNS.iter().any(|p| t.starts_with(p))
        })
    }

    /// Returns true when the WHOIS body explicitly *refuses*, *throttles*, or
    /// *negates* availability rather than answering it: a rate-limit / quota /
    /// access-denied banner, a port-43 refusal, a reserved/blocked status, or an
    /// explicit "not available for registration". Used by the availability
    /// fallback ([`crate::availability`]) to route such bodies to an
    /// inconclusive verdict instead of guessing "available"/"registered" from
    /// weaker signals like DNS presence.
    ///
    /// Distinct from [`is_available`](Self::is_available) (a conclusive
    /// "no match") and [`registry_unavailable`](Self::registry_unavailable)
    /// (the TLD has no usable port-43 WHOIS server at all). Scans every
    /// non-comment line (no word-count gate) so a sentence-form refusal like
    /// SWITCH's "Requests of this client are not permitted." is caught.
    pub fn indicates_registry_refusal(&self) -> bool {
        for line in self.raw_response.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('%') {
                continue;
            }
            let lower = trimmed.to_lowercase();
            let normalized = lower.split_whitespace().collect::<Vec<_>>().join(" ");
            if is_non_availability_line(&normalized) {
                return true;
            }
        }
        false
    }
}

/// Maximum word count for a line to be considered an availability *status*
/// line rather than prose. Registry "not found" phrasings are short (the
/// longest observed is 7 words); TOS/notice footers that merely quote such
/// phrases run much longer. Lines above this bound are ignored by
/// `is_available()` so footer prose can't flip a thin response to available.
const MAX_STATUS_LINE_WORDS: usize = 10;

/// Patterns indicating a domain is available (unregistered).
/// Matched case-insensitively via `contains()` on short status lines only
/// (see `MAX_STATUS_LINE_WORDS`).
const AVAILABILITY_PATTERNS: &[&str] = &[
    "no match for",
    "no match",
    "not found",
    "no data found",
    "no entries found",
    "domain not found",
    "available for registration",
    "not registered",
    // HKIRC (.hk / .香港) phrases it "has not been registered" — the bare
    // "not registered" above does not cover the interposed "been".
    "not been registered",
    "status: available",
    "status: free",
    "no object found",
    "does not exist",
    // Additional registry phrasings surfaced by a cross-TLD audit, mostly
    // no-RDAP ccTLDs where WHOIS is the only registry signal. All are unique
    // to "not found" responses (verified not to collide with registered or
    // "not available" bodies).
    "nothing found", // KazNIC .kz / .қаз ("*** Nothing found for this query.") and NIC.AT .at
    "no found",      // TWNIC .tw / 台灣 / 台湾 ("No Found")
    "no record found", // .ls and others ("No record found for '...'.")
    "no information was found", // .africa ("No information was found matching that query.")
    "object not found", // generic ("Object not found")
    "not find matchingrecord", // CONAC .政务 / .公益 ("Not find MatchingRecord")
    // Phrasings surfaced by the 2026-07 full-TLD live sweep:
    "no such domain",             // RESTENA .lu ("% No such domain")
    "object_not_found",           // NIC Mexico .mx ("No_Se_Encontro_El_Objeto/Object_Not_Found")
    "no se encuentra registrado", // NIC Argentina .ar (Spanish-only response)
    // ISOC-IL .il / .ישראל: "% No data was found to match the request
    // criteria." — "was" breaks the bare "no data found" pattern above.
    "no data was found",
];

/// Sentence-form "not found" verdicts that exceed [`MAX_STATUS_LINE_WORDS`].
/// Matched with `starts_with` on the normalized line (anchored), so TOS
/// footers that merely quote such a phrase mid-sentence cannot match.
/// Wording captured live 2026-07.
const AVAILABILITY_SENTENCE_PATTERNS: &[&str] = &[
    // KISA .kr: "The requested domain was not found in the Registry or
    // Registrar’s WHOIS Server."
    "the requested domain was not found",
    // EDUCAUSE .edu: "The domain name you requested was not found in our
    // database."
    "the domain name you requested was not found",
    // NASK .pl: "No information available about domain name <x> in the
    // Registry NASK database."
    "no information available about domain name",
];

/// Phrases that mark a status line as the *opposite* of available — an explicit
/// negation ("not available"), a reserved/blocked status, or a throttle/refusal
/// (rate limit, quota, access denied). Checked BEFORE [`AVAILABILITY_PATTERNS`]
/// in `is_available` so an unanchored positive substring (e.g. "available for
/// registration" inside "not available for registration", or "no data found"
/// inside a rate-limit banner) cannot invert a refused/reserved name into
/// "available, high confidence" (issue #45). Also backs
/// [`WhoisResponse::indicates_registry_refusal`] for routing such bodies to an
/// inconclusive availability verdict.
///
/// Every entry here contains a space, so it can never occur inside a domain
/// name and is safely matched with `contains()`. Single-token markers live in
/// [`NON_AVAILABILITY_WORDS`].
const NON_AVAILABILITY_PATTERNS: &[&str] = &[
    "not available", // "...is not available for registration."
    // Reserved-status phrasings. Deliberately NOT the bare word "reserved":
    // nearly every WHOIS body ends with an "All rights reserved." copyright
    // footer, and matching it would misroute genuinely-unregistered domains
    // to "inconclusive" before the DNS tie-breaker runs.
    "reserved -",    // "reserved - not registered for public use"
    "is reserved",   // "this name is reserved by the registry"
    "been reserved", // "this domain has been reserved"
    "reserved by",   // "reserved by the registry operator"
    "reserved for",  // "reserved for future use"
    "status: reserved",
    "reserved domain", // "Reserved Domain Name" (ICANN reserved names)
    "reserved name",
    "rate limit", // "rate limited" / "Access rate limited; ..."
    "rate exceeded",
    "too many requests",
    "access denied",
    "not permitted", // SWITCH .ch "Requests of this client are not permitted."
    "try again",     // throttle hint ("please try again later")
    "temporarily unavailable",
];

/// Single-token refusal / throttle markers. Unlike the phrases above these
/// can occur INSIDE the domain name a "no match" line echoes back
/// (`quotations.pl`, `UNBLOCKED-GAMES.COM`, `refused.ls`), which would turn a
/// conclusive "available" into "inconclusive". They are therefore matched as
/// whole words only — see [`contains_word`].
const NON_AVAILABILITY_WORDS: &[&str] = &[
    "rate-limit",   // hyphenated variant of "rate limit"
    "rate-limited", // "Your IP has been rate-limited."
    "quota",
    "denied",
    "refused",
    "blocked",
];

/// True when a normalized (lowercased, single-spaced) line negates, refuses
/// or throttles availability.
fn is_non_availability_line(normalized: &str) -> bool {
    NON_AVAILABILITY_PATTERNS
        .iter()
        .any(|p| normalized.contains(p))
        || NON_AVAILABILITY_WORDS
            .iter()
            .any(|w| contains_word(normalized, w))
}

/// Characters that can be part of a domain-name label.
fn is_label_char(c: char) -> bool {
    c.is_alphanumeric() || c == '-' || c == '_'
}

/// True when `word` occurs in `haystack` as a whole word rather than as part
/// of a domain name: it may not touch a label character on either side, nor a
/// `.` that joins it to another label (`refused.ls`, `www.blocked`). A `.`
/// that merely ends the sentence (`Query refused.`) is still a boundary.
fn contains_word(haystack: &str, word: &str) -> bool {
    haystack.match_indices(word).any(|(start, _)| {
        let before_ok = haystack[..start]
            .chars()
            .next_back()
            .is_none_or(|c| !is_label_char(c) && c != '.');
        let mut after = haystack[start + word.len()..].chars();
        let after_ok = match after.next() {
            None => true,
            Some('.') => after.next().is_none_or(|c| !is_label_char(c)),
            Some(c) => !is_label_char(c),
        };
        before_ok && after_ok
    })
}

/// Patterns indicating the registrar didn't have data for this domain.
/// Matched at the start of a trimmed line (not inside TOS footers).
const NOT_FOUND_PATTERNS: &[&str] = &[
    "no match for",
    "domain not found",
    "no data found",
    "queried object does not exist",
    "object does not exist",
    "not found:",
    "status: free",
    "domain is not registered",
];

pub(super) fn extract_field_with_patterns(text: &str, patterns: &[Regex]) -> Option<String> {
    for re in patterns {
        // The first occurrence of this label that carries a value. An empty
        // occurrence (`Label: \r\n` — the `(.+)` captures just the `\r`) is
        // skipped so CRLF and LF bodies behave alike: under LF the regex
        // engine already steps past an empty `Label:\n` line on its own.
        let first_value = re
            .captures_iter(text)
            .filter_map(|caps| caps.get(1))
            .map(|m| m.as_str().trim())
            .find(|v| !v.is_empty());
        if let Some(value) = first_value {
            if !is_placeholder_value(value) {
                return Some(decode_html_entities(value).into_owned());
            }
        }
    }
    None
}

/// Named HTML entities registries leave in plain-text replies (NIC Togo
/// `Activ&eacute;`): markup basics and the accented Latin letters of the
/// French-, Spanish- and Portuguese-speaking registries.
const HTML_ENTITIES: &[(&str, &str)] = &[
    ("amp", "&"),
    ("lt", "<"),
    ("gt", ">"),
    ("quot", "\""),
    ("apos", "'"),
    ("nbsp", " "),
    ("aacute", "á"),
    ("agrave", "à"),
    ("acirc", "â"),
    ("atilde", "ã"),
    ("auml", "ä"),
    ("eacute", "é"),
    ("egrave", "è"),
    ("ecirc", "ê"),
    ("euml", "ë"),
    ("iacute", "í"),
    ("icirc", "î"),
    ("iuml", "ï"),
    ("oacute", "ó"),
    ("ocirc", "ô"),
    ("otilde", "õ"),
    ("ouml", "ö"),
    ("uacute", "ú"),
    ("ugrave", "ù"),
    ("ucirc", "û"),
    ("uuml", "ü"),
    ("ccedil", "ç"),
    ("ntilde", "ñ"),
    ("Aacute", "Á"),
    ("Agrave", "À"),
    ("Eacute", "É"),
    ("Egrave", "È"),
    ("Ccedil", "Ç"),
    ("Ntilde", "Ñ"),
];

/// Decodes HTML entities in a reply value: the named ones in
/// [`HTML_ENTITIES`] and numeric `&#233;` / `&#xE9;`. Anything else,
/// including a bare `&`, is left as written.
fn decode_html_entities(value: &str) -> std::borrow::Cow<'_, str> {
    static_regex! {
        ENTITY = r"&(#[0-9]{1,7}|#[xX][0-9A-Fa-f]{1,6}|[A-Za-z]{2,8});";
    }
    if !value.contains('&') {
        return std::borrow::Cow::Borrowed(value);
    }
    ENTITY.replace_all(value, |caps: &regex::Captures<'_>| {
        let name = &caps[1];
        let decoded = if let Some(num) = name.strip_prefix('#') {
            let code = match num.strip_prefix(['x', 'X']) {
                Some(hex) => u32::from_str_radix(hex, 16).ok(),
                None => num.parse().ok(),
            };
            code.and_then(char::from_u32).map(String::from)
        } else {
            HTML_ENTITIES
                .iter()
                .find(|(n, _)| *n == name)
                .map(|(_, c)| (*c).to_string())
        };
        decoded.unwrap_or_else(|| caps[0].to_string())
    })
}

/// Registry/registrar boilerplate printed in place of contact data — most
/// often in the `Registrant Email:` slot of post-GDPR gTLD output — that is
/// NOT a value ("Please query the RDDS service of the Registrar of Record
/// identified in this output for information on how to contact the
/// Registrant, …").
const PLACEHOLDER_PHRASES: &[&str] = &[
    "please query the rdds",
    "please query the whois",
    "please ask the registrar",
    "how to contact the registrant",
    "select request email form",    // MarkMonitor
    "select contact domain holder", // GoDaddy
];

/// True for values that are privacy/redaction placeholders or boilerplate
/// rather than real data ("REDACTED FOR PRIVACY", "Not disclosed", DNS
/// Belgium's "Not shown, please visit www.dnsbelgium.be for webbased whois.",
/// [`PLACEHOLDER_PHRASES`], "N/A").
fn is_placeholder_value(value: &str) -> bool {
    let lower = value.to_lowercase();
    lower.contains("redacted")
        || lower.contains("data protected")
        || lower.contains("privacy")
        || lower.contains("not disclosed")
        || lower.contains("not shown")
        || lower.contains("withheld")
        || PLACEHOLDER_PHRASES.iter().any(|p| lower.contains(p))
        || lower == "n/a"
        || lower == "none"
        // THNIC (.th) `Tech Organization: Personal Information`
        || lower == "personal information"
        // Mediaserv (.gf/.mq) in place of an unpublished contact
        || lower == "no object found!"
}

/// Sub-field keys that name the entity inside a section: `Name:`, KazNIC
/// `Organization Name:`, `.sn` `Nom:`.
const SECTION_NAME_KEYS: &[&str] = &["name", "organization name", "organisation name", "nom"];

/// Section-style fallback for registries that print a heading on its own line
/// and the entity under it — NASK (`REGISTRAR:` / `MarkMonitor, Inc.`), DNS
/// Belgium (`Registrar:` / `\tName:\t MarkMonitor Inc.`), TWNIC
/// (`Registrant:` / blank / `      Google LLC`), METU (`** Registrar:` /
/// `NIC Handle: …` / `Organization Name: …`), Traficom (`Holder` /
/// `name: …`), `.sn` (`[HOLDER]` / … / `Nom: …`).
///
/// The heading is a whole line equal to one of `labels`, optionally marked
/// `**` or bracketed and with or without a colon. Its body runs to the next
/// blank line (one blank line straight after the heading is allowed). The
/// value is the body's first line when it is bare (no `:`), or else the
/// first [`SECTION_NAME_KEYS`] sub-field. Any other `Key: value` line — most
/// importantly `Registrar IANA ID: 376` — is never taken as the value, which
/// is exactly the misattribution the horizontal-whitespace field patterns
/// exist to prevent.
fn extract_section_value(text: &str, labels: &[&str]) -> Option<String> {
    let mut lines = text.lines();
    while let Some(line) = lines.next() {
        if !is_section_heading(line, labels) {
            continue;
        }
        let mut first = true;
        let mut skipped_blank = false;
        for body in lines.by_ref() {
            let body = body.trim();
            if body.is_empty() {
                if first && !skipped_blank {
                    skipped_blank = true;
                    continue;
                }
                break;
            }
            let value = match body.split_once(':') {
                None if first => Some(body),
                None => None,
                Some((key, value)) => SECTION_NAME_KEYS
                    .iter()
                    .any(|k| key.trim().eq_ignore_ascii_case(k))
                    .then(|| value.trim()),
            };
            first = false;
            if let Some(value) = value.filter(|v| !v.is_empty() && !is_placeholder_value(v)) {
                return Some(value.to_string());
            }
        }
    }
    None
}

/// Whether `line` is a bare heading for one of `labels`: `Registrant`,
/// `Registrant:`, `** Registrant:` or `[HOLDER]`, compared case-insensitively.
fn is_section_heading(line: &str, labels: &[&str]) -> bool {
    let heading = line
        .trim()
        .trim_start_matches('*')
        .trim()
        .trim_end_matches(':')
        .trim_end();
    let heading = heading
        .strip_prefix('[')
        .and_then(|h| h.strip_suffix(']'))
        .unwrap_or(heading);
    labels.iter().any(|l| heading.eq_ignore_ascii_case(l))
}

/// Interpretation order for ambiguous all-numeric dates (`A/B/YYYY`,
/// `A.B.YYYY` or `A-B-YYYY` where both `A` and `B` are <= 12). `DayFirst` reads them as
/// `DD/MM` (the international norm, Seer's documented default); `MonthFirst`
/// reads them as `MM/DD` (the US convention). Unambiguous dates (a field > 12,
/// ISO, or named-month) parse identically under either order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DateOrder {
    DayFirst,
    MonthFirst,
}

/// Infer the date order for a response from any *unambiguous* candidate date: a
/// numeric `A/B/YYYY` or `A.B.YYYY` where exactly one of the first two fields
/// exceeds 12 reveals whether the registry writes day-first or month-first.
/// Registries are internally consistent, so one unambiguous date fixes the order
/// for every ambiguous date in the same response. Returns `None` when nothing
/// disambiguates (ISO, named-month, or both fields no greater than 12) — callers
/// then fall back to the documented [`DateOrder::DayFirst`] default. This
/// replaces the old hardcoded global DMY tie-break with per-response (hence
/// per-registry) evidence, fixing US `MM/DD/YYYY` registries without a fragile
/// server table (issue #47).
fn infer_date_order<'a>(candidates: impl IntoIterator<Item = &'a str>) -> Option<DateOrder> {
    static_regex! {
        NUMERIC_DATE = r"^\s*(\d{1,2})[/.-](\d{1,2})[/.-]\d{4}\b";
    }
    for s in candidates {
        if let Some(c) = NUMERIC_DATE.captures(s) {
            if let (Ok(a), Ok(b)) = (c[1].parse::<u32>(), c[2].parse::<u32>()) {
                if a > 12 && b <= 12 {
                    return Some(DateOrder::DayFirst); // first field can only be a day
                }
                if b > 12 && a <= 12 {
                    return Some(DateOrder::MonthFirst); // second field can only be a day
                }
            }
        }
    }
    None
}

/// Parses a zone-less timestamp a registry writes in a fixed local time
/// (JPRS: JST, UTC+9; CNNIC: CST, UTC+8) into UTC. `date_fmt` is the
/// registry's date layout; `<date> HH:MM:SS` is shifted by the offset, while
/// a bare date stays midnight UTC, since shifting it would move it onto the
/// previous calendar day.
pub(crate) fn parse_fixed_offset_date(
    value: &str,
    date_fmt: &str,
    utc_offset_hours: i64,
) -> Option<DateTime<Utc>> {
    let value = value.trim();
    if let Ok(local) = NaiveDateTime::parse_from_str(value, &format!("{date_fmt} %H:%M:%S")) {
        // Checked: the body is untrusted (port 43 is plaintext), and a year
        // at chrono's lower bound would make the plain `-` operator panic.
        return local
            .and_utc()
            .checked_sub_signed(Duration::hours(utc_offset_hours));
    }
    NaiveDate::parse_from_str(value, date_fmt)
        .ok()
        .map(|date| date.and_time(NaiveTime::MIN).and_utc())
}

/// Splits a trailing UTC offset (`+03`, `+0530`, `GMT+1`, `(UTC+8)`) off a
/// date-time, returning the local part and the offset to subtract. Only a
/// value with a time of day qualifies: shifting a bare date would move it
/// onto another calendar day (the rule [`parse_fixed_offset_date`] follows).
fn split_utc_offset(value: &str) -> Option<(&str, Duration)> {
    static_regex! {
        UTC_OFFSET = r"^(.*\d:\d{2}(?::\d{2})?(?:\.\d+)?)[ \t]*\(?(?:UTC|GMT)?[ \t]*([+-])(\d{1,2})(?::?(\d{2}))?\)?$";
    }
    let caps = UTC_OFFSET.captures(value)?;
    let hours: i64 = caps.get(3)?.as_str().parse().ok()?;
    let minutes: i64 = caps.get(4).map_or(Some(0), |m| m.as_str().parse().ok())?;
    if hours > 14 || minutes > 59 {
        return None;
    }
    let offset = Duration::minutes(hours * 60 + minutes);
    let offset = if &caps[2] == "-" { -offset } else { offset };
    Some((caps.get(1)?.as_str(), offset))
}

/// Parse a date string from registry output into a UTC datetime, using the
/// documented international day-first interpretation for ambiguous all-numeric
/// dates. Thin wrapper over [`parse_date_with_order`].
pub(crate) fn parse_date(date_str: &str) -> Option<DateTime<Utc>> {
    parse_date_with_order(date_str, DateOrder::DayFirst)
}

/// Parse a date string from registry output into a UTC datetime, tolerating the
/// ~20 formats registries emit in practice. `order` decides how an ambiguous
/// all-numeric date is read (see [`DateOrder`]); unambiguous dates parse the
/// same either way. Shared with the RDAP parser (RDAP's `eventDate` is nominally
/// strict RFC 3339, but real servers are as sloppy as WHOIS, so both reuse this
/// tolerant parser).
pub(crate) fn parse_date_with_order(date_str: &str, order: DateOrder) -> Option<DateTime<Utc>> {
    static_regex! {
        // Registro.br appends the registration ticket: `created: 19970711 #46903`.
        TICKET_SUFFIX = r"\s+#\d+$";
    }
    // The longest known form is ~35 bytes (RFC 3339 with nanoseconds and an
    // offset); the cap leaves room for unseen registry spellings while
    // keeping a hostile value from costing a regex pass per format below.
    const MAX_DATE_LEN: usize = 128;
    // A trailing ` UTC` is `Z`; mid-value (`10:30:00 UTC-5`) it introduces
    // an offset, which `split_utc_offset` handles.
    let trimmed = date_str.trim();
    if trimmed.len() > MAX_DATE_LEN {
        return None;
    }
    let zulu = trimmed.strip_suffix(" UTC").map(|d| format!("{d}Z"));
    let cleaned = zulu
        .as_deref()
        .unwrap_or(trimmed)
        .replace(" (UTC)", "")
        // KazNIC (.kz): `1999-08-17 21:34:57 (GMT+0:00)`
        .replace(" (GMT+0:00)", "")
        .replace(" +0000", "Z");
    let cleaned = TICKET_SUFFIX.replace(&cleaned, "");
    // METU (.tr) ends its dates with a period: `2001-Aug-23.`
    let cleaned = cleaned.trim_end_matches('.');

    // First: try RFC 3339, which handles any timezone offset (e.g., +05:30, +01:00, Z)
    if let Ok(dt) = DateTime::parse_from_rfc3339(cleaned) {
        return Some(dt.with_timezone(&Utc));
    }

    // Second: try ISO 8601 with timezone offset (e.g., 2024-01-15T10:30:00+05:30)
    if let Ok(dt) = DateTime::<FixedOffset>::parse_from_str(cleaned, "%Y-%m-%dT%H:%M:%S%z") {
        return Some(dt.with_timezone(&Utc));
    }

    // Third: try space-separated datetime with timezone offset (e.g., 2024-01-15 10:30:00+05:30)
    if let Ok(dt) = DateTime::<FixedOffset>::parse_from_str(cleaned, "%Y-%m-%d %H:%M:%S%z") {
        return Some(dt.with_timezone(&Utc));
    }

    // Then a local time with a trailing UTC offset in a form chrono's `%z`
    // does not take — `+03` (Hostmaster .ua), `GMT+1` (ATI .tn), `(UTC+8)`
    // (TWNIC .tw): parse the local part with the formats below, then shift.
    // Exactly one offset is split off: the local part goes straight to the
    // naive formats, so a chain of offsets (`1:00-1:00-1:00…`) fails there
    // instead of recursing once per link.
    if let Some((local, offset)) = split_utc_offset(cleaned) {
        return parse_naive_date(local, order)?.checked_sub_signed(offset);
    }
    // Last resort: chrono's own lenient ISO 8601 reader. Kept out of
    // `parse_naive_date`: it also takes an offset, so it would let a split
    // local part carry a second one.
    parse_naive_date(cleaned, order).or_else(|| cleaned.parse::<DateTime<Utc>>().ok())
}

/// The timezone-less tail of [`parse_date_with_order`]: `cleaned` is already
/// normalized, and its time of day is read as UTC.
fn parse_naive_date(cleaned: &str, order: DateOrder) -> Option<DateTime<Utc>> {
    // Fourth: try NaiveDateTime / NaiveDate formats (timezone-less dates).
    // Unambiguous formats (year-first, named-month) first — these never depend
    // on the day/month order.
    const UNAMBIGUOUS_FORMATS: &[&str] = &[
        "%Y-%m-%dT%H:%M:%SZ",
        "%Y-%m-%dT%H:%M:%S%.fZ",
        // Naive ISO datetime, read as UTC (DENIC `Changed:`).
        "%Y-%m-%dT%H:%M:%S",
        "%Y-%m-%d %H:%M:%S",
        // NIC.ar `changed: 2023-07-17 17:23:05.989470`
        "%Y-%m-%d %H:%M:%S%.f",
        "%d-%b-%Y %H:%M:%S",
        "%d-%b-%Y %H:%M:%S%.f",
        // " UTC" is normalized to "Z" at the top, so this also reads "... UTC".
        "%d-%b-%Y %H:%M:%SZ",
        "%Y-%m-%d",
        "%d-%b-%Y",
        "%d-%B-%Y",
        // NASK (.pl): `created: 2002.09.19 13:00:00`
        "%Y.%m.%d %H:%M:%S",
        "%Y.%m.%d",
        "%Y/%m/%d %H:%M:%S",
        "%Y/%m/%d",
        "%b %d %Y",
        // ISNIC (.is): `created: September  5 2000`
        "%B %d %Y",
        // DNS Belgium (.be): `Registered: Tue Dec 12 2000`
        "%a %b %d %Y",
        // ctime, KG domain registry (.kg): `Record created: Tue Jan 16 10:31:46 2001`
        "%a %b %d %H:%M:%S %Y",
        // Registro.br (.br): `created: 19970711` (ticket suffix stripped above)
        "%Y%m%d",
        // nic.at (.at): `registered: 20000825 20:16:35`
        "%Y%m%d %H:%M:%S",
        // THNIC (.th): `Created date: 17 Jul 2014`
        "%d %b %Y",
        // NITC (.jo): `Updated Date: Jul 26 2005 12:00AM`
        "%b %d %Y %I:%M%p",
        // METU (.tr): `Created on: 2001-Aug-23.` (trailing dot stripped above)
        "%Y-%b-%d",
    ];
    // Ambiguous all-numeric formats, tried in the hinted order first. The
    // other order is still tried second so an unambiguous date (a field > 12)
    // is recovered rather than dropped — the second pass can only succeed for
    // an input the first rejected, so it never reinterprets an accepted date.
    // Each has a time-of-day variant (CZ.NIC: `registered: 18.09.2000
    // 13:05:00`); the date part obeys the same order rules.
    // HKIRC (.hk) separates with dashes: `Expiry Date: 31-03-2027`.
    const DAY_FIRST: &[&str] = &[
        "%d.%m.%Y %H:%M:%S",
        "%d.%m.%Y",
        "%d/%m/%Y %H:%M:%S",
        "%d/%m/%Y",
        // ATI (.tn): `14-07-2009 00:00:00 GMT+1` (offset split off first)
        "%d-%m-%Y %H:%M:%S",
        "%d-%m-%Y",
    ];
    const MONTH_FIRST: &[&str] = &[
        "%m.%d.%Y %H:%M:%S",
        "%m.%d.%Y",
        "%m/%d/%Y %H:%M:%S",
        "%m/%d/%Y",
        "%m-%d-%Y %H:%M:%S",
        "%m-%d-%Y",
    ];
    let (first_pair, second_pair) = match order {
        DateOrder::DayFirst => (DAY_FIRST, MONTH_FIRST),
        DateOrder::MonthFirst => (MONTH_FIRST, DAY_FIRST),
    };

    for fmt in UNAMBIGUOUS_FORMATS
        .iter()
        .chain(first_pair.iter())
        .chain(second_pair.iter())
    {
        if let Ok(dt) = NaiveDateTime::parse_from_str(cleaned, fmt) {
            return Some(dt.and_utc());
        }
        if let Ok(d) = NaiveDate::parse_from_str(cleaned, fmt) {
            return Some(d.and_hms_opt(0, 0, 0)?.and_utc());
        }
    }
    None
}

fn extract_nameservers(text: &str) -> Vec<String> {
    let nameservers = extract_labelled_nameservers(text);
    if nameservers.is_empty() {
        extract_nameserver_block(text)
    } else {
        nameservers
    }
}

/// Headings (lowercased, colon optional) that introduce a block of bare
/// hostname lines instead of `Label: host` fields.
const NAMESERVER_HEADINGS: &[&str] = &[
    "name servers",                     // Island Networks (.gg/.je), NIC México (.mx)
    "dns servers",                      // AMNIC (.am)
    "name server information",          // Register.bg (.bg)
    "name servers information",         // HKIRC (.hk)
    "name servers in the listed order", // KG domain registry (.kg)
    "nameservers",                      // DNS Belgium (.be)
    "domain nameservers",               // SETAR (.aw)
    "domain servers in listed order",   // TWNIC (.tw)
    "domain servers",                   // METU (.tr): `** Domain Servers:`
];

/// Prefixes some registries put before each host in a heading block:
/// NIC México `DNS: ns.example.mx`, ATI (.tn) `Name: ns4.ati.tn.` (after
/// [`normalize_label_padding`]).
const NAMESERVER_ENTRY_PREFIXES: &[&str] = &["dns:", "name:"];

/// Section-style fallback for registries that list nameservers one per line
/// under a heading. Blank lines between the heading and the first host are
/// skipped (HKIRC); the block ends at the first blank or non-hostname line, so
/// trailing notices can never be read as hosts. Glue after the hostname is
/// dropped, as in [`extract_labelled_nameservers`], and so is the `DNS:`
/// prefix NIC México puts on each entry.
fn extract_nameserver_block(text: &str) -> Vec<String> {
    let mut nameservers = Vec::new();
    let mut lines = text.lines();
    while let Some(line) = lines.next() {
        // METU (.tr) marks headings with `** `.
        let heading = line
            .trim()
            .trim_start_matches('*')
            .trim_start()
            .trim_end_matches(':')
            .to_lowercase();
        if !NAMESERVER_HEADINGS.contains(&heading.as_str()) {
            continue;
        }
        let mut started = false;
        for line in lines.by_ref() {
            let entry = line.trim_start();
            let entry = NAMESERVER_ENTRY_PREFIXES
                .iter()
                .find_map(|p| {
                    entry
                        .get(..p.len())
                        .filter(|head| head.eq_ignore_ascii_case(p))
                        .map(|_| &entry[p.len()..])
                })
                .unwrap_or(entry);
            let host = entry.split_whitespace().next().unwrap_or("");
            if host.is_empty() && !started {
                continue;
            }
            if !is_hostname(host) {
                break;
            }
            started = true;
            if let Some(ns) = clean_nameserver(host) {
                push_bounded(&mut nameservers, ns, MAX_NAMESERVERS);
            }
        }
        if !nameservers.is_empty() {
            break;
        }
    }
    nameservers
}

/// A dotted DNS name (`ns1.example.com`, optional trailing root dot).
fn is_hostname(s: &str) -> bool {
    static_regex! {
        HOSTNAME = r"^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z][A-Za-z0-9-]{0,62}\.?$";
    }
    HOSTNAME.is_match(s)
}

/// Values registries print in a nameserver slot that are not a nameserver
/// (UZINFOCOM .uz: `Name Server: not.defined.`, in WHOIS and RDAP alike).
const NAMESERVER_PLACEHOLDERS: &[&str] = &["not.defined"];

/// Whether a nameserver name (any case, trailing dot or not) is a
/// placeholder rather than a host. Shared with the RDAP nameserver list.
pub(crate) fn is_nameserver_placeholder(name: &str) -> bool {
    let name = name.trim_end_matches('.');
    NAMESERVER_PLACEHOLDERS
        .iter()
        .any(|p| name.eq_ignore_ascii_case(p))
}

/// One nameserver token in canonical form: lowercased, without the trailing
/// root dot TCI (.ru/.su) and UZINFOCOM (.uz) print (`ns5.nic.ru.`), so it
/// compares equal to the same host from RDAP or DNS. `None` for a
/// placeholder.
fn clean_nameserver(token: &str) -> Option<String> {
    let ns = token.trim_end_matches('.').to_lowercase();
    (!ns.is_empty() && !is_nameserver_placeholder(&ns)).then_some(ns)
}

/// Nameservers from `Label: host` fields ([`NAMESERVER_PATTERNS`]).
fn extract_labelled_nameservers(text: &str) -> Vec<String> {
    let mut nameservers = Vec::new();

    for re in NAMESERVER_PATTERNS.iter() {
        for caps in re.captures_iter(text) {
            if nameservers.len() >= MAX_NAMESERVERS {
                return nameservers;
            }
            if let Some(m) = caps.get(1) {
                // Strip glue IP addresses that some registries append after the hostname
                // e.g., "ns1.example.br 200.1.2.3 2001:db8::1" → "ns1.example.br"
                let raw = m.as_str().trim();
                if let Some(ns) = clean_nameserver(raw.split_whitespace().next().unwrap_or(raw)) {
                    push_bounded(&mut nameservers, ns, MAX_NAMESERVERS);
                }
            }
        }
    }

    nameservers
}

/// Headings (compared case-insensitively, `%`/`#` and trailing colon
/// stripped) that open a contact section, which runs to the next blank line.
/// Contact sections carry their own `Status:` / `State:` lines — a contact
/// object's `status: linked` (Hostmaster .ua), an address `State: Nuevo Leon`
/// (NIC México), `State: VKO` (KazNIC) — so the status scan skips them.
/// KazNIC prints the domain's own status after its contacts, so the scan
/// resumes after the section rather than stopping.
const CONTACT_HEADINGS: &[&str] = &[
    "registrant",
    "registrant contact",
    "owner contact",
    "holder",
    "domain holder",
    "admin contact",
    "administrative contact",
    "administrative contacts",
    "tech contact",
    "technical contact",
    "technical contacts",
    "billing contact",
    "billing contacts",
];

/// Whether `line` is a bare contact-section heading (`Registrant:`,
/// `Registrant`, `% Administrative Contacts:`) with no value after it.
fn is_contact_heading(line: &str) -> bool {
    let heading = line
        .trim()
        .trim_start_matches(['%', '#'])
        .trim()
        .trim_end_matches(':')
        .trim_end();
    CONTACT_HEADINGS
        .iter()
        .any(|h| heading.eq_ignore_ascii_case(h))
}

/// Line prefixes (lowercase, ASCII) that introduce domain status values.
const STATUS_LABELS: &[&str] = &[
    "domain status:",
    // Register.bg (.bg): `registration status: busy, active`
    "registration status:",
    "status:",
    // TCI (.ru/.su): `state: REGISTERED, DELEGATED, VERIFIED`
    "state:",
    // ANINF (.ga), NIC Sénégal (.sn): `Statut: actif`
    "statut:",
    // MoldData (.md): `Domain state: OK`
    "domain state:",
    // RESTENA (.lu): `domaintype: ACTIVE`
    "domaintype:",
];

static_regex! {
    // KG domain registry (.kg) puts the status after the name.
    KG_DOMAIN_STATUS = r"^Domain\s+\S+\s+\(([A-Za-z][A-Za-z ]*)\)\s*$";
}

/// Extracts Status values only from the top-level domain block of a WHOIS
/// response. Stops scanning at the first RIPE-style `[Section-Header]` line
/// and skips contact sections (see [`CONTACT_HEADINGS`]), which keeps
/// contact-object `Status:` lines (e.g. inside `[Tech-C]` blocks) out of the
/// domain status list.
fn extract_status_top_level(raw: &str) -> Vec<String> {
    let mut statuses = Vec::new();
    let mut in_contact = false;

    for line in raw.lines() {
        if statuses.len() >= MAX_STATUSES {
            break;
        }
        let trimmed = line.trim_start();

        // Stop at the first RIPE/JPRS-style sub-object section header.
        if trimmed.starts_with('[') && trimmed.contains(']') {
            break;
        }
        if is_contact_heading(trimmed) {
            in_contact = true;
            continue;
        }
        if trimmed.trim_end().is_empty() {
            in_contact = false;
            continue;
        }
        // Skip comments (a heading's `% ====` underline among them) and
        // contact-section lines.
        if in_contact || trimmed.starts_with('%') || trimmed.starts_with('#') {
            continue;
        }

        // KG domain registry (.kg): `Domain NIC.KG (ACTIVE)`
        if let Some(caps) = KG_DOMAIN_STATUS.captures(trimmed) {
            if let Some(m) = caps.get(1) {
                push_bounded(&mut statuses, m.as_str().to_string(), MAX_STATUSES);
            }
            continue;
        }

        // Match a [`STATUS_LABELS`] prefix case-insensitively via a prefix
        // check on the lowercased line.
        let lower = trimmed.to_lowercase();
        // Slice the ORIGINAL line by the ASCII prefix length. The prefixes are
        // pure ASCII, so their byte length is identical in `trimmed` and
        // `lower`; deriving the slice point from `lower`'s suffix length is
        // unsound because `to_lowercase()` is not length-preserving for all
        // Unicode (e.g. Turkish İ → i̇ grows 2→3 bytes), which could make the
        // lowercased suffix longer than the whole original line and underflow
        // `trimmed.len() - rest.len()` into an out-of-bounds slice panic.
        let value_opt = STATUS_LABELS
            .iter()
            .find(|label| lower.starts_with(*label))
            .map(|label| &trimmed[label.len()..]);

        // A value may list several comma-separated statuses (TCI's .ru/.su/.рф
        // `state: REGISTERED, DELEGATED, VERIFIED`); keep each one. ICANN-style
        // lines append an explanatory URL (`clientHold
        // https://icann.org/epp#clientHold`) and KazNIC a dash-led gloss
        // (`ok - Normal state.`); both are dropped, and the rest of
        // the entry is kept whole, since some registries' statuses are
        // phrases (CZ.NIC `Sponsoring registrar change forbidden`, Armenia
        // `registrar locked`).
        if let Some(rest) = value_opt {
            for entry in rest.split(',') {
                let phrase = entry
                    .split_whitespace()
                    .take_while(|word| {
                        *word != "-"
                            && !word.starts_with("http://")
                            && !word.starts_with("https://")
                    })
                    .collect::<Vec<_>>()
                    .join(" ");
                push_bounded(
                    &mut statuses,
                    decode_html_entities(&phrase).into_owned(),
                    MAX_STATUSES,
                );
            }
        }
    }

    statuses
}

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

    fn make_response(raw: &str) -> WhoisResponse {
        WhoisResponse::parse_internal("example.jp", "whois.jprs.jp", raw)
    }

    #[test]
    fn fixed_offset_date_shifts_datetimes_but_not_bare_dates() {
        let fmt = |d: Option<DateTime<Utc>>| d.map(|d| d.to_rfc3339());
        assert_eq!(
            fmt(parse_fixed_offset_date(
                " 2026-11-04 00:17:02 ",
                "%Y-%m-%d",
                8
            ))
            .as_deref(),
            Some("2026-11-03T16:17:02+00:00")
        );
        assert_eq!(
            fmt(parse_fixed_offset_date("2026-11-04", "%Y-%m-%d", 8)).as_deref(),
            Some("2026-11-04T00:00:00+00:00")
        );
        assert_eq!(parse_fixed_offset_date("garbage", "%Y-%m-%d", 8), None);
    }

    /// Port 43 is plaintext, so a hostile server can send chrono's minimum
    /// datetime; subtracting the offset must drop it, not panic.
    #[test]
    fn fixed_offset_date_at_chrono_min_does_not_panic() {
        let min = NaiveDateTime::MIN.format("%Y-%m-%d %H:%M:%S").to_string();
        assert!(
            NaiveDateTime::parse_from_str(&min, "%Y-%m-%d %H:%M:%S").is_ok(),
            "fixture must reach the offset subtraction: {min}"
        );
        assert_eq!(parse_fixed_offset_date(&min, "%Y-%m-%d", 8), None);
    }

    #[test]
    fn registrant_contact_email_label_is_read() {
        let r = make_response("Registrant Contact Email: hostmaster@example.cn\n");
        assert_eq!(r.registrant_email.as_deref(), Some("hostmaster@example.cn"));
    }

    #[test]
    fn organization_pattern_ignores_admin_and_tech_org_lines() {
        // With no registrant organization present, the bare `Organization:`
        // pattern must not capture the org from an `Admin Organization:` /
        // `Tech Organization:` line and mislabel it as the registrant org.
        let raw = "Domain Name: example.com\n\
                   Admin Organization: AcmeAdminCorp\n\
                   Tech Organization: AcmeTechCorp\n";
        assert_eq!(
            extract_field_with_patterns(raw, &ORGANIZATION_PATTERNS),
            None
        );

        // A genuine (possibly indented) registrant Organization: line is still
        // captured.
        let raw2 = "Domain Name: example.com\n\
                    Registrant Contact:\n\
                    \tOrganization: Real Registrant LLC\n\
                    Admin Organization: AcmeAdminCorp\n";
        assert_eq!(
            extract_field_with_patterns(raw2, &ORGANIZATION_PATTERNS).as_deref(),
            Some("Real Registrant LLC")
        );
    }

    #[test]
    fn comma_separated_state_keeps_every_status() {
        // TCI (.ru/.su/.рф) lists all states on one line; only the first was
        // kept before, with its trailing comma ("REGISTERED,").
        let raw = "domain:        MICROSOFT.RU\n\
                   state:         REGISTERED, DELEGATED, VERIFIED\n\
                   registrar:     RU-CENTER-RU\n";
        assert_eq!(
            extract_status_top_level(raw),
            vec!["REGISTERED", "DELEGATED", "VERIFIED"]
        );

        // ICANN-style trailing URL is still dropped.
        let raw = "Domain Status: clientHold https://icann.org/epp#clientHold\n";
        assert_eq!(extract_status_top_level(raw), vec!["clientHold"]);
    }

    // --- empty fields must not capture the following line ---------------

    #[test]
    fn empty_fields_do_not_capture_the_next_line() {
        // `\s*` between label and value used to match the CR/LF of an EMPTY
        // field and capture the following line as its value.
        let raw = concat!(
            "Domain Name: EXAMPLE.COM\r\n",
            "Registrar WHOIS Server: whois.tucows.com\r\n",
            "Creation Date: 2010-01-01T00:00:00Z\r\n",
            "Registrar Registration Expiration Date: \r\n",
            "Registrar: TUCOWS, INC.\r\n",
            "Registrant Organization: \r\n",
            "Registrant Street: 123 Main\r\n",
            "Name Server: \r\n",
            "DNSSEC: \r\n",
            "URL of the ICANN Whois Inaccuracy Complaint Form: https://www.icann.org/wicf/\r\n",
        );
        let r = WhoisResponse::parse("example.com", "whois.tucows.com", raw);
        assert!(
            r.nameservers.is_empty(),
            "empty Name Server must not yield the next label: {:?}",
            r.nameservers
        );
        assert_eq!(r.dnssec, None, "empty DNSSEC must not capture the URL line");
        assert_eq!(
            r.organization, None,
            "empty Registrant Organization must not capture the street line"
        );
        assert_eq!(r.registrant_address.as_deref(), Some("123 Main"));
        assert_eq!(r.registrar.as_deref(), Some("TUCOWS, INC."));
        assert_eq!(
            r.expiration_date, None,
            "empty expiry must stay None, not the registrar line"
        );

        // LF-only variant with trailing whitespace, plus a later populated
        // expiry label: the empty occurrence is skipped and the real one wins.
        let raw = "Registrar Registration Expiration Date: \n\
                   Registrar: TUCOWS, INC.\n\
                   Name Server: \n\
                   DNSSEC: unsigned\n\
                   Registry Expiry Date: 2027-03-01T00:00:00Z\n";
        let r = WhoisResponse::parse("example.com", "whois.tucows.com", raw);
        assert!(r.nameservers.is_empty(), "got {:?}", r.nameservers);
        assert_eq!(r.dnssec.as_deref(), Some("unsigned"));
        assert_eq!(
            r.expiration_date.map(|d| d.format("%Y-%m-%d").to_string()),
            Some("2027-03-01".to_string())
        );
    }

    /// DNS Belgium (.be) prints section headers with the value on the next
    /// (tab-indented) line: `Registrar:` / `\tName:\t MarkMonitor Inc.`.
    #[test]
    fn dns_belgium_section_registrar_is_extracted() {
        let raw = "% .be Whois Server 6.1\n\
                   %\n\
                   Domain:\tgoogle.be\n\
                   Status:\tNOT AVAILABLE\n\
                   Registered:\tTue Dec 12 2000\n\
                   \n\
                   Registrant:\n\
                   \tNot shown, please visit www.dnsbelgium.be for webbased whois.\n\
                   \n\
                   Registrar Technical Contacts:\n\
                   \tOrganisation:\tMarkMonitor Inc.\n\
                   \tLanguage:\ten\n\
                   \tPhone:\t+1.2083895740\n\
                   \tEmail:\tccops@markmonitor.com\n\
                   \n\
                   \n\
                   Registrar:\n\
                   \tName:\t MarkMonitor Inc.\n\
                   \tWebsite: http://www.markmonitor.com\n\
                   \n\
                   Nameservers:\n\
                   \tns2.google.com\n\
                   \tns1.google.com\n\
                   \n\
                   Keys:\n\
                   \n\
                   Flags:\n\
                   \tclientTransferProhibited\n\
                   \n\
                   Please visit www.dnsbelgium.be for more info.\n";
        let r = WhoisResponse::parse("google.be", "whois.dns.be", raw);
        assert_eq!(r.registrar.as_deref(), Some("MarkMonitor Inc."));
        assert_eq!(
            r.registrant, None,
            "the 'Not shown' notice is not a registrant"
        );
        assert_eq!(
            r.creation_date.map(|d| d.format("%Y-%m-%d").to_string()),
            Some("2000-12-12".to_string()),
            "created from 'Registered: Tue Dec 12 2000'"
        );
    }

    /// NASK (.pl) prints `REGISTRAR:` alone, then the registrar's name on
    /// the next line.
    #[test]
    fn nask_section_registrar_is_extracted() {
        let raw = "DOMAIN NAME:           google.pl\n\
                   registrant type:       organization\n\
                   nameservers:           ns1.google.com.\n\
                   \x20                      ns2.google.com.\n\
                   created:               2002.09.19 13:00:00\n\
                   last modified:         2025.08.19 13:47:36\n\
                   renewal date:          2026.09.18 14:00:00\n\
                   \n\
                   no option\n\
                   \n\
                   dnssec:                Unsigned\n\
                   \n\
                   \n\
                   REGISTRAR:\n\
                   MarkMonitor, Inc.\n\
                   3540 East Longwing Lane, Suite 300\n\
                   Meridian, Idaho 83646\n\
                   United States\n\
                   +1.2083895740\n\
                   ccops@markmonitor.com\n\
                   www.markmonitor.com\n\
                   \n\
                   WHOIS database responses: https://dns.pl/en/whois\n";
        let r = WhoisResponse::parse("google.pl", "whois.dns.pl", raw);
        assert_eq!(r.registrar.as_deref(), Some("MarkMonitor, Inc."));
        assert_eq!(r.dnssec.as_deref(), Some("Unsigned"));
        let fmt = |d: Option<DateTime<Utc>>| d.map(|d| d.format("%Y-%m-%d %H:%M:%S").to_string());
        assert_eq!(
            fmt(r.creation_date).as_deref(),
            Some("2002-09-19 13:00:00"),
            "created from 'created: 2002.09.19 13:00:00'"
        );
        assert_eq!(
            fmt(r.updated_date).as_deref(),
            Some("2025-08-19 13:47:36"),
            "updated from 'last modified: 2025.08.19 13:47:36'"
        );
    }

    /// TWNIC (.tw) lists the registrant name on the line after `Registrant:`.
    #[test]
    fn twnic_section_registrant_is_extracted() {
        let raw = "Domain Name: google.com.tw\n\
                   \x20  Domain Status: clientUpdateProhibited\n\
                   \x20  Registrant:\n\
                   \x20     Google LLC\n\
                   \x20     DNS Admin  dns-admin@google.com\n\
                   \n\
                   \x20  Record expires on 2026-11-09 00:00:00 (UTC+8)\n\
                   \n\
                   Registration Service Provider: Markmonitor, Inc.\n";
        let r = WhoisResponse::parse("google.com.tw", "whois.twnic.net.tw", raw);
        assert_eq!(r.registrant.as_deref(), Some("Google LLC"));
    }

    #[test]
    fn section_fallback_ignores_a_following_key_value_field() {
        // An empty `Registrar:` followed by another field is NOT a section
        // header: the next field's text must not become the registrar.
        let raw = "Domain Name: EXAMPLE.COM\nRegistrar:\nRegistrar IANA ID: 376\n";
        let r = WhoisResponse::parse("example.com", "whois.example", raw);
        assert_eq!(r.registrar, None);
    }

    #[test]
    fn contact_boilerplate_is_not_stored_as_a_value() {
        let raw = "Domain Name: EXAMPLE.COM\r\n\
                   Registrant Email: Please query the RDDS service of the Registrar of Record identified in this output for information on how to contact the Registrant, Admin, or Tech contact of the queried domain name.\r\n\
                   Admin Email: Please ask the Registrar of Record identified in this output for information on how to contact the Registrant, Admin, or Tech contact of the queried domain name.\r\n\
                   Tech Email: Select Request Email Form at https://domains.markmonitor.com/whois/example.com\r\n\
                   Registrant Phone: +1.5555550100\r\n";
        let r = WhoisResponse::parse("example.com", "whois.example", raw);
        assert_eq!(r.registrant_email, None);
        assert_eq!(r.admin_email, None);
        assert_eq!(r.tech_email, None);
        assert_eq!(
            r.registrant_phone.as_deref(),
            Some("+1.5555550100"),
            "real values are kept"
        );
    }

    // --- H10: is_available() scans the full response --------------------

    #[test]
    fn is_available_jprs_style_with_notice_preamble() {
        // JPRS prepends notice lines before the availability indicator.
        let raw = "\
Notice: JPRS database is provided for information purposes only.
Notice: Use of this service is subject to the JPRS terms.
Notice: For more info see https://jprs.jp/
Notice: Copyright (C) JPRS.

No match!!

";
        assert!(make_response(raw).is_available());
    }

    #[test]
    fn is_available_nic_br_style() {
        let raw = "\
% Copyright (c) Nic.br
% The use of the data below is only permitted as described in
% full by the terms of use at https://registro.br/termo/en.html,
% being prohibited its distribution, commercialization or
% reproduction, in particular, to use it for advertising or
% any similar purpose.

No match for domain exemplo.br.
";
        assert!(make_response(raw).is_available());
    }

    #[test]
    fn is_available_twnic_style() {
        let raw = "\
TWNIC WHOIS Server. This service is free and is provided as is.

Notice: Use of this service is subject to terms.
Notice: Do not use for spam.

Domain not found.
";
        assert!(make_response(raw).is_available());
    }

    #[test]
    fn is_available_false_when_registration_data_present_despite_noise() {
        // A registered domain whose WHOIS prose contains an availability
        // fragment (here in an abuse-contact/notice line) must NOT read as
        // available — concrete registration data (registrar/dates/NS) wins
        // over an unanchored substring match. This is the H6 false-positive
        // class: "<registered domain> reported AVAILABLE".
        let raw = "\
Domain Name: example.com
Registrar: Example Registrar, Inc.
Creation Date: 2020-01-01T00:00:00Z
Name Server: ns1.example.com
Registrar Abuse Contact: please report if the object not found in directory
";
        assert!(!make_response(raw).is_available());
    }

    #[test]
    fn is_available_false_for_registered_domain() {
        let raw = "\
Domain Name: example.com
Registrar: Example Registrar, Inc.
Creation Date: 2020-01-01T00:00:00Z
Name Server: ns1.example.com
";
        assert!(!make_response(raw).is_available());
    }

    // --- registry_unavailable(): registry serves no usable WHOIS --------

    #[test]
    fn registry_unavailable_true_for_tld_not_supported_sentinel() {
        // Identity Digital (.email/.life/.ninja/…) port-43 servers reply
        // "TLD is not supported." with no domain fields — RDAP-only TLDs.
        let raw = "\
TLD is not supported.
>>> Last update of WHOIS database: 2026-06-03T22:45:28Z <<<

Terms of Use: Access to WHOIS information is provided to assist persons ...
";
        assert!(make_response(raw).registry_unavailable());
    }

    #[test]
    fn registry_unavailable_true_for_freenom_gq_reply() {
        // Live reply from whois.dominio.gq for a registered domain
        // (2026-10-01): no data, and it must not read as "available".
        let raw = "The domain you requested is not known in Freenoms database.\n\
                   This TLD has no whois server.\n";
        let r = WhoisResponse::parse_internal("nic.gq", "whois.dominio.gq", raw);
        assert!(r.registry_unavailable());
        assert!(!r.is_available());
    }

    #[test]
    fn registry_unavailable_true_for_malformed_request_sentinel() {
        let raw = "\
Malformed request.
>>> Last update of WHOIS database: 2026-06-03T22:46:35Z <<<
";
        assert!(make_response(raw).registry_unavailable());
    }

    #[test]
    fn registry_unavailable_false_for_registered_domain() {
        let raw = "\
Domain Name: example.com
Registrar: Example Registrar, Inc.
Creation Date: 2020-01-01T00:00:00Z
Name Server: ns1.example.com
";
        assert!(!make_response(raw).registry_unavailable());
    }

    #[test]
    fn registry_unavailable_false_for_available_domain() {
        // An unregistered-domain "no match" response is NOT a service error —
        // it must read as available, not registry-unavailable.
        let raw = "No match for domain EXAMPLE.\n";
        assert!(!make_response(raw).registry_unavailable());
    }

    #[test]
    fn extract_status_does_not_panic_on_unicode_lowercasing_expansion() {
        // Turkish dotted capital İ (2 bytes) lowercases to i̇ (3 bytes), so a
        // status VALUE full of them makes the lowercased line longer than the
        // original. The old code sliced the original by a length derived from
        // the lowercased copy (`trimmed.len() - rest.len()`), which underflowed
        // and panicked out-of-bounds. `raw` is attacker-controlled (a hostile
        // WHOIS server), so this was a remotely-triggerable panic / DoS.
        let raw = format!("Domain Status: {}\n", "İ".repeat(40));
        let r = make_response(&raw); // must not panic
        assert!(
            !r.status.is_empty(),
            "status value should still be extracted"
        );
    }

    #[test]
    fn is_available_hkirc_has_not_been_registered() {
        // HKIRC (.hk and the IDN .香港/xn--j6w193g) signals an unregistered
        // domain with "The domain has not been registered." — note the
        // wording is "has not BEEN registered", which does NOT contain the
        // bare "not registered" substring the old pattern list relied on.
        let raw = "The domain has not been registered.\n";
        assert!(make_response(raw).is_available());
    }

    #[test]
    fn is_available_tab_delimited_status_available() {
        // DNS Belgium (.be) and similar registries separate the label and
        // value with a TAB: "Status:\tAVAILABLE". The scan must normalize
        // internal whitespace so the "status: available" pattern still hits.
        let raw = "Domain:\tfoo.be\nStatus:\tAVAILABLE\n";
        assert!(make_response(raw).is_available());
    }

    #[test]
    fn is_not_available_tab_delimited_status_not_available() {
        // Guard against a false positive from whitespace normalization:
        // "Status:\tNOT AVAILABLE" (a registered .be domain) must NOT be
        // read as available — "status: available" is not a substring of
        // "status: not available".
        let raw = "Domain:\tfoo.be\nStatus:\tNOT AVAILABLE\n";
        assert!(!make_response(raw).is_available());
    }

    #[test]
    fn is_available_recognizes_additional_registry_phrasings() {
        // "Not found" wordings surfaced by the cross-TLD audit, mostly from
        // no-RDAP ccTLDs where WHOIS is the only registry signal.
        for raw in [
            "*** Nothing found for this query.\n", // .kz / .қаз (KazNIC)
            "No Found\n",                          // TWNIC .tw / 台灣 / 台湾
            "No record found for 'example.ls'.\n", // .ls (Lesotho)
            "No information was found matching that query.\n", // .africa
            "Object not found\n",                  // generic
            "Not find MatchingRecord\n",           // CONAC .政务 / .公益
            "% No data was found to match the request criteria.\n", // ISOC-IL .il
        ] {
            assert!(
                make_response(raw).is_available(),
                "should detect available from: {raw:?}"
            );
        }
    }

    #[test]
    fn is_available_does_not_match_registered_or_blocked_phrasings() {
        // Guard against false positives from the broadened pattern list: a
        // registered domain, a "not available" status, a port-43 refusal, and
        // TOS prose containing "free" must all stay NOT-available.
        for raw in [
            "Domain Status: clientTransferProhibited\nRegistrar: Example, Inc.\n",
            "Status: NOT AVAILABLE\n",
            "Requests of this client are not permitted. Please use the web form.\n",
            "This WHOIS service is free for personal, non-commercial use.\n",
        ] {
            assert!(
                !make_response(raw).is_available(),
                "must NOT detect available from: {raw:?}"
            );
        }
    }

    #[test]
    fn is_available_false_for_negation_and_refusal_lines() {
        // Regression for the availability-inversion bug (#45): the per-line
        // scan matched AVAILABILITY_PATTERNS via an unanchored contains() with
        // no negation guard, so a short status line that *negates* or *refuses*
        // availability ("not available for registration", "not registered" in a
        // reserved status, "no data found" while rate-limited) was inverted into
        // "available, high confidence". All three must read as NOT available.
        for raw in [
            // reserved/premium — registry refuses registration (contains the
            // "available for registration" substring after "not ").
            "This domain name is not available for registration.\n",
            // reserved/blocked status (contains the "not registered" substring).
            "Domain Status: reserved - not registered for public use\n",
            // throttled — inconclusive, not free (contains "no data found").
            "Access rate limited; no data found for unauthenticated clients\n",
        ] {
            assert!(
                !make_response(raw).is_available(),
                "negation/refusal line must NOT read as available: {raw:?}"
            );
        }
    }

    #[test]
    fn indicates_registry_refusal_detects_throttle_and_negation() {
        // The refusal detector backs `classify_fallback`'s inconclusive routing: a
        // thin body that explicitly refuses / throttles / negates availability
        // must be flagged so the fallback decision does not guess.
        for raw in [
            "This domain name is not available for registration.\n",
            "Domain Status: reserved - not registered for public use\n",
            "Access rate limited; no data found for unauthenticated clients\n",
            "Requests of this client are not permitted. Please use the web form.\n",
        ] {
            assert!(
                make_response(raw).indicates_registry_refusal(),
                "should flag refusal/throttle/negation: {raw:?}"
            );
        }
    }

    /// Single-token refusal markers ("quota", "blocked", "refused", …) used
    /// to match inside the domain name echoed by a "no match" line, turning a
    /// conclusive "available" into "inconclusive".
    #[test]
    fn refusal_words_inside_the_echoed_domain_do_not_veto_availability() {
        for (domain, raw) in [
            (
                "quotations.pl",
                "No information available about domain name quotations.pl in the Registry NASK database.\n",
            ),
            ("unblocked-games.com", "No match for \"UNBLOCKED-GAMES.COM\".\n"),
            ("refused.ls", "No record found for 'refused.ls'.\n"),
            ("denied-access.com", "No match for \"DENIED-ACCESS.COM\".\n"),
            ("rate-limiter.com", "No match for \"RATE-LIMITER.COM\".\n"),
        ] {
            let r = WhoisResponse::parse(domain, "whois.example", raw);
            assert!(
                !r.indicates_registry_refusal(),
                "{domain}: echoed domain is not a refusal: {raw:?}"
            );
            assert!(r.is_available(), "{domain}: must read as available: {raw:?}");
        }
    }

    #[test]
    fn refusal_words_are_still_detected_as_whole_words() {
        for raw in [
            "Query refused.\n",
            "Your request has been blocked\n",
            "Request denied: too many queries from your IP\n",
            "Query quota exceeded for this client\n",
            "Rate-limit exceeded, no data found\n",
            "Your IP has been rate-limited.\n",
        ] {
            let r = make_response(raw);
            assert!(r.indicates_registry_refusal(), "must flag: {raw:?}");
            assert!(!r.is_available(), "must not read as available: {raw:?}");
        }
    }

    #[test]
    fn contains_word_respects_domain_label_boundaries() {
        assert!(contains_word("query refused.", "refused"));
        assert!(contains_word("refused", "refused"));
        assert!(contains_word("(blocked)", "blocked"));
        assert!(!contains_word(
            "no record found for 'refused.ls'.",
            "refused"
        ));
        assert!(!contains_word("www.blocked.example", "blocked"));
        assert!(!contains_word("unblocked-games.com", "blocked"));
        assert!(!contains_word("quotations.pl", "quota"));
    }

    #[test]
    fn indicates_registry_refusal_false_for_plain_not_found_and_registered() {
        // A genuine "no match" availability response and a registered domain
        // must NOT be flagged as refusal — those are conclusive signals.
        for raw in [
            "No match for domain EXAMPLE.\n",
            "Domain not found.\n",
            "Conditions of use for the whois service via port 43\n",
            "Domain Name: example.com\nRegistrar: Example, Inc.\nName Server: ns1.example.com\n",
            // Near-universal copyright footers contain the word "reserved" but
            // are not a refusal — a thin response whose only non-comment line
            // is such a footer must stay eligible for the DNS tie-breaker
            // instead of short-circuiting to "inconclusive".
            "Copyright (c) 2024 Example Registry Corp. All rights reserved.\n",
            "All rights reserved. Use of this service is subject to the terms of use.\n",
        ] {
            assert!(
                !make_response(raw).indicates_registry_refusal(),
                "must NOT flag as refusal: {raw:?}"
            );
        }
    }

    #[test]
    fn is_available_ignores_not_found_phrase_buried_in_prose() {
        // A thin response with NO parsed registration fields (so the H6
        // registration-data guard does not fire) whose only "does not exist"
        // / "not found" occurrence is inside a long prose/notice sentence
        // must NOT be read as available. Availability indicators are short
        // status lines, not phrases buried in footer prose.
        let raw = "\
This is an informational banner from the registry WHOIS service provider.
Note that if the queried object does not exist in our database we simply return an empty result rather than an error response.
Records not found in this directory may still exist upstream in the thick registry, so please check with the sponsoring registrar.
";
        assert!(
            !make_response(raw).is_available(),
            "long prose sentences must not trigger availability"
        );
    }

    // --- M19: indicates_not_found anchors at line start -----------------

    #[test]
    fn indicates_not_found_true_on_line_start() {
        let raw = "\
Domain Name: example.com
queried object does not exist
";
        assert!(make_response(raw).indicates_not_found());
    }

    #[test]
    fn indicates_not_found_false_when_phrase_is_in_tos_footer() {
        // A registered-domain response whose TOS footer quotes the phrase
        // must not be flagged as not-found.
        let raw = "\
Domain Name: example.com
Registrar: Example Registrar, Inc.
Creation Date: 2020-01-01T00:00:00Z
Name Server: ns1.example.com

Terms of Service:
Note that if the queried object does not exist in our database we return NXDOMAIN.
This document does not imply anything about specific domains.
";
        assert!(!make_response(raw).indicates_not_found());
    }

    // --- M13: extract_status_top_level skips sub-object sections --------

    #[test]
    fn status_extracted_only_from_top_level_block() {
        let raw = "\
Domain Name: example.jp
Status: Active
Registrar: Example Registrar

[Tech-C]
Status: ok
Name: Technical Contact
";
        let parsed = make_response(raw);
        // Only the top-level Active should be present; the Tech-C "ok" is skipped.
        assert_eq!(parsed.status, vec!["Active".to_string()]);
    }

    #[test]
    fn status_multiple_top_level_values_deduped() {
        let raw = "\
Domain Name: example.com
Domain Status: clientTransferProhibited
Domain Status: clientUpdateProhibited
Domain Status: clientTransferProhibited
";
        let parsed = make_response(raw);
        assert_eq!(
            parsed.status,
            vec![
                "clientTransferProhibited".to_string(),
                "clientUpdateProhibited".to_string(),
            ]
        );
    }

    // --- M14: parse_date handles "15-Jan-2024 10:30:00" -----------------

    #[test]
    fn parse_date_handles_d_b_y_with_time() {
        let parsed = parse_date("15-Jan-2024 10:30:00").expect("should parse");
        use chrono::Datelike;
        assert_eq!(parsed.year(), 2024);
        assert_eq!(parsed.month(), 1);
        assert_eq!(parsed.day(), 15);
    }

    #[test]
    fn parse_date_handles_d_b_y_with_time_utc_suffix() {
        let parsed = parse_date("15-Jan-2024 10:30:00 UTC").expect("should parse");
        use chrono::Datelike;
        assert_eq!(parsed.year(), 2024);
    }

    #[test]
    fn parse_date_still_handles_d_b_y_date_only() {
        let parsed = parse_date("15-Jan-2024").expect("should parse");
        use chrono::Datelike;
        assert_eq!(parsed.year(), 2024);
    }

    // --- parse_date: ambiguous numeric dates default to day-first, but
    //     unambiguous US month-first dates are recovered (not dropped) ----

    #[test]
    fn parse_date_recovers_unambiguous_us_mdy() {
        // Some registrars emit US month-first numeric dates. When the day
        // field is > 12 the date is unambiguously MDY and was previously
        // dropped (there was no %m/%d/%Y format). Recover it rather than
        // returning None.
        use chrono::Datelike;
        let parsed = parse_date("02/13/2024").expect("unambiguous MDY should parse");
        assert_eq!(parsed.year(), 2024);
        assert_eq!(parsed.month(), 2);
        assert_eq!(parsed.day(), 13);
    }

    #[test]
    fn parse_date_ambiguous_numeric_is_day_first() {
        // Documented precedence: ambiguous all-numeric dates (both fields
        // <= 12) are interpreted day-first (the international norm), matching
        // the %d/%m/%Y format ordering. "06/07/2024" => 6 July 2024. The
        // month-first fallback must NOT change this.
        use chrono::Datelike;
        let parsed = parse_date("06/07/2024").expect("should parse");
        assert_eq!(parsed.year(), 2024);
        assert_eq!(parsed.month(), 7);
        assert_eq!(parsed.day(), 6);
    }

    #[test]
    fn parse_date_splits_at_most_one_utc_offset() {
        // One offset still shifts; a second one makes it not a date, rather
        // than recursing into the remainder (which `%z` would then accept).
        let one = parse_date("2024-01-15 10:30:00 +01").expect("single offset");
        assert_eq!(one.to_rfc3339(), "2024-01-15T09:30:00+00:00");
        assert_eq!(parse_date("2024-01-15 10:30:00+01:00+01:00"), None);
    }

    #[test]
    fn parse_date_rejects_long_offset_chains_without_deep_recursion() {
        // `1:00-1:00-…` (100 KB, well under the WHOIS cap) once recursed per
        // link: it overflowed a 2 MiB Tokio worker stack and took seconds of
        // CPU. Run on a stack that size to prove it now returns at once.
        let hostile = format!("1:00{}", "-1:00".repeat(20_000));
        let started = std::time::Instant::now();
        let parsed = std::thread::Builder::new()
            .stack_size(2 * 1024 * 1024)
            .spawn(move || parse_date(&hostile))
            .expect("spawn")
            .join()
            .expect("no stack overflow");
        assert_eq!(parsed, None);
        assert!(started.elapsed() < std::time::Duration::from_secs(1));
    }

    // --- #47: per-registry date order disambiguation --------------------

    #[test]
    fn parse_date_with_order_disambiguates_month_first() {
        // The same ambiguous string reads differently per order hint:
        // day-first => 3 April; month-first (US) => 4 March.
        use chrono::Datelike;
        let dmy = parse_date_with_order("03/04/2024", DateOrder::DayFirst).expect("parse");
        assert_eq!(
            (dmy.month(), dmy.day()),
            (4, 3),
            "day-first reads 03/04 as 3 April"
        );
        let mdy = parse_date_with_order("03/04/2024", DateOrder::MonthFirst).expect("parse");
        assert_eq!(
            (mdy.month(), mdy.day()),
            (3, 4),
            "month-first reads 03/04 as 4 March"
        );
    }

    #[test]
    fn parse_date_with_order_unambiguous_is_order_independent() {
        // A field > 12 disambiguates the date regardless of the hint.
        use chrono::Datelike;
        for s in ["13/04/2024", "04/13/2024"] {
            for order in [DateOrder::DayFirst, DateOrder::MonthFirst] {
                let d = parse_date_with_order(s, order).expect("parse");
                assert_eq!(
                    (d.year(), d.month(), d.day()),
                    (2024, 4, 13),
                    "{s:?} under {order:?} must be 2024-04-13"
                );
            }
        }
    }

    #[test]
    fn parse_internal_infers_us_month_first_from_unambiguous_sibling() {
        // A US-format registry response: the ambiguous creation date
        // "03/04/2024" (both fields <= 12) must be read month-first (4 March)
        // because the sibling expiry "04/15/2034" is unambiguously month-first
        // (day 15). Registries are internally consistent, so one unambiguous
        // date reveals the order for the whole response (issue #47).
        use chrono::Datelike;
        let raw = "Creation Date: 03/04/2024\nRegistry Expiry Date: 04/15/2034\n";
        let r = make_response(raw);
        let creation = r.creation_date.expect("creation parsed");
        assert_eq!(
            (creation.month(), creation.day()),
            (3, 4),
            "ambiguous date must follow the registry's revealed month-first order"
        );
    }

    #[test]
    fn parse_internal_defaults_day_first_without_disambiguating_sibling() {
        // No unambiguous sibling → the documented day-first default holds.
        use chrono::Datelike;
        let raw = "Creation Date: 06/07/2024\n";
        let r = make_response(raw);
        let creation = r.creation_date.expect("creation parsed");
        assert_eq!(
            (creation.month(), creation.day()),
            (7, 6),
            "no disambiguating sibling keeps the day-first default"
        );
    }

    #[test]
    fn parse_date_handles_numeric_dates_with_time_of_day() {
        let fmt = |s: &str, order| {
            parse_date_with_order(s, order).map(|d| d.format("%Y-%m-%d %H:%M:%S").to_string())
        };
        let day_first = DateOrder::DayFirst;
        // Year-first (unambiguous).
        assert_eq!(
            fmt("2002.09.19 13:00:00", day_first).as_deref(),
            Some("2002-09-19 13:00:00")
        );
        assert_eq!(
            fmt("2002/09/19 13:00:00", day_first).as_deref(),
            Some("2002-09-19 13:00:00")
        );
        // CZ.NIC day-first with time.
        assert_eq!(
            fmt("18.09.2000 13:05:00", day_first).as_deref(),
            Some("2000-09-18 13:05:00")
        );
        // Ambiguous numeric dates with a time keep obeying the order hint...
        assert_eq!(
            fmt("03/04/2024 10:00:00", DateOrder::DayFirst).as_deref(),
            Some("2024-04-03 10:00:00")
        );
        assert_eq!(
            fmt("03/04/2024 10:00:00", DateOrder::MonthFirst).as_deref(),
            Some("2024-03-04 10:00:00")
        );
        // ...and unambiguous ones parse the same under either hint (#47).
        for order in [DateOrder::DayFirst, DateOrder::MonthFirst] {
            assert_eq!(
                fmt("04/13/2024 08:30:00", order).as_deref(),
                Some("2024-04-13 08:30:00")
            );
            assert_eq!(
                fmt("13.04.2024 08:30:00", order).as_deref(),
                Some("2024-04-13 08:30:00")
            );
        }
        // DNS Belgium weekday-prefixed dates.
        assert_eq!(
            fmt("Tue Dec 12 2000", day_first).as_deref(),
            Some("2000-12-12 00:00:00")
        );
    }

    #[test]
    fn parse_internal_infers_order_from_sibling_with_time_of_day() {
        // A US-format registry that prints times: the unambiguous expiry
        // (day 15) still reveals month-first for the ambiguous creation date.
        use chrono::Datelike;
        let raw = "Creation Date: 03/04/2024 10:00:00\n\
                   Registry Expiry Date: 04/15/2034 10:00:00\n";
        let r = make_response(raw);
        let creation = r.creation_date.expect("creation parsed");
        assert_eq!((creation.month(), creation.day()), (3, 4));
        let expiry = r.expiration_date.expect("expiry parsed");
        assert_eq!((expiry.month(), expiry.day()), (4, 15));
    }

    // --- H3: raw_response is not serialized -----------------------------

    #[test]
    fn raw_response_is_skipped_from_json_output() {
        let raw = "Domain Name: example.com\nRegistrar: Example Registrar\n";
        let parsed = make_response(raw);
        assert!(
            !parsed.raw_response.is_empty(),
            "raw_response still populated internally"
        );
        let json = serde_json::to_string(&parsed).expect("serialize");
        assert!(
            !json.contains("raw_response"),
            "raw_response must not appear in serialized JSON output: {}",
            json
        );
        assert!(
            !json.contains("Domain Name: example.com"),
            "raw response content must not leak in JSON: {}",
            json
        );
    }

    /// Regression: a serialized `WhoisResponse` must deserialize back.
    /// `raw_response` is `skip_serializing` (the 1 MB raw blob must never leak),
    /// but it also needs `default` — otherwise deserialization fails with
    /// "missing field `raw_response`", which silently corrupts persisted lookup
    /// history / cache files (the corrupt-file branch then discards them).
    #[test]
    fn whois_response_survives_json_round_trip() {
        let parsed = make_response("Domain Name: example.com\nRegistrar: Example Registrar\n");
        let json = serde_json::to_string(&parsed).expect("serialize");
        let back: WhoisResponse =
            serde_json::from_str(&json).expect("round-trip must not fail (missing field?)");
        assert_eq!(back.domain, parsed.domain, "domain survives round-trip");
        assert!(
            back.raw_response.is_empty(),
            "skipped raw_response defaults to empty on load"
        );
    }

    /// Punktum (.dk) format, captured live 2026-07: nameservers appear as
    /// `Hostname:` lines under a `Nameservers` heading, and the creation
    /// date is labelled `Registered:`.
    #[test]
    fn punktum_dk_hostnames_and_registered_date() {
        let raw = "Domain:               punktum.dk\n\
                   DNS:                  punktum.dk\n\
                   Registered:           2018-01-25\n\
                   Expires:              2027-01-31\n\
                   Registration period:  1 year\n\
                   DNSSEC:               Signed delegation\n\
                   Status:               Active\n\
                   \n\
                   Nameservers\n\
                   Hostname:             auth01.ns.dk-hostmaster.dk\n\
                   Hostname:             auth02.ns.dk-hostmaster.dk\n\
                   Hostname:             auth03.ns.dk-hostmaster.dk\n";
        let r = WhoisResponse::parse("punktum.dk", "whois.punktum.dk", raw);
        assert_eq!(
            r.nameservers,
            vec![
                "auth01.ns.dk-hostmaster.dk",
                "auth02.ns.dk-hostmaster.dk",
                "auth03.ns.dk-hostmaster.dk"
            ]
        );
        assert!(r.creation_date.is_some(), "created from 'Registered:'");
        assert!(r.expiration_date.is_some(), "expires from 'Expires:'");
    }

    /// Many ccTLD registries print the availability verdict on `%`-comment
    /// lines (wording captured live 2026-07). The comment marker must be
    /// stripped and the remainder evaluated, not skipped wholesale.
    #[test]
    fn availability_verdicts_on_comment_lines_are_detected() {
        let cases: &[(&str, &str)] = &[
            (
                "fr/AFNIC",
                "%% This is the AFNIC Whois server.\n%%\n%% NOT FOUND\n",
            ),
            (
                "br/NIC.br",
                "% Copyright (c) Nic.br\n% No match for seer-sweep.br\n",
            ),
            ("no/NORID", "% Norid AS holds the copyright\n% No match\n"),
            (
                "at/NIC.AT",
                "% Copyright (c)2026 by NIC.AT (1)\n% nothing found\n",
            ),
            (
                "cz/CZ.NIC",
                "%ERROR:101: no entries found\n% No entries found.\n",
            ),
            ("rs/RNIDS", "%ERROR:103: Domain is not registered\n"),
            (
                "is/ISNIC",
                "% Rights restricted by copyright.\n% No entries found for query \"x.is\".\n",
            ),
            ("lu/RESTENA", "% WHOIS x.lu\n% No such domain\n"),
            ("dz/NIC.DZ", "% No match for domain 'X.DZ'.\n"),
            ("sn/NIC.SN", "%% NOT FOUND\n"),
        ];
        for (name, raw) in cases {
            let r = WhoisResponse::parse("example.test", "whois.test", raw);
            assert!(
                r.is_available(),
                "{name}: comment-line verdict must mark available:\n{raw}"
            );
        }
    }

    /// Sentence-form "not found" phrasings exceed the 10-word status-line
    /// gate; they are matched anchored at line start instead (live 2026-07).
    #[test]
    fn availability_sentence_phrasings_are_detected() {
        let cases: &[(&str, &str)] = &[
            (
                "kr/KISA",
                "query : x.kr\nThe requested domain was not found in the Registry or Registrar\u{2019}s WHOIS Server.\n",
            ),
            (
                "edu/EDUCAUSE",
                "Domain Name: X.EDU\nThe domain name you requested was not found in our database.\n",
            ),
            (
                "pl/NASK",
                "No information available about domain name x.pl in the Registry NASK database.\n",
            ),
        ];
        for (name, raw) in cases {
            let r = WhoisResponse::parse("example.test", "whois.test", raw);
            assert!(
                r.is_available(),
                "{name}: sentence-form verdict must mark available:\n{raw}"
            );
        }
    }

    /// Registry-specific short phrasings captured live 2026-07: SIDN/.aw
    /// "<domain> is free" (suffix-anchored so prose like "registration is
    /// free of charge" cannot match), NIC Mexico's underscore token, and
    /// NIC Argentina's Spanish phrasing.
    #[test]
    fn availability_special_short_phrasings_are_detected() {
        for (name, raw) in [
            ("nl/SIDN", "x.nl is free\n"),
            ("aw/SETAR", "x.aw is free\n"),
            (
                "mx/NICMexico",
                "No_Se_Encontro_El_Objeto/Object_Not_Found\n",
            ),
            (
                "ar/NICArgentina",
                "El dominio no se encuentra registrado en NIC Argentina\n",
            ),
        ] {
            let r = WhoisResponse::parse("example.test", "whois.test", raw);
            assert!(r.is_available(), "{name} must mark available:\n{raw}");
        }
        // Suffix anchoring: "is free" mid-sentence must NOT flip availability.
        let prose = WhoisResponse::parse(
            "example.test",
            "whois.test",
            "Registration is free of charge today\n",
        );
        assert!(
            !prose.is_available(),
            "'is free' inside prose must not mark available"
        );
    }

    /// ANINF (.ga, captured live 2026-07) answers in French: dates are
    /// `Date de création:` / `Date d'expiration:` / `Dernière modification:`
    /// and nameservers are `Serveur de noms:` lines. Contact blocks carry
    /// their own `Dernière modification:` — the domain-level one (first in
    /// the body) must win.
    #[test]
    fn aninf_ga_french_labels_parse() {
        let raw = "Domain ID:                     DOM8624-GA\n\
                   Nom de domaine:                google.ga\n\
                   Date de création:              2023-06-06T19:15:12.718385Z\n\
                   Dernière modification:         2026-05-12T17:27:38.344508Z\n\
                   Date d'expiration:             2027-06-06T19:15:12.694489Z\n\
                   Registrar:                     MARKMONITOR Inc.\n\
                   Statut:                        actif\n\
                   \n\
                   [TECH_C]\n\
                   Nom:                           REDACTED_FOR_PRIVACY\n\
                   Dernière modification:         2023-11-09T18:15:51.973324Z\n\
                   \n\
                   Serveur de noms:               ns1.google.com\n\
                   Serveur de noms:               ns2.google.com\n\
                   \n\
                   DNSSEC:                        unsigned\n";
        let r = WhoisResponse::parse("google.ga", "whois.nic.ga", raw);
        assert_eq!(r.nameservers, vec!["ns1.google.com", "ns2.google.com"]);
        let created = r.creation_date.expect("creation from Date de création");
        assert_eq!(
            created.format("%Y-%m-%d").to_string(),
            "2023-06-06",
            "domain creation date"
        );
        let expires = r.expiration_date.expect("expiry from Date d'expiration");
        assert_eq!(expires.format("%Y-%m-%d").to_string(), "2027-06-06");
        let updated = r.updated_date.expect("updated from Dernière modification");
        assert_eq!(
            updated.format("%Y-%m-%d").to_string(),
            "2026-05-12",
            "domain-level modification must win over the contact block's"
        );
    }

    /// GMO Registry retired port-43 WHOIS (May 2026, ICANN RDAP transition)
    /// and now answers every query with a retirement notice. That is a
    /// service-level "no usable WHOIS" signal, not a registered/available
    /// verdict.
    #[test]
    fn whois_retirement_notice_is_registry_unavailable() {
        let raw = "Notice: Effective May 1, 2026, the WHOIS service has been retired in accordance with ICANN's RDAP transition policy. All registration data queries are now served via RDAP. The Registration Data Access Protocol (RDAP) base URL is: https://rdap.gmoregistry.net/rdap/";
        let r = WhoisResponse::parse("nic.canon", "whois.nic.canon", raw);
        assert!(
            r.registry_unavailable(),
            "retirement notice must be registry_unavailable"
        );
        assert!(!r.is_available(), "retirement notice is not 'available'");
    }
    #[test]
    fn switch_first_registration_date_on_the_next_line_is_parsed() {
        // SWITCH prints the value on the line after its header; the generic
        // `Key: value` patterns deliberately no longer reach across lines.
        let raw = "Domain name:\nexample.ch\n\nHolder of domain name:\nRedacted\n\n\
                   First registration date:\n01.12.2003\n";
        let r = WhoisResponse::parse_internal("example.ch", "whois.nic.ch", raw);
        assert_eq!(
            r.creation_date.map(|d| d.format("%Y-%m-%d").to_string()),
            Some("2003-12-01".to_string())
        );
        // SWITCH's legacy free-text value is not a date and is not guessed at.
        let raw = "First registration date:\nregistered before 1st January 1996\n";
        let r = WhoisResponse::parse_internal("old.ch", "whois.nic.ch", raw);
        assert!(r.creation_date.is_none());
    }

    // --- generic-parser fixtures ---------------------------------------

    #[test]
    fn generic_parser_basic() {
        let raw = r#"
Domain Name: example.com
Registrar: Example Registrar, Inc.
Creation Date: 2020-01-15T00:00:00Z
Expiration Date: 2025-01-15T00:00:00Z
Name Server: ns1.example.com
Name Server: ns2.example.com
"#;
        let result = WhoisResponse::parse_internal("example.com", "whois.example.com", raw);

        assert_eq!(result.domain, "example.com");
        assert_eq!(
            result.registrar,
            Some("Example Registrar, Inc.".to_string())
        );
        assert_eq!(result.nameservers.len(), 2);
    }

    // ------------------------------------------------------------------
    // Real-world fixture tests (M13).
    //
    // The trivial LF-only fixture above hid regressions for the three most
    // common shapes of gTLD WHOIS responses:
    //   1. Current Verisign thick .com format (CRLF, registrar/registry split)
    //   2. Post-2018 GDPR-redacted .com responses (PII replaced with
    //      "REDACTED FOR PRIVACY")
    //   3. CRLF line endings throughout (TCP WHOIS protocol default)
    //
    // These fixtures assert only on parser-visible fields (domain name,
    // registrar, dates, nameservers, status) — never PII, since real
    // responses vary in what they redact.
    // ------------------------------------------------------------------

    /// Current Verisign thick-WHOIS format for `.com` (post-GDPR).
    /// Abbreviated from a real response, preserving structure and CRLF.
    const VERISIGN_COM_FIXTURE: &str = concat!(
        "   Domain Name: EXAMPLE.COM\r\n",
        "   Registry Domain ID: 2336799_DOMAIN_COM-VRSN\r\n",
        "   Registrar WHOIS Server: whois.iana.org\r\n",
        "   Registrar URL: http://res-dom.iana.org\r\n",
        "   Updated Date: 2024-08-14T07:01:34Z\r\n",
        "   Creation Date: 1995-08-14T04:00:00Z\r\n",
        "   Registry Expiry Date: 2025-08-13T04:00:00Z\r\n",
        "   Registrar: RESERVED-Internet Assigned Numbers Authority\r\n",
        "   Registrar IANA ID: 376\r\n",
        "   Registrar Abuse Contact Email:\r\n",
        "   Registrar Abuse Contact Phone:\r\n",
        "   Domain Status: clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited\r\n",
        "   Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited\r\n",
        "   Domain Status: clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited\r\n",
        "   Name Server: A.IANA-SERVERS.NET\r\n",
        "   Name Server: B.IANA-SERVERS.NET\r\n",
        "   DNSSEC: signedDelegation\r\n",
        "   DNSSEC DS Data: 370 13 2 BE74359954660069D5C63DA59519AB22E46C7A3AEFAD516946B72A91BC93D46F\r\n",
        "   URL of the ICANN Whois Inaccuracy Complaint Form: https://www.icann.org/wicf/\r\n",
        ">>> Last update of whois database: 2026-04-20T12:34:56Z <<<\r\n",
    );

    #[test]
    fn test_verisign_thick_com_fixture() {
        let result = WhoisResponse::parse_internal(
            "example.com",
            "whois.verisign-grs.com",
            VERISIGN_COM_FIXTURE,
        );

        assert_eq!(result.domain, "example.com");
        assert_eq!(
            result.registrar.as_deref(),
            Some("RESERVED-Internet Assigned Numbers Authority"),
            "must extract registrar from current Verisign thick-WHOIS"
        );
        // Both A and B IANA servers should be captured.
        assert!(
            result
                .nameservers
                .iter()
                .any(|n| n.to_lowercase().contains("a.iana-servers.net")),
            "nameservers missing A: {:?}",
            result.nameservers
        );
        assert!(
            result
                .nameservers
                .iter()
                .any(|n| n.to_lowercase().contains("b.iana-servers.net")),
            "nameservers missing B: {:?}",
            result.nameservers
        );
        assert_eq!(result.nameservers.len(), 2);
        assert!(result.creation_date.is_some(), "creation date must parse");
        assert!(
            result.expiration_date.is_some(),
            "expiration date must parse"
        );
        assert_eq!(result.dnssec.as_deref(), Some("signedDelegation"));
        // At least three statuses captured.
        assert!(
            result.status.len() >= 3,
            "expected >= 3 statuses, got {:?}",
            result.status
        );
        // not-available: the response contains registration data.
        assert!(!result.is_available());
    }

    /// Post-2018 GDPR-redacted thick response for a `.com` domain.
    /// All PII is replaced by the string "REDACTED FOR PRIVACY"; core
    /// registry fields remain present. CRLF throughout.
    const GDPR_REDACTED_COM_FIXTURE: &str = concat!(
        "   Domain Name: REDACTED-EXAMPLE.COM\r\n",
        "   Registry Domain ID: 9999999_DOMAIN_COM-VRSN\r\n",
        "   Registrar WHOIS Server: whois.markmonitor.com\r\n",
        "   Registrar URL: http://www.markmonitor.com\r\n",
        "   Updated Date: 2025-11-08T10:00:00Z\r\n",
        "   Creation Date: 2010-03-12T17:22:00Z\r\n",
        "   Registry Expiry Date: 2027-03-12T17:22:00Z\r\n",
        "   Registrar: MarkMonitor Inc.\r\n",
        "   Registrar IANA ID: 292\r\n",
        "   Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited\r\n",
        "   Registry Registrant ID: REDACTED FOR PRIVACY\r\n",
        "   Registrant Name: REDACTED FOR PRIVACY\r\n",
        "   Registrant Organization: REDACTED FOR PRIVACY\r\n",
        "   Registrant Street: REDACTED FOR PRIVACY\r\n",
        "   Registrant City: REDACTED FOR PRIVACY\r\n",
        "   Registrant State/Province: REDACTED FOR PRIVACY\r\n",
        "   Registrant Postal Code: REDACTED FOR PRIVACY\r\n",
        "   Registrant Country: REDACTED FOR PRIVACY\r\n",
        "   Registrant Phone: REDACTED FOR PRIVACY\r\n",
        "   Registrant Email: Please query the RDDS service of the Registrar of Record identified in this output for information on how to contact the Registrant, Admin, or Tech contact of the queried domain name.\r\n",
        "   Admin Name: REDACTED FOR PRIVACY\r\n",
        "   Admin Email: REDACTED FOR PRIVACY\r\n",
        "   Tech Name: REDACTED FOR PRIVACY\r\n",
        "   Tech Email: REDACTED FOR PRIVACY\r\n",
        "   Name Server: NS1.MARKMONITOR.COM\r\n",
        "   Name Server: NS2.MARKMONITOR.COM\r\n",
        "   DNSSEC: unsigned\r\n",
        ">>> Last update of WHOIS database: 2026-04-20T12:00:00Z <<<\r\n",
    );

    #[test]
    fn test_gdpr_redacted_com_fixture() {
        let result = WhoisResponse::parse_internal(
            "redacted-example.com",
            "whois.verisign-grs.com",
            GDPR_REDACTED_COM_FIXTURE,
        );

        // Registry-level fields MUST still be extracted — these are never
        // redacted for gTLDs.
        assert_eq!(result.registrar.as_deref(), Some("MarkMonitor Inc."));
        assert!(result.creation_date.is_some());
        assert!(result.expiration_date.is_some());
        assert!(result.updated_date.is_some());
        assert_eq!(result.nameservers.len(), 2);
        assert_eq!(result.dnssec.as_deref(), Some("unsigned"));

        // PII fields are redacted — the parser actively filters out any
        // value containing "redacted" / "privacy" / "withheld" and returns
        // None for those, so downstream JSON/human output hides them
        // cleanly. This is a critical contract: GDPR-redacted responses
        // must not leak the literal "REDACTED FOR PRIVACY" string as if
        // it were a real contact name.
        assert!(
            result.registrant.is_none(),
            "registrant must be None when WHOIS says 'REDACTED FOR PRIVACY' \
             (got: {:?})",
            result.registrant
        );
        assert!(
            result.admin_name.is_none(),
            "admin_name must be None for redacted response"
        );
        assert!(
            result.tech_name.is_none(),
            "tech_name must be None for redacted response"
        );
        assert!(
            result.registrant_email.is_none(),
            "the 'Please query the RDDS service…' notice is not an email \
             (got: {:?})",
            result.registrant_email
        );

        // has_core_data should still be true — we have registrar, dates,
        // and nameservers.
        assert!(
            result.has_core_data(),
            "GDPR-redacted response still has core registration data"
        );

        assert!(!result.is_available());
    }

    /// Pure-CRLF thin response (registry-only) without any registrant data.
    /// This is what typical gTLD registries return before the registrar
    /// referral.
    const CRLF_THIN_REGISTRY_FIXTURE: &str = concat!(
        "Domain Name: thin-example.com\r\n",
        "Registry Domain ID: 1234567_DOMAIN_COM-VRSN\r\n",
        "Registrar WHOIS Server: whois.godaddy.com\r\n",
        "Registrar URL: http://www.godaddy.com\r\n",
        "Updated Date: 2025-09-01T00:00:00Z\r\n",
        "Creation Date: 2015-05-20T00:00:00Z\r\n",
        "Registry Expiry Date: 2026-05-20T00:00:00Z\r\n",
        "Registrar: GoDaddy.com, LLC\r\n",
        "Registrar IANA ID: 146\r\n",
        "Domain Status: ok https://icann.org/epp#ok\r\n",
        "Name Server: ns1.thin-example.com\r\n",
        "Name Server: ns2.thin-example.com\r\n",
        "DNSSEC: unsigned\r\n",
    );

    #[test]
    fn test_crlf_thin_registry_fixture() {
        let result = WhoisResponse::parse_internal(
            "thin-example.com",
            "whois.verisign-grs.com",
            CRLF_THIN_REGISTRY_FIXTURE,
        );

        // CRLF line endings must not break regex-based extraction.
        assert_eq!(result.registrar.as_deref(), Some("GoDaddy.com, LLC"));
        assert!(
            result.creation_date.is_some(),
            "creation date must parse under CRLF"
        );
        assert!(
            result.expiration_date.is_some(),
            "expiration date must parse under CRLF"
        );
        assert_eq!(result.nameservers.len(), 2);
        assert_eq!(result.dnssec.as_deref(), Some("unsigned"));
        assert_eq!(result.status.len(), 1);
        assert!(result.has_core_data());
        assert!(!result.is_available());
    }

    /// Minimal "not found" response — typical for available gTLDs.
    const AVAILABLE_COM_FIXTURE: &str = concat!(
        "No match for domain \"THIS-IS-UNREGISTERED-FOR-SURE-12345.COM\".\r\n",
        ">>> Last update of WHOIS database: 2026-04-20T12:00:00Z <<<\r\n",
    );

    #[test]
    fn test_available_com_fixture_is_detected() {
        let result = WhoisResponse::parse_internal(
            "this-is-unregistered-for-sure-12345.com",
            "whois.verisign-grs.com",
            AVAILABLE_COM_FIXTURE,
        );
        assert!(
            result.is_available(),
            "'No match for domain' response must be detected as available"
        );
        assert!(result.registrar.is_none());
        assert!(result.nameservers.is_empty());
    }

    // --- ccTLD formats found by the 2026-10-01 whois_sweep ---------------
    // Each body is trimmed from a live reply; the assertions name the fields
    // the generic parser used to miss.

    fn ymd(dt: Option<DateTime<Utc>>) -> Option<String> {
        dt.map(|d| d.format("%Y-%m-%d").to_string())
    }

    #[test]
    fn traficom_dot_leader_labels_parse() {
        // .fi (and .ax, same format): every label is padded with dots.
        let raw = "domain.............: nic.fi\n\
                   status.............: Registered\n\
                   created............: 16.2.1999 00:00:00\n\
                   expires............: 2.3.2027 14:08:22\n\
                   modified...........: 31.1.2026 16:08:34\n\
                   Nameservers\n\
                   nserver............: ns-se.elisa.net [OK]\n\
                   nserver............: ns-fi.elisa.net [OK]\n\
                   Registrar\n\
                   registrar..........: Ascio Technologies\n\
                   www................: www.ascio.com\n";
        let r = WhoisResponse::parse_internal("nic.fi", "whois.fi", raw);
        assert_eq!(r.registrar.as_deref(), Some("Ascio Technologies"));
        assert_eq!(ymd(r.creation_date).as_deref(), Some("1999-02-16"));
        assert_eq!(ymd(r.expiration_date).as_deref(), Some("2027-03-02"));
        assert_eq!(ymd(r.updated_date).as_deref(), Some("2026-01-31"));
        assert_eq!(r.nameservers, vec!["ns-se.elisa.net", "ns-fi.elisa.net"]);
        assert_eq!(r.status, vec!["Registered"]);
        assert!(r.has_core_data());
        // The raw body is kept verbatim; only extraction sees the rewrite.
        assert_eq!(r.raw_response, raw);
    }

    #[test]
    fn kaznic_dot_leaders_and_gmt_suffix_parse() {
        let raw = "Domain Name............: nic.kz\n\
                   Name Server list\n\
                   Name Server............: ns.nic.kz\n\
                   IP Address.............: 194.0.21.5, 2001:678:98:1::5\n\
                   Name Server............: ns1.nic.kz\n\
                   Domain created.........: 1999-08-17 21:34:57 (GMT+0:00)\n\
                   Last modified..........: 2022-12-05 17:28:31 (GMT+0:00)\n\
                   Domain status..........: ok - Normal state.\n\
                   Registrar created......: KAZNIC\n\
                   Current Registrar......: KAZNIC\n";
        let r = WhoisResponse::parse_internal("nic.kz", "whois.nic.kz", raw);
        assert_eq!(r.registrar.as_deref(), Some("KAZNIC"));
        assert_eq!(ymd(r.creation_date).as_deref(), Some("1999-08-17"));
        assert_eq!(ymd(r.updated_date).as_deref(), Some("2022-12-05"));
        assert_eq!(r.nameservers, vec!["ns.nic.kz", "ns1.nic.kz"]);
        assert_eq!(r.status, vec!["ok"]);
    }

    #[test]
    fn nic_monaco_space_padded_labels_parse() {
        let raw = "Domain             : NIC.MC\n\
                   Status             : ACTIVE\n\
                   Registrar          : NIC Monaco\n\
                   nserver            : ns1.nic.mc\n\
                   nserver            : ns2.nic.mc\n\
                   Created            : 2007-01-08T11:06:00Z\n\
                   Expires on         : 2027-01-08\n\
                   Last update        : 2026-01-08T00:10:01Z\n";
        let r = WhoisResponse::parse_internal("nic.mc", "whois.nic.mc", raw);
        assert_eq!(r.registrar.as_deref(), Some("NIC Monaco"));
        assert_eq!(ymd(r.creation_date).as_deref(), Some("2007-01-08"));
        assert_eq!(ymd(r.expiration_date).as_deref(), Some("2027-01-08"));
        assert_eq!(r.nameservers, vec!["ns1.nic.mc", "ns2.nic.mc"]);
        assert_eq!(r.status, vec!["ACTIVE"]);
    }

    #[test]
    fn label_padding_leaves_values_and_prose_alone() {
        let raw = "Registrar URL: https://example..test/a b :x\n\
                   This line has a colon : in prose.\n";
        let normalized = normalize_label_padding(raw);
        assert!(normalized.contains("Registrar URL: https://example..test/a b :x"));
        // A line-start label padded with blanks is normalized, nothing else.
        assert!(normalized.contains("This line has a colon: in prose."));
    }

    #[test]
    fn kg_ctime_dates_and_nameserver_block_parse() {
        let raw = "Domain NIC.KG (ACTIVE)\n\
                   Record created: Tue Jan 16 10:31:46 2001\n\
                   Record last updated on:  Tue Mar  3 21:02:44 2026\n\
                   Record expires on: Mon Mar 22 23:59:00 2027\n\
                   Name servers in the listed order:\n\
                   \n\
                   NS1.WEBSITE.ORG\n\
                   NS2.WEBSITE.ORG\n\
                   \n\
                   Some trailing.notice line\n";
        let r = WhoisResponse::parse_internal("nic.kg", "whois.kg", raw);
        assert_eq!(ymd(r.creation_date).as_deref(), Some("2001-01-16"));
        assert_eq!(ymd(r.updated_date).as_deref(), Some("2026-03-03"));
        assert_eq!(ymd(r.expiration_date).as_deref(), Some("2027-03-22"));
        assert_eq!(r.nameservers, vec!["ns1.website.org", "ns2.website.org"]);
    }

    #[test]
    fn nameserver_block_stops_at_non_host_line() {
        // Register.bg: glue after the host, block ends at the next field.
        let raw = "registration status: busy, active\n\
                   NAME SERVER INFORMATION:\n\
                   ns.digsys.bg \n\
                   a.nic.bg 192.92.129.99 2a02:6a80::192:92:129:99 \n\
                   DNSSEC: active\n";
        let r = WhoisResponse::parse_internal("nic.bg", "whois.register.bg", raw);
        assert_eq!(r.nameservers, vec!["ns.digsys.bg", "a.nic.bg"]);
        assert_eq!(r.status, vec!["busy", "active"]);
    }

    #[test]
    fn amnic_indented_dns_servers_block_parses() {
        let raw = "   Domain name: google.am\n\
                   \x20  Registrar:   abcdomain (ABCDomain LLC)\n\
                   \x20  DNS servers:\n\
                   \x20     ns1.google.com\n\
                   \x20     ns2.google.com\n\
                   \n\
                   \x20  Registered:    1999-06-05\n\
                   \x20  Expires:       2027-04-15\n";
        let r = WhoisResponse::parse_internal("google.am", "whois.amnic.net", raw);
        assert_eq!(r.nameservers, vec!["ns1.google.com", "ns2.google.com"]);
        assert!(r.has_core_data());
    }

    #[test]
    fn nic_mexico_dns_lines_parse() {
        let raw = "Domain Name:       nic.mx\r\n\
                   Created On:        1997-01-15\r\n\
                   Expiration Date:   2027-01-14\r\n\
                   Registrar:         Registry .MX\r\n\
                   Name Servers:\r\n\
                   \x20  DNS:            a.nic.mx       2001:1250:a000:0:0:0:0:1, 207.248.65.1\r\n\
                   \x20  DNS:            b.nic.mx       2001:1250:b000:0:0:0:0:1, 201.131.250.1\r\n\
                   DNSSEC DS Records:\r\n";
        let r = WhoisResponse::parse_internal("nic.mx", "whois.mx", raw);
        assert_eq!(r.nameservers, vec!["a.nic.mx", "b.nic.mx"]);
    }

    #[test]
    fn hkirc_dash_dates_and_spaced_nameserver_block_parse() {
        let raw = "Domain Name Commencement Date: 06-04-2004\n\
                   Expiry Date: 31-03-2027 \n\
                   Domain Status: Active\n\
                   Registrar Name: MARKMONITOR INC.\n\
                   Name Servers Information:\n\
                   \n\
                   NS1.GOOGLE.COM\n\
                   NS2.GOOGLE.COM\n\
                   \n\
                   Status Information:\n";
        let r = WhoisResponse::parse_internal("google.hk", "whois.hkirc.hk", raw);
        // 31-03 reveals day-first, so 06-04 is 6 April.
        assert_eq!(ymd(r.creation_date).as_deref(), Some("2004-04-06"));
        assert_eq!(ymd(r.expiration_date).as_deref(), Some("2027-03-31"));
        assert_eq!(r.nameservers, vec!["ns1.google.com", "ns2.google.com"]);
        assert!(r.has_core_data());
    }

    #[test]
    fn registro_br_ticket_suffixed_compact_date_parses() {
        let raw = "domain:      nic.br\n\
                   nserver:     a.dns.br\n\
                   created:     19970711 #46903\n\
                   changed:     20180327\n";
        let r = WhoisResponse::parse_internal("nic.br", "whois.registro.br", raw);
        assert_eq!(ymd(r.creation_date).as_deref(), Some("1997-07-11"));
    }

    #[test]
    fn isnic_full_month_name_date_parses() {
        let raw = "domain:       nic.is\n\
                   created:      September  5 2000\n\
                   expires:      September  5 2027\n";
        let r = WhoisResponse::parse_internal("nic.is", "whois.isnic.is", raw);
        assert_eq!(ymd(r.creation_date).as_deref(), Some("2000-09-05"));
        assert_eq!(ymd(r.expiration_date).as_deref(), Some("2027-09-05"));
    }

    #[test]
    fn restena_registrar_name_and_nic_bo_spanish_dates_parse() {
        let lu = "domainname:     nic.lu\nregistrar-name:         Fondation Restena\n";
        let r = WhoisResponse::parse_internal("nic.lu", "whois.dns.lu", lu);
        assert_eq!(r.registrar.as_deref(), Some("Fondation Restena"));

        let bo = "Dominio: google.bo\r\n\
                  Fecha de registro: 2019-01-15\r\n\
                  Fecha de vencimiento: 2027-01-15\r\n";
        let r = WhoisResponse::parse_internal("google.bo", "whois.nic.bo", bo);
        assert_eq!(ymd(r.creation_date).as_deref(), Some("2019-01-15"));
        assert_eq!(ymd(r.expiration_date).as_deref(), Some("2027-01-15"));
    }

    // ── ccTLD accuracy probe (2026-10-13): values that were present but wrong ──

    fn generic(domain: &str, raw: &str) -> WhoisResponse {
        WhoisResponse::parse_internal(domain, "whois.example", raw)
    }

    #[test]
    fn status_phrases_are_kept_whole_and_glosses_dropped() {
        // AMNIC (.am), PKNIC (.pk), ICANN-style URL suffix, KazNIC gloss.
        let r = generic("nic.am", "Status:      active, registrar locked\n");
        assert_eq!(r.status, vec!["active", "registrar locked"]);
        let r = generic("google.pk", "Status: Domain is Registered\n");
        assert_eq!(r.status, vec!["Domain is Registered"]);
        let r = generic(
            "example.com",
            "Domain Status: clientHold https://icann.org/epp#clientHold\n",
        );
        assert_eq!(r.status, vec!["clientHold"]);
        let r = generic("nic.kz", "Domain status: ok - Normal state.\n");
        assert_eq!(r.status, vec!["ok"]);
    }

    #[test]
    fn contact_section_state_and_status_are_not_domain_status() {
        // NIC México (.mx): an address `State:` under a contact heading.
        let mx = "Domain Name:       nic.mx\n\nRegistrant:\n   Name:           NIC México\n   State:          Nuevo Leon\n   Country:        Mexico\n";
        assert!(generic("nic.mx", mx).status.is_empty());
        // KazNIC (.kz): bare heading, and the domain status after the contacts.
        let kz = "Domain Name: nic.kz\n\nRegistrant\nName: KazNIC\nState: VKO\n\nDomain status: ok - Normal state.\n";
        assert_eq!(generic("nic.kz", kz).status, vec!["ok"]);
        // Hostmaster (.ua): `% Registrant:` comment heading over a contact object.
        let ua = "domain: nic.ua\nstatus: clientTransferProhibited\n\n% Registrant:\n% ===========\nperson: NIC.UA LLC\nstatus: ok\nstatus: linked\n";
        assert_eq!(
            generic("nic.ua", ua).status,
            vec!["clientTransferProhibited"]
        );
    }

    #[test]
    fn nameservers_drop_the_root_dot_and_placeholders() {
        // TCI (.ru) and UZINFOCOM (.uz)
        let r = generic(
            "nic.ru",
            "nserver: ns5.nic.ru. 31.177.67.100\nnserver: NS6.nic.ru.\n",
        );
        assert_eq!(r.nameservers, vec!["ns5.nic.ru", "ns6.nic.ru"]);
        let r = generic(
            "nic.uz",
            "   Name Server: ns.uz. 91.212.89.8\n   Name Server: not.defined. \n",
        );
        assert_eq!(r.nameservers, vec!["ns.uz"]);
    }

    #[test]
    fn registrar_admin_email_is_not_the_admin_email() {
        // PNINA (.ps), ARCEP (.bf): the registrar's own contacts come first.
        let raw =
            "Registrar Admin Email: CCOPS@markmonitor.com\nAdmin Email: dns-admin@google.com\n";
        assert_eq!(
            generic("google.ps", raw).admin_email.as_deref(),
            Some("dns-admin@google.com")
        );
        let raw = "Registrar Admin Email: registre@arcep.bf\n";
        assert!(generic("nic.bf", raw).admin_email.is_none());
    }

    #[test]
    fn dot_leaders_after_the_colon_are_padding() {
        // NIC Togo (.tg)
        let raw = "Domain:.............nic.tg\nRegistrar:..........NETMASTER SARL\n";
        assert_eq!(
            generic("nic.tg", raw).registrar.as_deref(),
            Some("NETMASTER SARL")
        );
    }

    #[test]
    fn personal_information_is_a_placeholder() {
        // THNIC (.th)
        let raw = "Tech Organization:          Personal Information\n";
        assert!(generic("nic.th", raw).tech_organization.is_none());
    }

    #[test]
    fn space_separated_fractional_seconds_parse() {
        // NIC.ar `changed: 2023-07-17 17:23:05.989470`
        let d = parse_date("2023-07-17 17:23:05.989470").map(|d| d.to_rfc3339());
        assert_eq!(d.as_deref(), Some("2023-07-17T17:23:05.989470+00:00"));
    }

    // ── ccTLD dates present in the reply but not read (issue #189) ──

    fn dates(domain: &str, raw: &str) -> [Option<String>; 3] {
        let r = generic(domain, raw);
        [r.creation_date, r.expiration_date, r.updated_date]
            .map(|d| d.map(|d| d.format("%Y-%m-%d %H:%M").to_string()))
    }

    fn some(s: &str) -> Option<String> {
        Some(s.to_string())
    }

    #[test]
    fn registry_date_labels_are_read() {
        // SK-NIC (.sk)
        let raw = "Created: 2003-09-30\nValid Until: 2027-09-30\nUpdated: 2026-09-08\n";
        assert_eq!(
            dates("google.sk", raw),
            [
                some("2003-09-30 00:00"),
                some("2027-09-30 00:00"),
                some("2026-09-08 00:00")
            ]
        );
        // UG registry (.ug): `Renewed On` is not an update.
        let raw = "Expires On: 2027-03-18\nRegistered On: 2004-08-03\nRenewed On: 2026-03-03\n\nInformation Last Updated: 2026-05-18T03:10:41.000+03:00\n";
        assert_eq!(
            dates("google.ug", raw),
            [
                some("2004-08-03 00:00"),
                some("2027-03-18 00:00"),
                some("2026-05-18 00:10")
            ]
        );
        // NIC Togo (.tg), dot leaders after the colon.
        let raw = "Activation:.........2023-03-02\nExpiration:.........2030-06-26\n";
        assert_eq!(
            dates("nic.tg", raw),
            [some("2023-03-02 00:00"), some("2030-06-26 00:00"), None]
        );
        // Norid (.no), BNNIC (.bn), hoster.by (.by), RNIDS (.rs), Register.si (.si)
        assert_eq!(
            dates("nic.no", "Last updated:    2026-01-27\n")[2],
            some("2026-01-27 00:00")
        );
        assert_eq!(
            dates("nic.bn", "Modified Date:\t\t02-Mar-2026 14:08:42\n")[2],
            some("2026-03-02 14:08")
        );
        assert_eq!(
            dates("nic.by", "Update Date: 2026-08-19\n")[2],
            some("2026-08-19 00:00")
        );
        assert_eq!(
            dates("nic.rs", "Modification date: 17.03.2025 14:55:15\n")[2],
            some("2025-03-17 14:55")
        );
        assert_eq!(
            dates("nic.si", "created:\t2008-10-28\nexpire:\t\t2027-10-28\n")[1],
            some("2027-10-28 00:00")
        );
    }

    #[test]
    fn whois_server_clock_is_not_the_updated_date() {
        // METU (.tr): `Last Update Time:` is when the reply was generated.
        let raw = "Created on..............: 2001-Aug-23.\nExpires on..............: 2027-Aug-22.\n\nLast Update Time: 2026-10-13T19:16:43+03:00\n";
        assert_eq!(
            dates("google.com.tr", raw),
            [some("2001-08-23 00:00"), some("2027-08-22 00:00"), None]
        );
    }

    #[test]
    fn record_created_and_expires_sentences_are_read() {
        // TWNIC (.tw): no colon, local time marked `(UTC+8)`.
        let raw = "   Record expires on 2027-10-31 12:47:54 (UTC+8)\n   Record created on 2005-10-27 17:02:34 (UTC+8)\n";
        assert_eq!(
            dates("google.tw", raw),
            [some("2005-10-27 09:02"), some("2027-10-31 04:47"), None]
        );
    }

    #[test]
    fn domain_changed_line_is_the_updated_date() {
        // nic.at (.at): the domain's `changed:` precedes the contacts'.
        let raw = "domain: nic.at\nchanged:           20200427 16:03:40\nregistered:        20000825 20:16:35\n\nnic-hdl: X\nchanged:           20121116 16:58:21\n";
        assert_eq!(
            dates("nic.at", raw),
            [some("2000-08-25 20:16"), None, some("2020-04-27 16:03")]
        );
    }

    #[test]
    fn named_month_and_twelve_hour_formats_parse() {
        // THNIC (.th), NITC (.jo)
        let raw = "Updated date: 23 Jun 2026\nCreated date: 17 Jul 2014\nExp date: 16 Jul 2027\n";
        assert_eq!(
            dates("nic.th", raw),
            [
                some("2014-07-17 00:00"),
                some("2027-07-16 00:00"),
                some("2026-06-23 00:00")
            ]
        );
        assert_eq!(
            dates("nic.jo", "Updated Date: Jul 26 2005 12:00AM\n")[2],
            some("2005-07-26 00:00")
        );
    }

    #[test]
    fn trailing_utc_offsets_convert_to_utc() {
        let fmt = |s: &str| parse_date(s).map(|d| d.format("%Y-%m-%d %H:%M").to_string());
        // Hostmaster (.ua) `+03`, ATI (.tn) `GMT+1`, a negative and a minutes offset.
        assert_eq!(fmt("2007-10-04 13:40:19+03"), some("2007-10-04 10:40"));
        assert_eq!(fmt("14-07-2009 00:00:00 GMT+1"), some("2009-07-13 23:00"));
        assert_eq!(fmt("2024-01-15 10:30:00 UTC-5"), some("2024-01-15 15:30"));
        assert_eq!(
            fmt("2024-01-15 10:30:00 (UTC+5:30)"),
            some("2024-01-15 05:00")
        );
        // RFC 3339 is unaffected; an out-of-range offset is not a date.
        assert_eq!(
            fmt("2026-05-18T03:10:41.000+03:00"),
            some("2026-05-18 00:10")
        );
        assert_eq!(fmt("2024-01-15 10:30:00+99"), None);
    }

    // ── ccTLD nameservers present in the reply but not read (issue #189) ──

    #[test]
    fn nameserver_heading_blocks_are_read() {
        let ns = |domain: &str, raw: &str| generic(domain, raw).nameservers;
        // DNS Belgium (.be): tab-indented under `Nameservers:`, then `Keys:`.
        assert_eq!(
            ns(
                "nic.be",
                "Nameservers:\n\tns3.combell.net\n\tns4.combell.net\n\nKeys:\n"
            ),
            vec!["ns3.combell.net", "ns4.combell.net"]
        );
        // SETAR (.aw)
        assert_eq!(
            ns("nic.aw", "Domain nameservers:\n   ns3.sidn.nl\n   ns1.sidn.nl\n\nCreation Date: 2014-02-25\n"),
            vec!["ns3.sidn.nl", "ns1.sidn.nl"]
        );
        // TWNIC (.tw): trailing blanks after each host.
        assert_eq!(
            ns("google.tw", "   Domain servers in listed order:\n      ns1.google.com     \n      ns2.google.com     \n"),
            vec!["ns1.google.com", "ns2.google.com"]
        );
        // METU (.tr): `** ` heading marker.
        assert_eq!(
            ns(
                "google.com.tr",
                "** Domain Servers:\nns4.google.com\nns1.google.com\n\n** Additional Info:\n"
            ),
            vec!["ns4.google.com", "ns1.google.com"]
        );
        // ATI (.tn): `Name....: host.` entries under `DNS servers`.
        assert_eq!(
            ns("nic.tn", "DNS servers\nName................: ns4.ati.tn.\nName................: ns6.ati.tn.\n"),
            vec!["ns4.ati.tn", "ns6.ati.tn"]
        );
    }

    #[test]
    fn numbered_and_annotated_nameserver_labels_are_read() {
        // TMNIC (.tm): glue continuation lines start with `:`.
        let tm = "NS 1   : dns01.nic.tm\n       : 74.116.178.11,74.116.179.11\n       : 2001:678:4::b\nNS 2   : dns1.nic.tm\n       : 194.0.1.11\n";
        assert_eq!(
            generic("nic.tm", tm).nameservers,
            vec!["dns01.nic.tm", "dns1.nic.tm"]
        );
        // NIC Togo (.tg)
        let tg = "Name Server (DB):...ns1.nic.tg\nName Server (DB):...ns2.nic.tg\n";
        assert_eq!(
            generic("nic.tg", tg).nameservers,
            vec!["ns1.nic.tg", "ns2.nic.tg"]
        );
    }

    // ── ccTLD registrar / registrant present in the reply but not read (#189) ──

    #[test]
    fn registrant_sections_are_read() {
        let reg = |domain: &str, raw: &str| generic(domain, raw).registrant;
        // TWNIC (.tw): colon heading, a blank line, then the bare name.
        assert_eq!(
            reg(
                "google.tw",
                "   Registrant:\n      \n      Google LLC\n      dns-admin@google.com\n"
            )
            .as_deref(),
            Some("Google LLC")
        );
        // METU (.tr): `** ` heading, bare name.
        assert_eq!(
            reg(
                "google.com.tr",
                "** Registrant:\nGoogle LLC\nHidden upon user request\n"
            )
            .as_deref(),
            Some("Google LLC")
        );
        // Traficom (.fi): colon-less `Holder`, padded `name` sub-field.
        assert_eq!(
            reg("nic.fi", "Holder\nname...............: Elisa Oyj\n").as_deref(),
            Some("Elisa Oyj")
        );
        // KazNIC (.kz): colon-less heading, `Name:`.
        assert_eq!(
            reg("nic.kz", "Registrant\nName...................: KazNIC\n").as_deref(),
            Some("KazNIC")
        );
        // ATI (.tn): `Owner Contact`; NIC.SM: `Owner:` and a bare name.
        assert_eq!(
            reg("nic.tn", "Owner Contact\nName................: ATI\n").as_deref(),
            Some("ATI")
        );
        assert_eq!(
            reg(
                "nic.sm",
                "Owner:\nTelecom Italia San Marino S.p.A.\nVia 28 Luglio, 212\n"
            )
            .as_deref(),
            Some("Telecom Italia San Marino S.p.A.")
        );
        // `.sn`: bracketed heading, French `Nom:` after other keys.
        assert_eq!(reg("nic.sn", "[HOLDER]\nID Contact: NICS100\nType: Organisation\nNom: Network Information Center Sénégal\n").as_deref(), Some("Network Information Center Sénégal"));
    }

    #[test]
    fn section_value_never_takes_another_field_or_crosses_a_blank_line() {
        // A non-name `Key: value` is skipped, and the section ends at a blank
        // line, so the next section's bare line is not borrowed.
        let raw = "Registrar:\nRegistrar IANA ID: 376\n\nSome Other Heading\n";
        assert!(generic("example.com", raw).registrar.is_none());
        // Mediaserv (.gf/.mq) placeholder for an unpublished contact.
        assert!(
            generic("nic.mq", "[holder]\nNO OBJECT FOUND!\nobject: 2068011865\n")
                .registrant
                .is_none()
        );
    }

    #[test]
    fn registrar_from_section_or_service_provider_label() {
        // METU (.tr): handle line first, then `Organization Name`.
        let raw =
            "** Registrar:\nNIC Handle\t\t: ogv40\nOrganization Name\t: ODTÜ GELİŞTİRME VAKFI\n";
        assert_eq!(
            generic("google.com.tr", raw).registrar.as_deref(),
            Some("ODTÜ GELİŞTİRME VAKFI")
        );
        // TWNIC (.tw)
        let raw = "Registration Service Provider: Markmonitor, Inc.\n";
        assert_eq!(
            generic("google.tw", raw).registrar.as_deref(),
            Some("Markmonitor, Inc.")
        );
    }

    #[test]
    fn registrant_and_organization_labels_are_read() {
        // .ae
        let r = generic("nic.ae", "Registrant Contact Name:         Etisalat\nRegistrant Contact Organisation: Etisalat Corp\n");
        assert_eq!(
            (r.registrant.as_deref(), r.organization.as_deref()),
            (Some("Etisalat"), Some("Etisalat Corp"))
        );
        // Tecnisys (.st)
        let r = generic(
            "nic.st",
            "registrant-organization: ST Registry\nregistrant-name:         ST Registry (TEM1)\n",
        );
        assert_eq!(
            (r.registrant.as_deref(), r.organization.as_deref()),
            (Some("ST Registry (TEM1)"), Some("ST Registry"))
        );
        // Registro.br: `owner:`, not `owner-c:`
        assert_eq!(
            generic("nic.br", "owner-c:     FAN\nowner:       NIC.BR\n")
                .registrant
                .as_deref(),
            Some("NIC.BR")
        );
        // THNIC (.th), HKIRC (.hk), hoster.by (.by)
        assert_eq!(
            generic("nic.th", "Domain Holder Organization: Google LLC\n")
                .organization
                .as_deref(),
            Some("Google LLC")
        );
        let hk = "Company English Name (It should be the same as the registered/corporation name on your Business Register Certificate or relevant documents): GOOGLE LLC\n";
        assert_eq!(
            generic("google.hk", hk).organization.as_deref(),
            Some("GOOGLE LLC")
        );
        assert_eq!(
            generic("nic.by", "Org: OOO Example\nCountry: BY\n")
                .organization
                .as_deref(),
            Some("OOO Example")
        );
    }

    #[test]
    fn plain_registrant_outranks_registrant_contact_name() {
        // auDA (.au) prints both; `Registrant:` is the holder.
        let raw = "Registrant: INSTRA CORPORATION PTY LTD\nRegistrant Contact Name: Domain Administrator\n";
        assert_eq!(
            generic("nic.au", raw).registrant.as_deref(),
            Some("INSTRA CORPORATION PTY LTD")
        );
    }

    // ── ccTLD status labels present in the reply but not read (#189) ──

    #[test]
    fn registry_status_labels_are_read() {
        let st = |domain: &str, raw: &str| generic(domain, raw).status;
        // ANINF (.ga) / NIC Sénégal (.sn), MoldData (.md), RESTENA (.lu)
        assert_eq!(
            st("nic.ga", "Statut:                        actif\n"),
            vec!["actif"]
        );
        assert_eq!(st("nic.md", "Domain state:   OK\n"), vec!["OK"]);
        assert_eq!(
            st("nic.lu", "domainname:     nic.lu\ndomaintype:     ACTIVE\n"),
            vec!["ACTIVE"]
        );
        // KG domain registry (.kg): status in parentheses after the name.
        assert_eq!(
            st(
                "nic.kg",
                "% banner\n\nDomain NIC.KG (ACTIVE)\n\nAdministrative Contact:\n"
            ),
            vec!["ACTIVE"]
        );
        // A `Domain …` line without the parenthesised status is not one.
        assert!(st("nic.kg", "Domain NIC.KG\n").is_empty());
    }

    #[test]
    fn html_entities_in_values_are_decoded() {
        // NIC Togo (.tg)
        assert_eq!(
            generic("nic.tg", "Status:.............Activ&eacute;\n").status,
            vec!["Activé"]
        );
        assert_eq!(
            decode_html_entities("Soci&#233;t&#xE9; &amp; Fils"),
            "Société & Fils"
        );
        // Unknown entities and a bare `&` are left alone.
        assert_eq!(decode_html_entities("A & B &bogus;"), "A & B &bogus;");
        assert_eq!(
            generic("x.tg", "Registrar: Netmaster &amp; Co\n")
                .registrar
                .as_deref(),
            Some("Netmaster & Co")
        );
    }

    #[test]
    fn isle_of_man_reply_parses_with_redacted_contacts() {
        // Live whois.nic.im reply for google.im (2026-10-13), trimmed. The
        // contacts are GDPR-redacted (`Name: Redacted`) and must stay empty;
        // .im publishes no creation date or status.
        let raw = "\n                This information has been redacted to comply with European Union General Data Protection Regulations (GDPR).\n\nDomain Name:\tgoogle.im\nDomain Managers\nName: Redacted\nAddress\nRedacted\nDomain Owners / Registrant\nName: Redacted\nAddress\nRedacted\nDomain Details\nExpiry Date: 16/08/2027 23:59:39\nName Server:ns1.google.com.\nName Server:ns2.google.com.\n";
        let r = generic("google.im", raw);
        assert_eq!(dates("google.im", raw)[1], some("2027-08-16 23:59"));
        assert_eq!(r.nameservers, vec!["ns1.google.com", "ns2.google.com"]);
        assert!(r.registrar.is_none() && r.registrant.is_none());
    }
}