tail-fin-591 0.7.8

591.com.tw Taiwan rentals adapter for tail-fin: listings, communities, price history, crawl
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
pub mod site;
pub mod types;

pub use site::FiveNineOneSite;
pub use types::{
    AreaRange, AreaValue, Community, CommunityDetail, CommunityRankItem, CommunityRanks,
    ContentUnit, CoordArea, CrawlOptions, DealTime, HighValueListing, HighValueParams,
    LabelledValue, MapCoord, NearbyCommunity, NewhouseDetail, NewhouseHousing, NewhouseLayoutBlock,
    NewhouseMarket, NewhouseMarketItem, NewhouseMarketRoom, NewhouseModules,
    NewhouseNearbyBusiness, NewhouseNearbyComm, NewhouseNearbyMarket, NewhousePage, NewhousePhoto,
    NewhousePhotoCategory, NewhousePoi, NewhousePriceList, NewhouseProject, NewhouseSaleCtrlInfo,
    NewhouseSaleCtrlPrice, NewhouseSalesAgent, NewhouseSurrounding, NewhouseSurroundingFacility,
    NewhouseSurroundingHousing, PendingArea, PendingPrice, PendingRoom, PriceRange, PriceRecord,
    PriceValue, Region, RentAddress, RentDetail, RentFactTable, RentLinkInfo, RentLinkInfoExt,
    RentNoticeItem, RentPhoto, RentPhotoGroup, RentPublish, RentRemark, RentServiceItem,
    RentServiceTable, RentSurround, RentSurroundCategory, RentSurroundPoi, RentTag, SaleDetail,
    SaleHouseListing, SaleHousePage, SaleListing, SaleSimilarWare, SearchListing, SearchParams,
};

use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, REFERER};
use tail_fin_common::TailFinError;
use types::{DetailResponse, HotResponse};

const USER_AGENT: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const HOT_URL: &str = "https://api.591.com.tw/api/community/rentHot";
const DETAIL_URL: &str = "https://api.591.com.tw/api/community/detail";
const NEARBY_URL: &str = "https://api.591.com.tw/api/community/nearby";
const SALE_LIST_URL: &str = "https://bff-house.591.com.tw/v1/web/sale/list";
const NEWHOUSE_LIST_URL: &str = "https://bff-newhouse.591.com.tw/v1/list-search";
const COMMUNITY_RANK_URL: &str = "https://bff.591.com.tw/v1/community/community-rank";
const RENT_LIST_URL: &str = "https://bff-house.591.com.tw/v3/web/rent/list";
const NEWHOUSE_BASE_INFO_URL: &str = "https://bff-newhouse.591.com.tw/v1/detail/base-info";
const NEWHOUSE_MODULE_INFO_URL: &str = "https://bff-newhouse.591.com.tw/v1/detail/module-info";
const NEWHOUSE_PHOTOS_URL: &str = "https://bff-newhouse.591.com.tw/v1/detail/photos";
const NEWHOUSE_SURROUNDING_URL: &str = "https://bff-newhouse.591.com.tw/v1/detail/surrounding";
const NEWHOUSE_NEARBY_MARKET_URL: &str = "https://bff-newhouse.591.com.tw/v1/detail/nearby-market";
const NEWHOUSE_PRICE_LIST_URL: &str = "https://bff-newhouse.591.com.tw/v1/price/list";
const HIGH_VALUE_SEARCH_URL: &str = "https://bff-house.591.com.tw/v1/high-value/search";
const COORDINATE_AREA_URL: &str = "https://bff.591.com.tw/v1/coordinate/area";
const RENT_DETAIL_URL: &str = "https://bff-house.591.com.tw/v2/web/rent/detail";
const RENT_PHOTOS_URL: &str = "https://bff-house.591.com.tw/v1/ware/photos";
const SALE_DETAIL_URL: &str = "https://bff-house.591.com.tw/v1/touch/sale/detail";
const SALE_SIMILAR_URL: &str = "https://bff-house.591.com.tw/v2/web/sale/similar-wares";

/// Required headers/params for endpoints that BFF-validates a non-empty
/// device ID. Originally the newhouse-detail family rejects with
/// `{"status":0,"msg":"設備 ID 不能為空"}` if `deviceid` (header) is
/// missing; the touch sale-detail endpoint does the same with the
/// `device_id` query param. Verified live 2026-04-30 — the server
/// doesn't validate the value's format, only its presence.
const BFF_DEVICE_HEADER_VALUE: &str = "touch";
const BFF_DEVICEID_VALUE: &str = "tail-fin-rust-client";

/// Page size that `bff-house.591.com.tw/v3/web/rent/list` returns per
/// request. Verified live 2026-04-30. Exposed publicly so the CLI's
/// pagination math (checkpoint advance, resume offset, default limit)
/// stays in sync with the library.
pub const RENT_PAGE_SIZE: usize = 30;

/// Threshold above which `warn_if_high_drop` flags an unusually high
/// ad-/ placeholder-filter rate. 50% means "if more than half the raw
/// items got dropped, something's probably wrong".
const HIGH_DROP_RATIO: f64 = 0.5;

/// Eprintln a warning when per-item filtering dropped more than
/// `HIGH_DROP_RATIO` of the raw items 591 returned. Lets operators
/// catch a 591-side schema change before the regression net does.
fn warn_if_high_drop(endpoint: &str, raw_count: usize, kept: usize) {
    if raw_count == 0 || kept >= raw_count {
        return;
    }
    let dropped = raw_count - kept;
    if (dropped as f64) / (raw_count as f64) > HIGH_DROP_RATIO {
        eprintln!(
            "[tail-fin-591] {endpoint}: filter dropped {dropped}/{raw_count} items \
             (>{:.0}% — possible 591-side schema change)",
            HIGH_DROP_RATIO * 100.0
        );
    }
}

/// Referer used for sale-side BFF endpoints.
const SALE_REFERER: &str = "https://sale.591.com.tw/";
/// Referer used for newhouse BFF endpoints.
const NEWHOUSE_REFERER: &str = "https://newhouse.591.com.tw/";
/// Referer used for cross-domain BFF endpoints (community-rank).
const WWW_REFERER: &str = "https://www.591.com.tw/";

/// Taiwan region codes used by the 591 API.
pub const REGIONS: &[Region] = &[
    Region {
        id: 1,
        name: "台北市",
    },
    Region {
        id: 2,
        name: "新北市",
    },
    Region {
        id: 3,
        name: "桃園市",
    },
    Region {
        id: 4,
        name: "台中市",
    },
    Region {
        id: 5,
        name: "台南市",
    },
    Region {
        id: 6,
        name: "高雄市",
    },
    Region {
        id: 7,
        name: "基隆市",
    },
    Region {
        id: 8,
        name: "新竹市",
    },
    Region {
        id: 9,
        name: "嘉義市",
    },
    Region {
        id: 10,
        name: "新竹縣",
    },
    Region {
        id: 11,
        name: "苗栗縣",
    },
    Region {
        id: 12,
        name: "彰化縣",
    },
    Region {
        id: 13,
        name: "南投縣",
    },
    Region {
        id: 14,
        name: "雲林縣",
    },
    Region {
        id: 15,
        name: "嘉義縣",
    },
    Region {
        id: 16,
        name: "屏東縣",
    },
    Region {
        id: 17,
        name: "宜蘭縣",
    },
    Region {
        id: 18,
        name: "花蓮縣",
    },
    Region {
        id: 19,
        name: "台東縣",
    },
    Region {
        id: 20,
        name: "澎湖縣",
    },
    Region {
        id: 21,
        name: "金門縣",
    },
    Region {
        id: 22,
        name: "連江縣",
    },
];

/// Client for the 591 rental platform public API.
///
/// Uses native HTTP (reqwest) — no browser required.
pub struct Client591 {
    client: reqwest::Client,
}

impl Client591 {
    /// Create a new client.
    pub fn new() -> Result<Self, TailFinError> {
        let mut headers = HeaderMap::new();
        headers.insert(
            ACCEPT,
            HeaderValue::from_static("application/json, text/plain, */*"),
        );
        headers.insert(
            REFERER,
            HeaderValue::from_static("https://rent.591.com.tw/"),
        );

        let client = reqwest::Client::builder()
            .user_agent(USER_AGENT)
            .default_headers(headers)
            .build()
            .map_err(|e| TailFinError::Api(e.to_string()))?;

        Ok(Self { client })
    }

    /// Fetch the hot community list for a given region.
    ///
    /// `region_id` is the 591 region code (1 = Taipei City).
    /// Returns up to `limit` communities (the API ignores the limit param,
    /// so slicing is done client-side).
    pub async fn hot(&self, region_id: u32, limit: usize) -> Result<Vec<Community>, TailFinError> {
        let resp: HotResponse = self
            .client
            .get(HOT_URL)
            .query(&[("region_id", region_id.to_string())])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 API returned status {}",
                resp.status
            )));
        }

        let mut items = resp.data.unwrap_or_default();
        items.truncate(limit);
        Ok(items)
    }

    /// Fetch detailed info for a community by ID.
    pub async fn community(&self, id: u64) -> Result<Option<CommunityDetail>, TailFinError> {
        let resp = self.fetch_detail(id).await?;
        Ok(resp.and_then(|d| d.community))
    }

    /// Fetch transaction price history for a community.
    ///
    /// Returns recent actual sale prices recorded in the ROC government registry.
    pub async fn price_history(
        &self,
        id: u64,
        limit: usize,
    ) -> Result<Vec<PriceRecord>, TailFinError> {
        let data = self.fetch_detail(id).await?;
        let mut records = data
            .and_then(|d| d.price)
            .map(|p| p.items)
            .unwrap_or_default();
        records.truncate(limit);
        Ok(records)
    }

    /// Fetch nearby communities (geographically close to `id`).
    ///
    /// 591 returns up to ~5 communities with sale-side stats (price
    /// per ping, min sale price, distance). Useful for "what else is
    /// in the same neighbourhood" queries; orthogonal to the rent-hot
    /// list (which is region-keyed, not community-keyed).
    pub async fn nearby(
        &self,
        id: u64,
        limit: usize,
    ) -> Result<Vec<NearbyCommunity>, TailFinError> {
        let resp: types::NearbyResponse = self
            .client
            .get(NEARBY_URL)
            .query(&[("id", id.to_string())])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 nearby returned status {}",
                resp.status
            )));
        }

        let mut items: Vec<NearbyCommunity> = resp
            .data
            .unwrap_or_default()
            .into_iter()
            .map(NearbyCommunity::from)
            .collect();
        items.truncate(limit);
        Ok(items)
    }

    /// Paginated **sale listings** for a region.
    ///
    /// Hits `bff-house.591.com.tw/v1/web/sale/list`. 591 paginates by
    /// `firstRow` (0-indexed offset, page size 30). The total in
    /// the returned `SaleHousePage` is the count of all matching
    /// listings across pages.
    ///
    /// `region_id` is the same scheme as `hot()` (1 = Taipei).
    pub async fn sale_list(
        &self,
        region_id: u32,
        first_row: usize,
        limit: usize,
    ) -> Result<SaleHousePage, TailFinError> {
        let resp: types::SaleListResponse = self
            .client
            .get(SALE_LIST_URL)
            .header(REFERER, SALE_REFERER)
            .query(&[
                ("type", "2"),
                ("category", "1"),
                ("regionid", &region_id.to_string()),
                ("firstRow", &first_row.to_string()),
                ("shType", "list"),
            ])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 sale_list returned status {}",
                resp.status
            )));
        }

        let data = resp.data.unwrap_or_default();
        // 591 mixes paid newhouse ads (`is_newhouse: 1`, different
        // schema) into the sale-listing array. Per-item parse +
        // filter_map drops ads — callers get only listings that
        // match the documented `SaleHouseListing` shape. We log to
        // stderr when the drop ratio is high so a 591-side schema
        // change doesn't silently degrade to empty pages.
        let raw_count = data.house_list.len();
        let houses: Vec<SaleHouseListing> = data
            .house_list
            .into_iter()
            .filter_map(|v| serde_json::from_value(v).ok())
            .take(limit)
            .collect();
        warn_if_high_drop("sale_list", raw_count, houses.len());
        Ok(SaleHousePage {
            total: data.total,
            first_row,
            houses,
        })
    }

    /// Paginated **new-construction (newhouse) projects** for a region.
    ///
    /// Hits `bff-newhouse.591.com.tw/v1/list-search`. Pagination uses
    /// `page` (1-indexed); 591 returns 20 per page.
    pub async fn newhouse_list(
        &self,
        region_id: u32,
        page: u32,
    ) -> Result<NewhousePage, TailFinError> {
        let resp: types::NewhouseListResponse = self
            .client
            .get(NEWHOUSE_LIST_URL)
            .header(REFERER, NEWHOUSE_REFERER)
            .query(&[
                ("page", &page.to_string()),
                ("device", &"pc".to_string()),
                ("regionid", &region_id.to_string()),
            ])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 newhouse_list returned status {}",
                resp.status
            )));
        }
        let data = resp
            .data
            .ok_or_else(|| TailFinError::Api("591 newhouse_list returned no data".into()))?;
        // Filter out empty placeholder slots (591 mixes ad-injection
        // wrappers into the items array — these are objects with a
        // single key and no `hid` / `build_name`).
        let raw_count = data.items.len();
        let items: Vec<NewhouseProject> = data
            .items
            .into_iter()
            .filter_map(|v| serde_json::from_value(v).ok())
            .collect();
        warn_if_high_drop("newhouse_list", raw_count, items.len());
        Ok(NewhousePage {
            total: data.total,
            online_total: data.online_total,
            page: data.page,
            per_page: data.per_page,
            total_page: data.total_page,
            items,
        })
    }

    /// Newhouse-detail GET request builder. The newhouse-detail
    /// family rejects requests without `device: touch` and
    /// `deviceid: <non-empty>` headers, so funnel every endpoint
    /// through this helper to keep auth + Origin/Referer consistent.
    fn newhouse_get(&self, url: &str) -> reqwest::RequestBuilder {
        self.client
            .get(url)
            .header(REFERER, NEWHOUSE_REFERER)
            .header("Origin", "https://newhouse.591.com.tw")
            .header("device", BFF_DEVICE_HEADER_VALUE)
            .header("deviceid", BFF_DEVICEID_VALUE)
    }

    /// Newhouse project detail core fields (build name, address, price,
    /// area, room layouts, build type, manager fees, dates, licenses, …).
    ///
    /// Hits `bff-newhouse.591.com.tw/v1/detail/base-info`. Returns the
    /// curated [`NewhouseHousing`] subset of the wire `data.housing`
    /// block (80+ fields → ~25 most useful for project shopping).
    /// `hid` is the project ID — same as `NewhouseProject.hid` from
    /// `newhouse_list`.
    pub async fn newhouse_base_info(&self, hid: u64) -> Result<NewhouseHousing, TailFinError> {
        let resp: types::NewhouseBaseInfoResponse = self
            .newhouse_get(NEWHOUSE_BASE_INFO_URL)
            .query(&[
                ("id", hid.to_string()),
                ("region_id", "1".to_string()),
                ("is_auth", "0".to_string()),
            ])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 newhouse_base_info returned status {} ({})",
                resp.status,
                resp.msg.as_deref().unwrap_or("")
            )));
        }
        resp.data
            .and_then(|d| d.housing)
            .ok_or_else(|| TailFinError::Api(format!("591 newhouse {hid} not found")))
    }

    /// Newhouse project module-info: floor plans, market history,
    /// listed sales agents.
    ///
    /// Hits `bff-newhouse.591.com.tw/v1/detail/module-info`. Returns
    /// the curated [`NewhouseModules`] aggregate of `layout`,
    /// `market`, and `sales`. The `news` and `report` wire keys are
    /// dropped (mostly empty across the projects we sampled).
    pub async fn newhouse_module_info(&self, hid: u64) -> Result<NewhouseModules, TailFinError> {
        let resp: types::NewhouseModuleInfoResponse = self
            .newhouse_get(NEWHOUSE_MODULE_INFO_URL)
            .query(&[
                ("id", hid.to_string()),
                ("region_id", "1".to_string()),
                ("is_auth", "0".to_string()),
            ])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 newhouse_module_info returned status {} ({})",
                resp.status,
                resp.msg.as_deref().unwrap_or("")
            )));
        }
        let data = resp
            .data
            .ok_or_else(|| TailFinError::Api(format!("591 newhouse {hid} not found")))?;
        Ok(NewhouseModules {
            layout: data.layout,
            market: data.market,
            sales_agents: data.sales.data,
        })
    }

    /// Newhouse project photo gallery, organized by category.
    ///
    /// Hits `bff-newhouse.591.com.tw/v1/detail/photos`. Returns a
    /// Vec of [`NewhousePhotoCategory`] (cover / floor plan / traffic
    /// / 3D / real-life / environment) — empty Vec if the project has
    /// no photos uploaded.
    pub async fn newhouse_photos(
        &self,
        hid: u64,
    ) -> Result<Vec<NewhousePhotoCategory>, TailFinError> {
        let resp: types::NewhousePhotosResponse = self
            .newhouse_get(NEWHOUSE_PHOTOS_URL)
            .query(&[("id", hid.to_string()), ("is_auth", "0".to_string())])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 newhouse_photos returned status {} ({})",
                resp.status,
                resp.msg.as_deref().unwrap_or("")
            )));
        }
        Ok(resp.data.unwrap_or_default())
    }

    /// Newhouse project's surrounding POIs (transit, schools, life
    /// amenities) plus building/sales-office geo coordinates.
    ///
    /// Hits `bff-newhouse.591.com.tw/v1/detail/surrounding`.
    pub async fn newhouse_surrounding(
        &self,
        hid: u64,
    ) -> Result<NewhouseSurrounding, TailFinError> {
        let resp: types::NewhouseSurroundingResponse = self
            .newhouse_get(NEWHOUSE_SURROUNDING_URL)
            .query(&[("id", hid.to_string()), ("is_auth", "0".to_string())])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 newhouse_surrounding returned status {} ({})",
                resp.status,
                resp.msg.as_deref().unwrap_or("")
            )));
        }
        resp.data
            .ok_or_else(|| TailFinError::Api(format!("591 newhouse {hid} not found")))
    }

    /// Newhouse project's nearby resale comps (other communities) and
    /// business districts (商圈) with average prices.
    ///
    /// Hits `bff-newhouse.591.com.tw/v1/detail/nearby-market`. Note
    /// the URL param is `hid` (not `id`) on this endpoint — separate
    /// query semantics from the `id`-keyed siblings.
    pub async fn newhouse_nearby_market(
        &self,
        hid: u64,
    ) -> Result<NewhouseNearbyMarket, TailFinError> {
        let resp: types::NewhouseNearbyMarketResponse = self
            .newhouse_get(NEWHOUSE_NEARBY_MARKET_URL)
            .query(&[("hid", hid.to_string())])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 newhouse_nearby_market returned status {} ({})",
                resp.status,
                resp.msg.as_deref().unwrap_or("")
            )));
        }
        Ok(resp.data.unwrap_or(NewhouseNearbyMarket {
            community_items: vec![],
            business_items: vec![],
        }))
    }

    /// Newhouse project price-list (per-unit catalogue + sale-control
    /// metadata).
    ///
    /// Hits `bff-newhouse.591.com.tw/v1/price/list` with `trans_type`
    /// fixed at 1 (sale price; trans_type=2 returns rental-side data
    /// for the same projects, not exercised here). Often less rich
    /// than `newhouse_module_info().market` for active pre-sale
    /// projects — call both and prefer module-info's market block
    /// for actual transaction history.
    pub async fn newhouse_price_list(&self, hid: u64) -> Result<NewhousePriceList, TailFinError> {
        let resp: types::NewhousePriceListResponse = self
            .newhouse_get(NEWHOUSE_PRICE_LIST_URL)
            .query(&[
                ("id", hid.to_string()),
                ("region_id", "1".to_string()),
                ("trans_type", "1".to_string()),
                ("room", "0".to_string()),
                ("from", "detail".to_string()),
            ])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 newhouse_price_list returned status {} ({})",
                resp.status,
                resp.msg.as_deref().unwrap_or("")
            )));
        }
        resp.data
            .ok_or_else(|| TailFinError::Api(format!("591 newhouse {hid} not found")))
    }

    /// Fetch the full newhouse-detail bundle in parallel.
    ///
    /// Calls all 6 detail sub-endpoints (`base-info`, `module-info`,
    /// `photos`, `surrounding`, `nearby-market`, `price/list`)
    /// concurrently via `tokio::join!`. Each sub-call's success or
    /// failure lands independently in the corresponding bundle field
    /// — partial failures don't fail the whole bundle. Returns once
    /// all 6 calls have settled.
    ///
    /// Typical wall-clock: ~350ms (the slowest sub-call dominates) —
    /// roughly 4× faster than calling the 6 atomic methods serially.
    pub async fn newhouse_detail(&self, hid: u64) -> NewhouseDetail {
        let (base, modules, photos, surround, nearby, price) = tokio::join!(
            self.newhouse_base_info(hid),
            self.newhouse_module_info(hid),
            self.newhouse_photos(hid),
            self.newhouse_surrounding(hid),
            self.newhouse_nearby_market(hid),
            self.newhouse_price_list(hid),
        );
        let (housing, housing_error) = match base {
            Ok(v) => (Some(v), None),
            Err(e) => (None, Some(e.to_string())),
        };
        let (modules, modules_error) = match modules {
            Ok(v) => (Some(v), None),
            Err(e) => (None, Some(e.to_string())),
        };
        let (photos_vec, photos_error) = match photos {
            Ok(v) => (v, None),
            Err(e) => (vec![], Some(e.to_string())),
        };
        let (surrounding, surrounding_error) = match surround {
            Ok(v) => (Some(v), None),
            Err(e) => (None, Some(e.to_string())),
        };
        let (nearby_market, nearby_market_error) = match nearby {
            Ok(v) => (Some(v), None),
            Err(e) => (None, Some(e.to_string())),
        };
        let (price_list, price_list_error) = match price {
            Ok(v) => (Some(v), None),
            Err(e) => (None, Some(e.to_string())),
        };
        NewhouseDetail {
            housing,
            housing_error,
            modules,
            modules_error,
            photos: photos_vec,
            photos_error,
            surrounding,
            surrounding_error,
            nearby_market,
            nearby_market_error,
            price_list,
            price_list_error,
        }
    }

    /// Two community rankings for a region — by price metric and by
    /// sale-activity metric. Hits
    /// `bff.591.com.tw/v1/community/community-rank`. Each slot holds
    /// up to ~10 communities; both share the same `time` snapshot.
    pub async fn community_rank(&self, region_id: u32) -> Result<CommunityRanks, TailFinError> {
        let resp: types::CommunityRankResponse = self
            .client
            .get(COMMUNITY_RANK_URL)
            .header(REFERER, WWW_REFERER)
            .query(&[("regionid", region_id.to_string())])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 community_rank returned status {}",
                resp.status
            )));
        }
        let data = resp
            .data
            .ok_or_else(|| TailFinError::Api("591 community_rank returned no data".into()))?;
        // The two slots come with separate `time` strings; use the
        // price-side time as canonical (they're observed identical).
        Ok(CommunityRanks {
            price_data: data.price_data.data,
            sale_data: data.sale_data.data,
            time: data.price_data.time,
        })
    }

    /// Pure-HTTP rental listing search via `bff-house.591.com.tw/v3/web/rent/list`.
    ///
    /// **No browser, no CSRF, no cookies required** — verified
    /// 2026-04-30 against a clean curl from a fresh process. See
    /// `docs/superpowers/research/2026-04-30-591-har-discovery.md`.
    ///
    /// Pagination is by `params.first_row` (page size 30). The server
    /// echoes `firstRow: 0` even on later pages; trust your input
    /// offset, not the response field.
    ///
    /// Returns `(total_matching, listings)` where `total_matching` is
    /// the global count across all pages (NOT this page's length).
    pub async fn rent_search(
        &self,
        params: &SearchParams,
    ) -> Result<(u32, Vec<SearchListing>), TailFinError> {
        let region = params.region_id.to_string();
        let first_row = params.first_row.to_string();
        let mut query: Vec<(&str, String)> = vec![("regionid", region), ("firstRow", first_row)];
        if let Some(k) = params.kind {
            query.push(("kind", k.to_string()));
        }
        if params.price_min.is_some() || params.price_max.is_some() {
            let lo = params.price_min.map(|p| p.to_string()).unwrap_or_default();
            let hi = params.price_max.map(|p| p.to_string()).unwrap_or_default();
            query.push(("multiPrice", format!("{lo}_{hi}")));
        }
        if let Some(o) = &params.order {
            query.push(("order", o.clone()));
        }

        let resp: types::RentListResponse = self
            .client
            .get(RENT_LIST_URL)
            .query(&query)
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 rent_search returned status {}",
                resp.status
            )));
        }

        let data = resp
            .data
            .ok_or_else(|| TailFinError::Api("591 rent_search returned no data".into()))?;

        let total = data.total;
        let limit = params.limit.max(1);
        let listings: Vec<SearchListing> = data
            .items
            .into_iter()
            .take(limit)
            .map(SearchListing::from)
            .collect();
        Ok((total, listings))
    }

    /// Crawl all rental listings matching `params`, paginating
    /// automatically via `/v3/web/rent/list`.
    ///
    /// Calls `on_page(page_num, first_row, listings)` after each page.
    /// Stops when a page returns fewer than `RENT_PAGE_SIZE` items
    /// (last page reached) or after `opts.max_pages` pages if non-zero.
    ///
    /// Returns the total number of listings the callback received.
    pub async fn rent_crawl<F>(
        &self,
        params: &SearchParams,
        opts: &CrawlOptions,
        mut on_page: F,
    ) -> Result<usize, TailFinError>
    where
        F: FnMut(usize, usize, &[SearchListing]),
    {
        let mut total_fetched = 0;
        let mut page = opts.start_page;
        let mut pages_fetched = 0;

        loop {
            let first_row = page * RENT_PAGE_SIZE;
            let page_params = SearchParams {
                first_row,
                limit: RENT_PAGE_SIZE,
                ..params.clone()
            };

            let listings = {
                let mut last_err: Option<TailFinError> = None;
                let mut result: Option<Vec<SearchListing>> = None;
                for attempt in 0..=opts.retries {
                    match self.rent_search(&page_params).await {
                        Ok((_total, items)) => {
                            result = Some(items);
                            break;
                        }
                        Err(e) => {
                            if attempt < opts.retries {
                                eprintln!(
                                    "[crawl] page {} attempt {}/{} failed: {}; retrying in 2s",
                                    page + 1,
                                    attempt + 1,
                                    opts.retries,
                                    e
                                );
                                tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
                            }
                            last_err = Some(e);
                        }
                    }
                }
                match result {
                    Some(items) => items,
                    None => return Err(last_err.unwrap()),
                }
            };

            let n = listings.len();
            if n > 0 {
                on_page(page, first_row, &listings);
                total_fetched += n;
            }
            pages_fetched += 1;

            let max_reached = opts.max_pages > 0 && pages_fetched >= opts.max_pages;
            let last_page = n < RENT_PAGE_SIZE;
            if last_page || max_reached {
                break;
            }
            if opts.delay_ms > 0 {
                tokio::time::sleep(tokio::time::Duration::from_millis(opts.delay_ms)).await;
            }
            page += 1;
        }

        Ok(total_fetched)
    }

    /// Curated premium-listing search.
    ///
    /// POSTs JSON to `bff-house.591.com.tw/v1/high-value/search`.
    /// 591 returns a small (~6 items) hand-curated pool of premium
    /// sale listings; the request-side `kind`/`type`/`section_id`/
    /// `shape`/`room`/`price`/`area` filters are "preferred" rather
    /// than strict (591's curation logic decides the final set).
    ///
    /// **Two kind values populate distinct curated pools**: `9` (the
    /// default, mostly residential) and `10` (a separate bucket with
    /// different streets / `post_id`s). Verified live 2026-04-30 — see
    /// [`HighValueParams`] for the full quirk catalog. Use
    /// [`HighValueParams::for_region`] for the typical defaults
    /// (kind=9, type=2).
    pub async fn high_value_search(
        &self,
        params: &HighValueParams,
    ) -> Result<Vec<HighValueListing>, TailFinError> {
        let resp: types::HighValueSearchResponse = self
            .client
            .post(HIGH_VALUE_SEARCH_URL)
            .header(REFERER, SALE_REFERER)
            .header("Origin", "https://sale.591.com.tw")
            .json(params)
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 high_value_search returned status {} ({})",
                resp.status, resp.msg
            )));
        }
        Ok(resp.data)
    }

    /// Reverse-geocode GPS coordinates to a 591 region+section.
    ///
    /// Hits `bff.591.com.tw/v1/coordinate/area`. Returns `Some(area)`
    /// when the coordinates land inside Taiwan, `None` otherwise (591
    /// responds with `status: 0` and the message
    /// `"坐标不在台湾范围内"`).
    ///
    /// `region_id` is sent as a hint but doesn't constrain the
    /// response — the server resolves the actual region/section from
    /// the lat/lng. Pass any valid region (1 = Taipei is a safe
    /// default).
    ///
    /// **Status-handling differs from sibling endpoints.** Most
    /// `Client591` methods collapse non-1 status into either an
    /// error or `Ok(None)`; this method instead matches `1` →
    /// `Ok(Some(_))`, `0` → `Ok(None)` (documented miss), anything
    /// else → `Err`. The intent: a future server-side wire-state
    /// change becomes loud-fail rather than silently swallowed.
    pub async fn coordinate_area(
        &self,
        latitude: f64,
        longitude: f64,
        region_id: u32,
    ) -> Result<Option<CoordArea>, TailFinError> {
        let resp: types::CoordResponse = self
            .client
            .get(COORDINATE_AREA_URL)
            .header(REFERER, NEWHOUSE_REFERER)
            .query(&[
                ("latitude", latitude.to_string()),
                ("longitude", longitude.to_string()),
                ("region_id", region_id.to_string()),
                ("device", "touch".to_string()),
            ])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        // status semantics: 1 = hit (data is {area: …}), 0 = miss
        // (data is `[]`, msg explains why). Anything else is an
        // unexpected wire-state — surface the msg as a real error so
        // a future 591 schema flip doesn't silently swallow into None.
        match resp.status {
            1 => {}
            0 => return Ok(None),
            other => {
                return Err(TailFinError::Api(format!(
                    "591 coordinate_area returned status {other} ({})",
                    resp.msg
                )));
            }
        }
        // Hit shape: `data: { area: { region_id, region_name, ... } }`.
        // Pluck `data.area` from the raw Value and typed-deserialize.
        // On status=1, data should be an object containing `area`.
        // If it's anything else (e.g. an array — the off-Taiwan shape
        // — or a missing key), surface a shape-aware error rather
        // than a misleading "missing key" so a future server-side
        // wire change is debuggable.
        let area_value = resp.data.get("area").cloned().ok_or_else(|| {
            TailFinError::Parse(format!(
                "unexpected data shape on hit (expected object with 'area' key, got {})",
                if resp.data.is_array() {
                    "array"
                } else if resp.data.is_object() {
                    "object without 'area' key"
                } else {
                    "non-object"
                }
            ))
        })?;
        let area: CoordArea =
            serde_json::from_value(area_value).map_err(|e| TailFinError::Parse(e.to_string()))?;
        Ok(Some(area))
    }

    /// Single rent listing detail.
    ///
    /// Hits `bff-house.591.com.tw/v2/web/rent/detail`. Returns the
    /// curated [`RentDetail`] subset of the wire `data` block — full
    /// address with lat/lng, deposit + cost breakdown, structured
    /// houseInfo / preference / service / surround sections, plus
    /// the listing's primary contact ([`RentLinkInfo`]).
    ///
    /// `post_id` is the rent listing ID (`SearchListing.post_id` from
    /// `rent_search`). Pure HTTP — no browser, no auth.
    pub async fn rent_detail(&self, post_id: u64) -> Result<RentDetail, TailFinError> {
        let resp: types::RentDetailResponse = self
            .client
            .get(RENT_DETAIL_URL)
            .query(&[("id", post_id.to_string())])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 rent_detail returned status {} ({})",
                resp.status, resp.msg
            )));
        }
        resp.data
            .ok_or_else(|| TailFinError::Api(format!("591 rent listing {post_id} not found")))
    }

    /// Categorized photo gallery for a rent listing.
    ///
    /// Hits `bff-house.591.com.tw/v1/ware/photos`. Returns a Vec of
    /// [`RentPhotoGroup`] (photo buckets like `"picture"`, `"floor"`,
    /// `"environment"`); empty Vec if the listing has no photos.
    /// `type=1` is hardcoded on the wire — it's the rent-side photo
    /// query mode (verified live 2026-04-30).
    pub async fn rent_photos(&self, post_id: u64) -> Result<Vec<RentPhotoGroup>, TailFinError> {
        let resp: types::RentPhotosResponse = self
            .client
            .get(RENT_PHOTOS_URL)
            .query(&[("id", post_id.to_string()), ("type", "1".to_string())])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 rent_photos returned status {} ({})",
                resp.status, resp.msg
            )));
        }
        Ok(resp.data.map(|d| d.list).unwrap_or_default())
    }

    /// Single sale listing detail.
    ///
    /// Hits `bff-house.591.com.tw/v1/touch/sale/detail`. Returns the
    /// curated [`SaleDetail`] subset of the wire `data` block —
    /// title, price (raw + numeric), area / layout / floor / shape,
    /// lat / lng, age, fitment, agent contact (`linkman`, `mobile`,
    /// `telephone`, `email`, `identity`, `company_name`).
    ///
    /// `post_id` is the bare numeric sale listing ID. The wire
    /// expects an `S`-prefixed form (`"S19599759"`) — the adapter
    /// adds the prefix for you. Uses `device_id=tail-fin-rust-client`
    /// and `device=touch` query params; verified live 2026-05-01 that
    /// the endpoint returns `status: 0` without a non-empty `device_id`.
    pub async fn sale_detail(&self, post_id: u64) -> Result<SaleDetail, TailFinError> {
        let id = format!("S{post_id}");
        let resp: types::SaleDetailResponse = self
            .client
            .get(SALE_DETAIL_URL)
            .header(REFERER, SALE_REFERER)
            .header("Origin", "https://sale.591.com.tw")
            .query(&[
                ("id", id.as_str()),
                ("is_business", "0"),
                ("device_id", BFF_DEVICEID_VALUE),
                ("__v__", "1"),
                ("region_id", "1"),
                ("device", "touch"),
            ])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 sale_detail returned status {} ({})",
                resp.status,
                resp.msg.as_deref().unwrap_or("")
            )));
        }
        resp.data
            .ok_or_else(|| TailFinError::Api(format!("591 sale listing {post_id} not found")))
    }

    /// Similar sale listings — curated "you might also like" set.
    ///
    /// Hits `bff-house.591.com.tw/v2/web/sale/similar-wares`. Returns
    /// up to ~5 [`SaleSimilarWare`] entries (compact title / price /
    /// area / room / cover-photo URL) for cross-listing browse.
    /// Anonymous, no special headers needed.
    pub async fn sale_similar_wares(
        &self,
        post_id: u64,
    ) -> Result<Vec<SaleSimilarWare>, TailFinError> {
        let resp: types::SaleSimilarWaresResponse = self
            .client
            .get(SALE_SIMILAR_URL)
            .header(REFERER, SALE_REFERER)
            .header("Origin", "https://sale.591.com.tw")
            .query(&[
                ("id", post_id.to_string()),
                ("region_id", "1".to_string()),
                ("device", "touch".to_string()),
            ])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Err(TailFinError::Api(format!(
                "591 sale_similar_wares returned status {} ({})",
                resp.status,
                resp.msg.as_deref().unwrap_or("")
            )));
        }
        Ok(resp.data)
    }

    /// Fetch active sale listings near a community.
    ///
    /// Listings are flattened across all room types, sorted by post time (API order).
    pub async fn sales(
        &self,
        id: u64,
        limit: usize,
    ) -> Result<(u32, Vec<SaleListing>), TailFinError> {
        let data = self.fetch_detail(id).await?;
        let sale = data.and_then(|d| d.sale);
        let total = sale.as_ref().map(|s| s.total).unwrap_or(0);
        let mut listings: Vec<SaleListing> = sale
            .map(|s| s.rooms.into_iter().flat_map(|r| r.items).collect())
            .unwrap_or_default();
        listings.truncate(limit);
        Ok((total, listings))
    }

    // Shared detail fetch — one HTTP call, all sections.
    async fn fetch_detail(&self, id: u64) -> Result<Option<types::DetailData>, TailFinError> {
        let resp: DetailResponse = self
            .client
            .get(DETAIL_URL)
            .query(&[("id", id.to_string())])
            .send()
            .await
            .map_err(|e| TailFinError::Api(e.to_string()))?
            .json()
            .await
            .map_err(|e| TailFinError::Parse(e.to_string()))?;

        if resp.status != 1 {
            return Ok(None);
        }

        Ok(resp.data)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{DetailResponse, HotResponse};

    #[test]
    fn test_client_new() {
        let client = Client591::new();
        assert!(client.is_ok());
    }

    #[test]
    fn test_rent_list_response_deserialize() {
        use crate::types::RentListResponse;
        let json = r#"{
            "status": 1,
            "data": {
                "total": "3728",
                "firstRow": 0,
                "items": [{
                    "id": 21121520,
                    "type": 1,
                    "kind": 2,
                    "kind_name": "獨立套房",
                    "title": "中山套房",
                    "price": "17,500",
                    "price_unit": "元/月",
                    "address": "中山區-中山北路一段105巷",
                    "area_name": "9坪",
                    "layoutStr": "",
                    "floor_name": "4F/6F",
                    "photoList": ["https://img2.591.com.tw/a.jpg"],
                    "tags": ["近捷運"],
                    "refresh_time": "7小時內更新",
                    "regionid": 1,
                    "sectionid": 3
                }]
            }
        }"#;
        let resp: RentListResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 1);
        let data = resp.data.unwrap();
        assert_eq!(data.total, 3728);
        assert_eq!(data.items.len(), 1);
        assert_eq!(data.items[0].id, 21121520);
        assert_eq!(data.items[0].title, "中山套房");
    }

    #[test]
    fn test_rent_list_item_into_search_listing_full() {
        use crate::types::RentListItem;
        let item = RentListItem {
            id: 21121520,
            title: "中山套房".into(),
            price: Some("17,500".into()),
            price_unit: Some("元/月".into()),
            address: Some("中山區-中山北路".into()),
            area_name: Some("9坪".into()),
            kind_name: Some("獨立套房".into()),
            layout_str: Some("2房1廳".into()),
            floor_name: Some("4F/6F".into()),
            photo_list: Some(vec!["https://img2.591.com.tw/a.jpg".into()]),
            tags: Some(vec!["近捷運".into()]),
            refresh_time: Some("7小時內更新".into()),
        };
        let listing: SearchListing = item.into();
        assert_eq!(listing.post_id, 21121520);
        assert_eq!(listing.title, "中山套房");
        assert_eq!(listing.price.as_deref(), Some("17,500"));
        assert_eq!(listing.area.as_deref(), Some("9坪"));
        assert_eq!(listing.room.as_deref(), Some("2房1廳"));
        assert_eq!(listing.floor.as_deref(), Some("4F/6F"));
        assert_eq!(listing.tags.as_ref().map(|v| v.len()), Some(1));
        assert_eq!(listing.post_time.as_deref(), Some("7小時內更新"));
    }

    #[test]
    fn test_rent_list_item_into_search_listing_empty_collections_become_none() {
        use crate::types::RentListItem;
        let item = RentListItem {
            id: 1,
            title: "x".into(),
            price: None,
            price_unit: None,
            address: None,
            area_name: None,
            kind_name: None,
            layout_str: Some(String::new()),
            floor_name: None,
            photo_list: Some(vec![]),
            tags: Some(vec![]),
            refresh_time: None,
        };
        let listing: SearchListing = item.into();
        assert!(listing.room.is_none(), "empty layoutStr should become None");
        assert!(listing.photo_list.is_none(), "empty Vec should become None");
        assert!(listing.tags.is_none(), "empty Vec should become None");
    }

    #[test]
    fn test_rent_list_response_total_accepts_int() {
        // 591 sends `total` as a string today (`"3728"`), but the
        // sibling sale-list endpoint already returns ints. Lock the
        // forward-compat contract so a server-side type flip doesn't
        // silently land at 0 or fail loudly without explanation.
        use crate::types::RentListResponse;
        let json = r#"{"status":1,"data":{"total":3728,"firstRow":0,"items":[]}}"#;
        let resp: RentListResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.data.unwrap().total, 3728);
    }

    #[test]
    fn test_rent_list_response_total_garbage_string_fails_loudly() {
        // The pre-fix code did `.parse().unwrap_or(0)` which silently
        // collapsed garbage to 0. After the fix the deserializer
        // rejects non-numeric strings, surfacing as TailFinError::Parse
        // at the `.json()` call site rather than a phantom zero.
        use crate::types::RentListResponse;
        let json = r#"{"status":1,"data":{"total":"abc","firstRow":0,"items":[]}}"#;
        let result: Result<RentListResponse, _> = serde_json::from_str(json);
        assert!(result.is_err(), "garbage total should fail to deserialize");
    }

    #[test]
    fn test_rent_list_response_error_status() {
        use crate::types::RentListResponse;
        let json = r#"{"status":0,"msg":"參數錯誤"}"#;
        let resp: RentListResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 0);
        assert!(resp.data.is_none());
    }

    #[test]
    fn test_hot_response_deserialize() {
        let json = r#"{"status":1,"msg":"請求成功","data":[{"id":"123","name":"Test"},{"id":"456","name":"Other"}]}"#;
        let resp: HotResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 1);
        let data = resp.data.unwrap();
        assert_eq!(data.len(), 2);
        assert_eq!(data[0].id, "123");
        assert_eq!(data[0].name, "Test");
    }

    #[test]
    fn test_hot_response_empty_data() {
        let json = r#"{"status":1,"msg":"請求成功","data":[]}"#;
        let resp: HotResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.data.unwrap().len(), 0);
    }

    #[test]
    fn test_hot_response_error_status() {
        let json = r#"{"status":0,"msg":"error"}"#;
        let resp: HotResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 0);
        assert!(resp.data.is_none());
    }

    #[test]
    fn test_detail_response_deserialize() {
        let json = r#"{
            "status": 1,
            "data": {
                "community": {
                    "id": 7329,
                    "name": "台北晶麒",
                    "region": "台北市",
                    "section": "萬華區",
                    "address": "台北市萬華區康定路103號",
                    "age": "10年",
                    "floor": "26層",
                    "house_holds": "687戶",
                    "lat": "25.0387262",
                    "lng": "121.5013407",
                    "build_purpose": "住宅",
                    "base_area": "1124.00",
                    "const_company": "興富發建設股份有限公司",
                    "search_count": "248,275"
                },
                "price": { "items": [] },
                "sale": { "search_type": 1, "total": 0, "rooms": [] }
            }
        }"#;
        let resp: DetailResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 1);
        let data = resp.data.unwrap();
        let community = data.community.unwrap();
        assert_eq!(community.id, 7329);
        assert_eq!(community.name, "台北晶麒");
        assert_eq!(community.region.as_deref(), Some("台北市"));
    }

    #[test]
    fn test_price_record_deserialize() {
        let json = r#"{
            "id": 7238140,
            "date": "115-01-20",
            "address": "康定路103號 | 18樓之16",
            "layout": "1房1廳",
            "build_area": "20.00坪",
            "total_price": "1,490萬元",
            "unit_price": { "price": "74.5", "unit": "萬/坪" },
            "shift_floor": "18樓",
            "total_floor": "26樓",
            "build_purpose_str": "住宅"
        }"#;
        let record: PriceRecord = serde_json::from_str(json).unwrap();
        assert_eq!(record.id, 7238140);
        assert_eq!(record.date, "115-01-20");
        assert_eq!(record.unit_price.price, "74.5");
    }

    #[test]
    fn test_sale_listing_deserialize() {
        let json = r#"{
            "houseid": 20003249,
            "title": "台北晶麒景觀精緻宅",
            "price_v": { "price": "1,925", "unit": "萬" },
            "price_unit": "95.0萬/坪",
            "room": "1房1廳",
            "address": "萬華區-台北晶麒",
            "area_v": { "area": "27.83", "unit": "坪" },
            "floor": "19樓",
            "floor_en": "19F/26F",
            "photo_src": "https://img1.591.com.tw/test.jpg",
            "label": ["含車位", "有陽台"]
        }"#;
        let listing: SaleListing = serde_json::from_str(json).unwrap();
        assert_eq!(listing.houseid, 20003249);
        assert_eq!(listing.price_v.price, "1,925");
        assert_eq!(listing.label.len(), 2);
    }

    #[test]
    fn test_detail_response_not_found() {
        let json = r#"{"status":0,"msg":"[id]參數錯誤"}"#;
        let resp: DetailResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 0);
        assert!(resp.data.is_none());
    }

    #[test]
    fn test_community_serialize_skips_none() {
        let detail = CommunityDetail {
            id: 1,
            name: "Test".to_string(),
            region: Some("台北市".to_string()),
            section: None,
            address: None,
            age: None,
            floor: None,
            house_holds: None,
            lat: None,
            lng: None,
            build_purpose: None,
            base_area: None,
            const_company: None,
            search_count: None,
        };
        let json = serde_json::to_string(&detail).unwrap();
        assert!(json.contains("\"region\""));
        assert!(!json.contains("\"section\""));
    }

    #[test]
    fn test_newhouse_base_info_deserialize() {
        use crate::types::{NewhouseBaseInfoResponse, NewhouseHousing};
        let json = r#"{
            "status": 1,
            "msg": "成功",
            "data": {
                "housing": {
                    "hid": 138145,
                    "build_name": "春風大院",
                    "address": "台北市中山區",
                    "region": "台北市",
                    "regionid": 1,
                    "section": "中山區",
                    "sectionid": 3,
                    "community_id": 5958967,
                    "build_type_name": "預售屋",
                    "purpose_name": "住宅大樓",
                    "price": {"pending": 1, "price": "待定", "unit": ""},
                    "area": {"pending": 0, "area": "16~59", "area_min": "16.00", "unit": "坪"},
                    "layout": {"pending": 0, "layout": "2/3/4", "unit": "房"},
                    "households": "1幢,1棟,118戶住家",
                    "manage_cost": {"pending": 0, "price": "150", "unit": "元/坪/月"},
                    "cover": "https://img.591.com.tw/x.jpg",
                    "shop_name": "南京復興生活圈",
                    "tag": ["近捷運", "低公設", "景觀宅"],
                    "open_sell_time": 202510,
                    "deal_time": {"type": "finished", "date": "2030年下半年", "deal": 0},
                    "build_company": "待定",
                    "sell_company": "巨將創見廣告",
                    "structural_engine": "SRC",
                    "floor": "地上18層",
                    "decorate": "毛胚屋",
                    "park_ratio": "1:1.03",
                    "license": "114建字第0132號",
                    "use_license": "暫無",
                    "browsenum": 655773,
                    "fav_num": 318
                }
            }
        }"#;
        let resp: NewhouseBaseInfoResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 1);
        let h: NewhouseHousing = resp.data.unwrap().housing.unwrap();
        assert_eq!(h.hid, 138145);
        assert_eq!(h.build_name, "春風大院");
        assert_eq!(h.price.pending, 1);
        assert_eq!(h.price.price, "待定");
        assert_eq!(h.area.area, "16~59");
        assert_eq!(h.area.area_min, "16.00");
        assert_eq!(h.layout.layout, "2/3/4");
        assert_eq!(h.tag, vec!["近捷運", "低公設", "景觀宅"]);
        assert_eq!(h.deal_time.kind, "finished");
    }

    #[test]
    fn test_newhouse_base_info_tolerates_null_numerics() {
        // Pinning the null-tolerance contract for the I1 fix:
        // open_sell_time=null and community_id=null both land at 0
        // rather than failing the entire deserialize.
        use crate::types::NewhouseBaseInfoResponse;
        let json = r#"{
            "status": 1,
            "data": {
                "housing": {
                    "hid": 1, "build_name": "x", "address": "x",
                    "regionid": 1, "sectionid": 1,
                    "community_id": null,
                    "build_type_name": "預售屋", "purpose_name": "住宅",
                    "price": {"pending": 1, "price": "待定", "unit": ""},
                    "area": {"pending": 0, "area": "1", "unit": "坪"},
                    "layout": {"pending": 0, "layout": "1", "unit": "房"},
                    "households": "x",
                    "manage_cost": {"pending": 0, "price": "0", "unit": "x"},
                    "cover": "x", "shop_name": "x", "tag": [],
                    "open_sell_time": null,
                    "deal_time": {"type": "x", "date": "x", "deal": 0},
                    "build_company": "x", "sell_company": "x",
                    "structural_engine": "x", "floor": "x", "decorate": "x",
                    "park_ratio": "x", "license": "x", "use_license": "x",
                    "browsenum": 0, "fav_num": 0
                }
            }
        }"#;
        let resp: NewhouseBaseInfoResponse = serde_json::from_str(json).unwrap();
        let h = resp.data.unwrap().housing.unwrap();
        assert_eq!(h.community_id, 0);
        assert_eq!(h.open_sell_time, 0);
    }

    #[test]
    fn test_newhouse_module_info_deserialize() {
        use crate::types::NewhouseModuleInfoResponse;
        let json = r#"{
            "status": 1,
            "data": {
                "layout": {"total": 0, "items": [], "room_group": []},
                "market": {
                    "housing_id": 138145,
                    "housing_name": "春風大院",
                    "community_id": null,
                    "rooms": [{"name": "成交均價", "price": "149.1"}],
                    "items": [],
                    "total": null,
                    "update_date": "04/21"
                },
                "sales": {
                    "data": [{
                        "user_id": 1, "realname": "x", "mobile_v2": "0900",
                        "avatar": "https://x", "tags": []
                    }]
                }
            }
        }"#;
        let resp: NewhouseModuleInfoResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 1);
        let data = resp.data.unwrap();
        let market = data.market.unwrap();
        // null total / null community_id collapse to 0.
        assert_eq!(market.total, 0);
        assert_eq!(market.community_id, 0);
        assert_eq!(market.rooms.len(), 1);
        assert_eq!(data.sales.data.len(), 1);
    }

    #[test]
    fn test_newhouse_photos_deserialize() {
        use crate::types::NewhousePhotosResponse;
        let json = r#"{
            "status": 1,
            "data": [
                {
                    "id": "logo", "name": "封面圖", "build_name": "x", "total": 1,
                    "items": [{
                        "id": 1, "cate": "logo", "cate_name": "封面圖",
                        "src_img": "https://x.jpg"
                    }]
                },
                {
                    "id": "circum", "name": "環境圖", "build_name": "x", "total": 2,
                    "items": [{
                        "id": 2, "cate": "circum", "cate_name": "環境圖",
                        "note": "捷運中山", "src_img": "https://y.jpg"
                    }]
                }
            ]
        }"#;
        let resp: NewhousePhotosResponse = serde_json::from_str(json).unwrap();
        let cats = resp.data.unwrap();
        assert_eq!(cats.len(), 2);
        assert_eq!(cats[0].id, "logo");
        assert_eq!(cats[1].id, "circum");
        assert_eq!(cats[1].items[0].note, "捷運中山");
    }

    #[test]
    fn test_newhouse_surrounding_deserialize() {
        use crate::types::NewhouseSurroundingResponse;
        let json = r#"{
            "status": 1,
            "data": {
                "facility": {
                    "total": null,
                    "traffic": [{
                        "name": "中山國中",
                        "distance": 876,
                        "distance_text": "876公尺",
                        "lat": 25.0521,
                        "lng": 121.5488,
                        "sub_type": "subway_station"
                    }],
                    "education": [],
                    "life": []
                },
                "housing": {
                    "hid": 1, "build_name": "x", "address": "x",
                    "map": {"pending": 0, "lat": "25.05", "lng": "121.54"},
                    "reception_map": {"pending": 0, "lat": "25.05", "lng": "121.54"}
                }
            }
        }"#;
        let resp: NewhouseSurroundingResponse = serde_json::from_str(json).unwrap();
        let s = resp.data.unwrap();
        // facility.total: null lands at 0 via I1 fix.
        assert_eq!(s.facility.total, 0);
        // POIs use raw f64 lat/lng on this endpoint (different from housing.map).
        assert_eq!(s.facility.traffic[0].sub_type, "subway_station");
        // Project map uses string lat/lng (591 wire-asymmetry).
        assert_eq!(s.housing.map.lat, "25.05");
    }

    #[test]
    fn test_newhouse_nearby_market_deserialize() {
        use crate::types::NewhouseNearbyMarketResponse;
        let json = r#"{
            "status": 1,
            "data": {
                "community_items": [{
                    "community_id": 5880697, "community_name": "南京阿曼",
                    "deal_count": 67,
                    "price": {"content": "142.7", "unit": "萬/坪"},
                    "community_image": "https://x",
                    "build_type": 1, "build_type_str": "預售屋",
                    "build_purpose": "住宅",
                    "layout": {"content": "1、2", "unit": "房"},
                    "area": {"content": "13~25", "unit": "坪"},
                    "age": null,
                    "distance": 788
                }],
                "business_items": [{
                    "id": 101, "shop_id": 101, "name": "南京復興生活圈",
                    "price_unit": "165.0", "unit": "萬/坪"
                }]
            }
        }"#;
        let resp: NewhouseNearbyMarketResponse = serde_json::from_str(json).unwrap();
        let m = resp.data.unwrap();
        assert_eq!(m.community_items.len(), 1);
        // age: null collapses to 0 via I1 fix.
        assert_eq!(m.community_items[0].age, 0);
        assert_eq!(m.community_items[0].deal_count, 67);
        assert_eq!(m.business_items.len(), 1);
    }

    #[test]
    fn test_newhouse_price_list_deserialize() {
        use crate::types::NewhousePriceListResponse;
        let json = r#"{
            "status": 1,
            "data": {
                "housing_id": 138145, "housing_name": "春風大院",
                "community_id": null,
                "rooms": [{"name": "成交均價", "price": ""}],
                "has_sale_ctrl": 1,
                "sale_ctrl_info": {
                    "update_count": 3,
                    "price": {
                        "id": 1, "address": "A棟7樓09戶", "room": "2房",
                        "unit_price": {"price": "163.0", "unit": "萬"}
                    }
                },
                "items": [],
                "total": null,
                "update_date": "04/21"
            }
        }"#;
        let resp: NewhousePriceListResponse = serde_json::from_str(json).unwrap();
        let p = resp.data.unwrap();
        // null community_id and total collapse to 0 via I1 fix.
        assert_eq!(p.community_id, 0);
        assert_eq!(p.total, 0);
        let s = p.sale_ctrl_info.unwrap();
        assert_eq!(s.price.address, "A棟7樓09戶");
    }

    #[test]
    fn test_coordinate_area_response_hit_shape() {
        // Success path: status=1, data = { area: { ... } }.
        use crate::types::{CoordArea, CoordResponse};
        let json = r#"{
            "status":1, "msg":"",
            "data":{"area":{"region_id":1,"region_name":"台北市","section_id":7,"section_name":"信義區"}}
        }"#;
        let resp: CoordResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 1);
        let area_v = resp.data.get("area").cloned().unwrap();
        let area: CoordArea = serde_json::from_value(area_v).unwrap();
        assert_eq!(area.region_id, 1);
        assert_eq!(area.region_name, "台北市");
        assert_eq!(area.section_id, 7);
        assert_eq!(area.section_name, "信義區");
    }

    #[test]
    fn test_coordinate_area_response_miss_shape() {
        // Off-Taiwan path: status=0, data = [] (NOT an object).
        // Locks the wire-shape polymorphism — typed deserialize via
        // `data: serde_json::Value` survives both shapes.
        use crate::types::CoordResponse;
        let json = r#"{"status":0,"msg":"坐标不在台湾范围内","data":[]}"#;
        let resp: CoordResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 0);
        assert!(resp.msg.contains("台湾"));
        // data is the empty array — Value variant, not a parse error.
        assert!(resp.data.is_array());
    }

    #[test]
    fn test_coordinate_area_response_unknown_status_deserializes() {
        // Pins the third arm of the status-handling matrix: any
        // status other than 0 or 1 should still deserialize cleanly
        // (the dispatch happens in coordinate_area, not in serde) so
        // that the production code can format msg into the error.
        use crate::types::CoordResponse;
        let json = r#"{"status":2,"msg":"rate limited","data":null}"#;
        let resp: CoordResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 2);
        assert_eq!(resp.msg, "rate limited");
        assert!(resp.data.is_null());
    }

    #[test]
    fn test_rent_detail_response_deserialize() {
        // Compact happy-path fixture — all the camelCase wire keys
        // (priceUnit, headInfo, regionId, etc.) routed through
        // #[serde(rename_all = "camelCase")] on the structs.
        use crate::types::RentDetailResponse;
        let json = r#"{
            "status": 1,
            "msg": "",
            "data": {
                "title": "中山套房",
                "price": "17,800",
                "priceUnit": "元/月",
                "deposit": "押金面議",
                "headInfo": "17,800元/月",
                "address": {
                    "data": "中山區雙城街50號",
                    "value": "中山區雙城街50號 中山區雙城街50號",
                    "lat": "25.0669894",
                    "lng": "121.5235794"
                },
                "regionId": 1,
                "sectionId": 3,
                "kind": 2,
                "status": "open",
                "info": [
                    {"name": "類型", "value": "獨立套房", "key": "kind"},
                    {"name": "使用坪數", "value": "10.2坪", "key": "area"}
                ],
                "cost": {
                    "title": "費用詳情",
                    "active": 1,
                    "data": [
                        {"name": "押金", "value": "面議", "key": "deposit"}
                    ]
                },
                "houseInfo": {"active": 1, "data": []},
                "preference": {"active": 1, "data": []},
                "service": {
                    "title": "提供設備",
                    "active": 1,
                    "facility": [
                        {"key": "fridge", "active": 1, "name": "冰箱"},
                        {"key": "tv", "active": 0, "name": "電視"}
                    ],
                    "notice": [
                        {"key": "leaseTime", "name": "最短一年"},
                        {"key": "pet", "name": "不可養寵物"}
                    ]
                },
                "surround": {
                    "title": "周邊配套", "key": "surround",
                    "address": "中山區雙城街50號",
                    "lat": "25.0669894", "lng": "121.5235794",
                    "data": [{"name": "交通", "key": "traffic", "children": [
                        {"type": "subway", "name": "中山國小站", "distance": 558, "distanceTxt": "距房屋約558公尺"}
                    ]}]
                },
                "tags": [{"id": 16, "value": "新上架"}],
                "publish": {
                    "id": 2, "name": "新發佈", "key": "new",
                    "postTime": "13小時前", "updateTime": "19分鐘內"
                },
                "remark": {
                    "title": "屋況介紹",
                    "key": "remark",
                    "active": 1,
                    "content": "屋況良好"
                },
                "linkInfo": {
                    "name": "程先生", "role": 3, "roleName": "仲介",
                    "mobile": "0922-168-660", "phone": "",
                    "imName": "程先生", "imUid": 780619, "uid": 780619,
                    "shopId": 4929, "isAgent": 0, "isGoldAgent": 0,
                    "certificateStatus": 2, "rentNum": 5, "saleNum": 0
                }
            }
        }"#;
        let resp: RentDetailResponse = serde_json::from_str(json).unwrap();
        let d = resp.data.unwrap();
        assert_eq!(d.title, "中山套房");
        assert_eq!(d.price, "17,800");
        assert_eq!(d.price_unit, "元/月");
        assert_eq!(d.address.lat, "25.0669894");
        assert_eq!(d.region_id, 1);
        assert_eq!(d.kind, 2);
        assert_eq!(d.info.len(), 2);
        assert_eq!(d.info[0].key, "kind");
        assert_eq!(d.cost.data[0].value, "面議");
        // service has the new typed shape (facility + notice).
        assert_eq!(d.service.facility.len(), 2);
        assert_eq!(d.service.facility[0].key, "fridge");
        assert_eq!(d.service.facility[0].active, 1);
        assert_eq!(d.service.notice.len(), 2);
        assert_eq!(d.service.notice[0].key, "leaseTime");
        assert_eq!(d.surround.data[0].children[0].kind, "subway");
        assert_eq!(
            d.surround.data[0].children[0].distance_txt,
            "距房屋約558公尺"
        );
        assert_eq!(d.tags[0].id, 16);
        assert_eq!(d.publish.post_time, "13小時前");
        // link_info is now a polymorphic Value — query via accessor trait.
        use crate::types::RentLinkInfoExt;
        assert_eq!(d.link_info.link_str("roleName"), Some("仲介"));
        assert_eq!(d.link_info.link_str("mobile"), Some("0922-168-660"));
        assert_eq!(d.link_info.link_u64("shopId"), Some(4929));
    }

    #[test]
    fn test_rent_link_info_polymorphism() {
        // 591 returns linkInfo in two shapes interchangeably: named-
        // field object OR array of {key, value} pairs. Both must yield
        // identical accessor results — verified live 2026-04-30.
        use crate::types::{RentLinkInfo, RentLinkInfoExt};

        let mapped: RentLinkInfo = serde_json::from_str(
            r#"{"name":"程先生","role":3,"roleName":"仲介","mobile":"0922","shopId":4929}"#,
        )
        .unwrap();
        assert_eq!(mapped.link_str("name"), Some("程先生"));
        assert_eq!(mapped.link_u64("shopId"), Some(4929));
        assert_eq!(mapped.link_u32("role"), Some(3));

        let pairs: RentLinkInfo = serde_json::from_str(
            r#"[{"key":"name","value":"程先生"},{"key":"role","value":3},{"key":"shopId","value":4929}]"#,
        )
        .unwrap();
        assert_eq!(pairs.link_str("name"), Some("程先生"));
        assert_eq!(pairs.link_u64("shopId"), Some(4929));
        assert_eq!(pairs.link_u32("role"), Some(3));
    }

    #[test]
    fn test_rent_photos_response_deserialize() {
        use crate::types::RentPhotosResponse;
        let json = r#"{
            "status": 1,
            "msg": "",
            "data": {
                "list": [{
                    "key": "picture",
                    "items": [{
                        "photoId": 476004995,
                        "photo": "https://img/big.jpg",
                        "origPhoto": "https://img/orig.jpg",
                        "thumbPhoto": "https://img/thumb.jpg",
                        "isCover": 1,
                        "purpose": 10,
                        "note": "",
                        "type": 3
                    }]
                }]
            }
        }"#;
        let resp: RentPhotosResponse = serde_json::from_str(json).unwrap();
        let groups = resp.data.unwrap().list;
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].key, "picture");
        assert_eq!(groups[0].items[0].photo_id, 476004995);
        assert_eq!(groups[0].items[0].is_cover, 1);
    }

    #[test]
    fn test_sale_detail_response_deserialize() {
        // Compact fixture exercising the wire's stringly-typed numerics
        // (region_id, room, lat, etc. all arrive as strings).
        use crate::types::SaleDetailResponse;
        let json = r#"{
            "status": 1,
            "msg": null,
            "data": {
                "id": "S19599759",
                "title": "三重透天",
                "price": "1,988萬元",
                "price_value": "1988",
                "unitprice": "86.02萬/坪",
                "area": "23.111坪",
                "area_value": "23.111",
                "layout": "3房2廳3衛",
                "room": "3",
                "hall": "2",
                "toilet": "3",
                "kind": "住宅",
                "kind_id": "9",
                "region": "新北市",
                "region_id": "3",
                "section": "三重區",
                "section_id": "43",
                "addr": "",
                "lat": "25.0713174",
                "lng": "121.4833166",
                "age": "56年",
                "houseage": "56",
                "shape": "透天厝",
                "fitment": "中檔裝潢",
                "direction": "東南",
                "lift": "0",
                "parking": "無",
                "mainarea": "20.69坪",
                "managefee": "無",
                "posttime": "1769328229",
                "community": "",
                "community_id": "",
                "linkman": "值班人員",
                "mobile": "0965-109-089",
                "telephone": "02-85229096",
                "email": "x@x.com",
                "identity": "仲介",
                "company_name": "有巢氏房屋",
                "certificate_type": "Middleman"
            }
        }"#;
        let resp: SaleDetailResponse = serde_json::from_str(json).unwrap();
        let d = resp.data.unwrap();
        assert_eq!(d.id, "S19599759");
        assert_eq!(d.price, "1,988萬元");
        assert_eq!(d.price_value, "1988");
        assert_eq!(d.region_id, "3");
        assert_eq!(d.layout, "3房2廳3衛");
        assert_eq!(d.identity, "仲介");
        assert_eq!(d.lat, "25.0713174");
        // Numeric parses cleanly from wire-string.
        assert_eq!(d.lat.parse::<f64>().unwrap(), 25.0713174);
        assert_eq!(d.region_id.parse::<u32>().unwrap(), 3);
    }

    #[test]
    fn test_sale_similar_wares_response_deserialize() {
        use crate::types::SaleSimilarWaresResponse;
        let json = r#"{
            "status": 1,
            "msg": "ok",
            "data": [{
                "type": "2",
                "post_id": "19979734",
                "title": "透天厝近三重",
                "price": "1980",
                "area": "20.808",
                "kind": "9",
                "is_vip": "0",
                "is_refresh": "0",
                "is_combine": "1",
                "room": "6房6衛",
                "section_name": "三重區",
                "photo_url": "https://img1.591.com.tw/x.jpg",
                "tag": "",
                "similar_type": ""
            }]
        }"#;
        let resp: SaleSimilarWaresResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.data.len(), 1);
        assert_eq!(resp.data[0].post_id, "19979734");
        assert_eq!(resp.data[0].kind_type, "2");
        assert_eq!(resp.data[0].section_name, "三重區");
        assert_eq!(resp.data[0].is_combine, "1");
    }

    #[test]
    fn test_high_value_search_response_deserialize() {
        use crate::types::HighValueSearchResponse;
        let json = r#"{
            "status": 1,
            "msg": "",
            "data": [{
                "type": 2,
                "post_id": 19916382,
                "title": "郵政新村好3房",
                "price": 3088,
                "area": 27.1,
                "kind": 9,
                "room": 3,
                "hall": 2,
                "toilet": 1,
                "region_name": "台北市",
                "section_name": "大安區",
                "street_name": "建國南路一段",
                "unit_price": 114.1,
                "cover": "https://img1.591.com.tw/x.jpg",
                "unit": "萬",
                "area_unit": "坪",
                "layout": "3房2廳1衛"
            }]
        }"#;
        let resp: HighValueSearchResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 1);
        assert_eq!(resp.data.len(), 1);
        let l = &resp.data[0];
        assert_eq!(l.post_id, 19916382);
        assert_eq!(l.title, "郵政新村好3房");
        assert_eq!(l.price, 3088);
        assert_eq!(l.region_name, "台北市");
    }

    #[test]
    fn test_high_value_search_empty_data() {
        // Some kinds (e.g. kind=2) return status=1 with data:[] — locked
        // here so a future "panic on empty data" regression is caught.
        use crate::types::HighValueSearchResponse;
        let json = r#"{"status":1,"msg":"","data":[]}"#;
        let resp: HighValueSearchResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, 1);
        assert!(resp.data.is_empty());
    }

    #[test]
    fn test_high_value_params_serialize_omits_empty_arrays_correctly() {
        use crate::types::HighValueParams;
        // for_region defaults: empty arrays should still be serialized
        // (591 expects them present even when empty), kind_type renamed
        // to `type`. Verifying the wire-shape contract.
        let params = HighValueParams::for_region(1);
        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("\"region_id\":1"));
        assert!(json.contains("\"kind\":9"));
        // type is a Rust keyword — verify the rename worked.
        assert!(json.contains("\"type\":2"));
        assert!(json.contains("\"section_id\":[]"));
        assert!(json.contains("\"shape\":[]"));
    }

    #[test]
    fn test_regions_list() {
        assert_eq!(REGIONS.len(), 22);
        assert_eq!(REGIONS[0].id, 1);
        assert_eq!(REGIONS[0].name, "台北市");
        assert_eq!(REGIONS[5].id, 6);
        assert_eq!(REGIONS[5].name, "高雄市");
        // All IDs unique and sequential
        for (i, r) in REGIONS.iter().enumerate() {
            assert_eq!(r.id as usize, i + 1);
        }
    }

    #[tokio::test]
    async fn test_hot_live() {
        let client = Client591::new().unwrap();
        let result = client.hot(1, 5).await;
        assert!(result.is_ok(), "hot() failed: {:?}", result);
        let communities = result.unwrap();
        assert!(!communities.is_empty());
        assert!(communities.len() <= 5);
        for c in &communities {
            assert!(!c.id.is_empty());
            assert!(!c.name.is_empty());
        }
    }

    #[tokio::test]
    async fn test_community_live() {
        let client = Client591::new().unwrap();
        let result = client.community(7329).await;
        assert!(result.is_ok(), "community() failed: {:?}", result);
        let detail = result.unwrap().unwrap();
        assert_eq!(detail.id, 7329);
        assert!(detail.region.is_some());
        assert!(detail.address.is_some());
    }

    #[tokio::test]
    async fn test_price_history_live() {
        let client = Client591::new().unwrap();
        let result = client.price_history(7329, 5).await;
        assert!(result.is_ok(), "price_history() failed: {:?}", result);
        let records = result.unwrap();
        assert!(records.len() <= 5);
        if !records.is_empty() {
            assert!(!records[0].date.is_empty());
            assert!(!records[0].layout.is_empty());
            assert!(!records[0].total_price.is_empty());
        }
    }

    #[tokio::test]
    async fn test_sales_live() {
        let client = Client591::new().unwrap();
        let result = client.sales(7329, 5).await;
        assert!(result.is_ok(), "sales() failed: {:?}", result);
        let (total, listings) = result.unwrap();
        assert!(total > 0, "expected sale listings for 台北晶麒");
        assert!(listings.len() <= 5);
        if !listings.is_empty() {
            assert!(!listings[0].title.is_empty());
            assert!(!listings[0].price_v.price.is_empty());
        }
    }

    #[tokio::test]
    async fn test_community_not_found() {
        let client = Client591::new().unwrap();
        let result = client.community(0).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }
}