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
use serde::{Deserialize, Deserializer, Serialize};

/// 591 returns some "really an integer" fields as either a JSON
/// integer or a JSON string depending on the listing. This helper
/// accepts both forms and lands on `u32`. Used for `SaleHouseListing::
/// photo_num` (string `"11"` or int `19` in the wild).
fn u32_string_or_int<'de, D: Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
    let v = serde_json::Value::deserialize(d)?;
    match v {
        serde_json::Value::String(s) => s.parse().map_err(serde::de::Error::custom),
        serde_json::Value::Number(n) => n
            .as_u64()
            .and_then(|n| u32::try_from(n).ok())
            .ok_or_else(|| serde::de::Error::custom(format!("u32 out of range: {n}"))),
        other => Err(serde::de::Error::custom(format!(
            "expected string or integer for u32, got {other:?}"
        ))),
    }
}

/// A hot community listing (from `/api/community/rentHot`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Community {
    pub id: String,
    pub name: String,
}

/// Detailed info for a community (from `/api/community/detail`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommunityDetail {
    pub id: u64,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub section: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub age: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub floor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub house_holds: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lat: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lng: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub build_purpose: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_area: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub const_company: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_count: Option<String>,
}

/// A nearby community (from `/api/community/nearby`).
///
/// 591 returns up to ~5 communities geographically close to the queried
/// `id`, each with sale-side stats (`min_price`, `sale_num`) and a
/// distance string. Distinct from [`Community`] (which is just
/// `{id, name}` from the rent-hot list) and [`CommunityDetail`] (which
/// is the full info page for a single community).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NearbyCommunity {
    pub id: u64,
    pub name: String,
    /// Numeric region id (1 = Taipei, etc.). See `REGIONS`.
    pub region_id: u32,
    /// Numeric section id (district within a region).
    pub section_id: u32,
    /// Display region (e.g. `"台北市"`).
    pub region: String,
    /// Display section (e.g. `"信義區"`).
    pub section: String,
    /// Average sale price per ping (e.g. `{ price: "150.66", unit: "萬/坪" }`).
    pub price_unit: PriceValue,
    pub address: String,
    pub full_address: String,
    /// Age string, e.g. `"5年屋齡"`. Empty for buildings 591 hasn't
    /// dated.
    pub age: String,
    /// Total household count, e.g. `"282戶"`. May be empty.
    pub house_holds: String,
    /// `"住宅"` / `"華廈"` / `"商用"` etc.
    pub build_purpose: String,
    /// Distance from the queried community, e.g. `"距離126公尺"`.
    pub distance: String,
    /// Number of for-sale listings currently on this community.
    pub sale_num: u32,
    /// Minimum sale price among `sale_num` listings, in 萬元 (10,000 NTD).
    /// Typically `0` when `sale_num == 0` (the live test asserts the
    /// forward direction `sale_num > 0 ⇒ min_price > 0`; the reverse
    /// is documented but not empirically verified across all cases).
    pub min_price: u64,
}

/// A single transaction price record (from community detail `price.items`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceRecord {
    pub id: u64,
    /// ROC date string, e.g. "115-01-20"
    pub date: String,
    pub address: String,
    pub layout: String,
    pub build_area: String,
    pub total_price: String,
    pub unit_price: PriceValue,
    pub shift_floor: String,
    pub total_floor: String,
    pub build_purpose_str: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceValue {
    pub price: String,
    pub unit: String,
}

/// A sale listing near a community (from community detail `sale.rooms[].items[]`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SaleListing {
    pub houseid: u64,
    pub title: String,
    pub price_v: PriceValue,
    pub price_unit: String,
    pub room: String,
    pub address: String,
    pub area_v: AreaValue,
    pub floor: String,
    pub floor_en: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub photo_src: Option<String>,
    pub label: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AreaValue {
    pub area: String,
    pub unit: String,
}

/// A rental listing from `bff-house.591.com.tw/v3/web/rent/list` (pure HTTP).
///
/// Wire fields are mapped via `From<RentListItem>`. `price` is the
/// formatted display string (`"17,500"`, with comma); `area` carries
/// the unit suffix (`"9坪"`); `post_time` is a Chinese relative-time
/// string (`"7小時內更新"`), not an ISO date.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchListing {
    pub post_id: u64,
    pub title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price_unit: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub area: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub room: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub floor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub photo_list: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_time: Option<String>,
}

/// Parameters for the rental search.
#[derive(Debug, Clone, Default)]
pub struct SearchParams {
    /// Region ID (1 = Taipei City). See `REGIONS` for full list.
    pub region_id: u32,
    /// House kind: 0=all, 1=整層住家, 2=獨立套房, 3=分租套房, 8=雅房, 24=車位
    pub kind: Option<u32>,
    /// Maximum monthly rent (NTD)
    pub price_max: Option<u32>,
    /// Minimum monthly rent (NTD)
    pub price_min: Option<u32>,
    /// Sort field: "posttime" (default) or "price"
    pub order: Option<String>,
    /// Max results to return (per page)
    pub limit: usize,
    /// Pagination offset (0, 30, 60, …). Used by `crawl` to walk through pages.
    pub first_row: usize,
}

/// Options controlling the pagination behaviour of [`crate::Client591::rent_crawl`].
#[derive(Debug, Clone)]
pub struct CrawlOptions {
    /// Maximum pages to fetch. 0 = no limit.
    pub max_pages: usize,
    /// Milliseconds to wait between pages.
    pub delay_ms: u64,
    /// Retry attempts per page on failure (with 2s fixed backoff between retries).
    pub retries: u32,
    /// Starting page index (for resume). 0 = start from beginning.
    pub start_page: usize,
}

impl Default for CrawlOptions {
    fn default() -> Self {
        Self {
            max_pages: 0,
            delay_ms: 1000,
            retries: 3,
            start_page: 0,
        }
    }
}

/// A region with its ID and name.
#[derive(Debug, Clone, Serialize)]
pub struct Region {
    pub id: u32,
    pub name: &'static str,
}

// ---------------------------------------------------------------------------
// BFF endpoints — sale_list / newhouse_list / community_rank
// ---------------------------------------------------------------------------

/// A single sale listing from `bff-house.591/v1/web/sale/list`.
///
/// 591's BFF response carries 60+ fields per listing; this type
/// surfaces the user-facing subset (identity / location / price /
/// area / display strings) and skips ad/internal flags.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SaleHouseListing {
    pub houseid: u64,
    pub title: String,
    pub address: String,
    /// Area in 坪 (Taiwanese unit, ~3.3 m²).
    pub area: f64,
    /// Total sale price in 萬元 (10,000 NTD).
    pub price: u64,
    /// Pre-formatted price string (e.g. `"1,798"`).
    pub showprice: String,
    /// Per-坪 price (e.g. `"119.71萬/坪"`).
    pub unit_price: String,
    /// Floor / total floors (e.g. `"5F/12F"`).
    pub floor: String,
    /// Room / 廳 / 衛 layout (e.g. `"2房1廳1衛"`).
    pub room: String,
    /// `"住宅"` / `"華廈"` / `"商用"` / etc.
    pub kind_name: String,
    /// `"電梯大樓"` / `"公寓"` / etc.
    pub shape_name: String,
    pub region_id: u32,
    pub region_name: String,
    pub section_id: u32,
    pub section_name: String,
    /// Numeric age in years.
    pub houseage: u32,
    /// Human-readable age (`"1年"`).
    pub showhouseage: String,
    /// Unix seconds.
    pub posttime: i64,
    /// View count.
    pub browsenum: u64,
    pub photo_url: String,
    /// Number of photos for the listing. JSON key `"photoNum"`. 591
    /// returns this as **either** a JSON string (`"11"`) or a raw
    /// integer (`19`); we accept both forms via `u32_string_or_int`.
    #[serde(rename = "photoNum", deserialize_with = "u32_string_or_int")]
    pub photo_num: u32,
    /// Owner's display name (`"屋主金小姐"`).
    pub nick_name: String,
    /// Listing tags (often empty).
    #[serde(default)]
    pub tag: Vec<String>,
    /// Community/building name. Falls back to `"依現場名稱"` placeholder
    /// for owner-direct listings without a registered community.
    pub community_name: String,
    /// 591 community detail link (empty when no registered community).
    #[serde(default)]
    pub community_link: String,
    /// Number of for-sale listings on this community. 591 omits this
    /// field entirely for owner-direct listings without a registered
    /// community — `#[serde(default)]` lands those at 0.
    #[serde(default)]
    pub community_sale_num: u32,
    /// "Last refreshed" indicator. 591 returns this as **either**:
    /// - a Chinese relative-time string (`"2小時前"`, `"剛剛"`), or
    /// - a Unix timestamp integer (`1777397463`)
    ///
    /// depending on the listing's age class. Exposed as raw
    /// `serde_json::Value` so callers can match on the discriminant
    /// rather than fight a custom deserializer. For "when was this
    /// posted, full stop" use the stable `posttime` field.
    pub refreshtime: serde_json::Value,
}

/// One page of sale listings from `/v1/web/sale/list`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SaleHousePage {
    /// Total matching listings across all pages.
    pub total: u32,
    /// 0-indexed first row of this page.
    pub first_row: usize,
    pub houses: Vec<SaleHouseListing>,
}

/// A single new-construction project from `bff-newhouse.591/v1/list-search`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseProject {
    /// 建案 ID — 591's "house" id for newhouse projects.
    pub hid: u64,
    /// Linked community ID (the post-handover community in the
    /// rent / sale catalog), if 591 has a record.
    pub community_id: u64,
    /// 建案名稱.
    pub build_name: String,
    /// Full address (`"台北市松山區八德路三段201號"`).
    pub address: String,
    /// Area range string (`"20~26坪"`).
    pub area: String,
    /// Room layout summary (`"二房(20、26坪)"`).
    pub room: String,
    /// Price string — usually a single number (e.g. `"138"`); 591
    /// formats this without a thousands separator for newhouse.
    pub price: String,
    /// Unit suffix — typically `"萬/坪"`.
    pub price_unit: String,
    /// `"住商用"` / `"住宅"` / etc.
    pub purpose_str: String,
    pub region: String,
    #[serde(rename = "regionid")]
    pub region_id: u32,
    pub section: String,
    #[serde(rename = "sectionid")]
    pub section_id: u32,
    /// Nearest landmark / 商圈 (`"台北小巨蛋生活圈"`).
    pub shop_name: String,
    /// Cover photo URL.
    pub cover: String,
    /// Sales-office phone.
    pub phone: String,
    pub phone_ext: String,
    /// Marketing tags (`["近捷運", "明星學區", "近公園", "低首付"]`).
    #[serde(default)]
    pub tag: Vec<String>,
    /// `"2026-04-28"`.
    pub updatetime: String,
    /// Whether the project has a video tour.
    pub is_video: u8,
    /// Visibility tier text (`"區域VIP"` / etc); empty for non-paid.
    pub group_type_txt: String,
}

/// One page of newhouse projects from `/v1/list-search`.
///
/// Constructed from a wire response that mixes empty placeholder slots
/// (single-key objects from 591's ad-injection layer) into the items
/// array. The adapter filters those out — `items` here only contains
/// successfully-parsed `NewhouseProject` entries.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhousePage {
    /// Total projects matching the filter.
    pub total: u32,
    /// Currently-online projects.
    pub online_total: u32,
    /// 1-indexed page number.
    pub page: u32,
    pub per_page: u32,
    pub total_page: u32,
    pub items: Vec<NewhouseProject>,
}

/// 591's `photo_src` shape — appears across rank / various BFF
/// endpoints as an object with the actual URL inside.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhotoSrc {
    /// Image URL.
    pub src: String,
    /// 591-internal type discriminant.
    #[serde(default, rename = "type")]
    pub kind: u32,
}

/// One entry in a community-rank slot. Used for both `price_data`
/// (price-ranked) and `sale_data` (sale-activity-ranked) buckets.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommunityRankItem {
    pub cid: u64,
    pub name: String,
    pub address: String,
    /// Cover photo (object form: `{src, type}`).
    pub photo_src: PhotoSrc,
    /// Average per-坪 price.
    pub price: PriceValue,
    /// Numeric metric used for the ranking — depends on slot:
    /// in `price_data` this is the priced-by metric (some kind of
    /// listings-volume figure); in `sale_data` it tracks paid-rank
    /// activity. Value as observed: `1059` for the top entry.
    pub price_num: u64,
    /// Number of for-sale listings in this community.
    pub sale_num: u32,
    /// Nearest landmark / station / 商圈.
    pub shop_name: String,
}

/// Community ranks for a region from `/v1/community/community-rank`.
///
/// 591 returns two parallel rankings of the same shape: `price_data`
/// (top 10 by price-related metric) and `sale_data` (top 10 by sale
/// activity). Both share the same `time` snapshot date.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommunityRanks {
    pub price_data: Vec<CommunityRankItem>,
    pub sale_data: Vec<CommunityRankItem>,
    /// Snapshot date (`"2026-04-29"`).
    pub time: String,
}

// ---------------------------------------------------------------------------
// /v3/web/rent/list — pure-HTTP rent search (used by Client591::rent_search)
// ---------------------------------------------------------------------------

/// Top-level wrapper for `bff-house.591.com.tw/v3/web/rent/list`.
///
/// `status` is a JSON integer (`1` for success), `total` is a JSON
/// string (`"3728"`) — verified live 2026-04-30. The wire `firstRow`
/// field is intentionally not modeled because 591 echoes 0 even on
/// later pages; the caller tracks its own offset.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RentListResponse {
    pub status: i32,
    pub data: Option<RentListData>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RentListData {
    /// Total matching listings. 591 currently sends this as a JSON
    /// string (`"3728"`), but `u32_string_or_int_default` accepts the
    /// int form too — forward-compat for a server-side type flip and
    /// loud-fail on garbage strings (rather than the old silent zero).
    #[serde(default, deserialize_with = "u32_string_or_int_default")]
    pub total: u32,
    pub items: Vec<RentListItem>,
}

/// A single rental listing as returned by `/v3/web/rent/list`.
///
/// Wire shape — fields are mapped to the public [`SearchListing`]
/// via `From<RentListItem>`. Most secondary fields (browse_count,
/// surrounding, fitment_name, etc.) are dropped intentionally —
/// they're not part of `SearchListing`'s public contract.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RentListItem {
    pub id: u64,
    pub title: String,
    /// Display price (e.g. `"17,500"` — note the comma).
    #[serde(default)]
    pub price: Option<String>,
    /// Price unit (`"元/月"`).
    #[serde(default)]
    pub price_unit: Option<String>,
    #[serde(default)]
    pub address: Option<String>,
    /// Area display string (`"9坪"`). Numeric `area` is present
    /// too but we keep the existing `SearchListing.area: String`
    /// contract for compatibility.
    #[serde(default)]
    pub area_name: Option<String>,
    #[serde(default)]
    pub kind_name: Option<String>,
    /// Layout string. Often empty for 套房 (`""`); populated
    /// for whole-floor rentals (`"2房1廳"`).
    #[serde(default, rename = "layoutStr")]
    pub layout_str: Option<String>,
    #[serde(default)]
    pub floor_name: Option<String>,
    #[serde(default, rename = "photoList")]
    pub photo_list: Option<Vec<String>>,
    #[serde(default)]
    pub tags: Option<Vec<String>>,
    /// Relative-time string ("7小時內更新", "剛剛更新"). Used
    /// as the closest analog to `SearchListing.post_time`.
    #[serde(default)]
    pub refresh_time: Option<String>,
}

impl From<RentListItem> for SearchListing {
    fn from(v: RentListItem) -> Self {
        // Empty strings / empty Vecs collapse to None to match the
        // semantics the existing parse_listing helper used and the
        // `#[serde(skip_serializing_if = "Option::is_none")]` output
        // contract on SearchListing.
        let room = v.layout_str.filter(|s| !s.is_empty());
        let photo_list = v.photo_list.filter(|v| !v.is_empty());
        let tags = v.tags.filter(|v| !v.is_empty());
        SearchListing {
            post_id: v.id,
            title: v.title,
            price: v.price,
            price_unit: v.price_unit,
            address: v.address,
            area: v.area_name,
            kind_name: v.kind_name,
            room,
            floor: v.floor_name,
            photo_list,
            tags,
            post_time: v.refresh_time,
        }
    }
}

// ---------------------------------------------------------------------------
// Newhouse detail family (bff-newhouse.591.com.tw/v1/detail/*, /v1/price/list)
// ---------------------------------------------------------------------------

/// A pending-aware monetary or numeric field. 591 wraps "value or
/// TBD" data in this shape: when `pending: 1`, `price` carries the
/// placeholder string `"待定"` (TBD) and `unit` is empty; when
/// `pending: 0`, both fields carry real values.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingPrice {
    pub pending: u8,
    pub price: String,
    pub unit: String,
}

/// Like [`PendingPrice`] but for area ranges. The wire shape adds
/// `area_min` for the lower bound when `pending: 0`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingArea {
    pub pending: u8,
    /// Range string (e.g. `"16~59"`).
    pub area: String,
    /// Lower-bound value (e.g. `"16.00"`). Empty/absent when pending.
    #[serde(default)]
    pub area_min: String,
    pub unit: String,
}

/// Like [`PendingPrice`] but the value field is named `layout`
/// (e.g. `"2/3/4"` for a project offering 2-, 3-, and 4-room units).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingRoom {
    pub pending: u8,
    pub layout: String,
    pub unit: String,
}

/// Newhouse handover-date metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DealTime {
    /// `"finished"` (project complete) or `"unfinished"` (still selling).
    #[serde(rename = "type")]
    pub kind: String,
    /// Display string (e.g. `"2030年下半年"`).
    pub date: String,
    /// Sales-progress flag.
    pub deal: u8,
}

/// Newhouse project detail (curated subset of `/v1/detail/base-info`'s
/// `data.housing` block — the wire shape carries 80+ fields, this
/// surfaces the ~25 most useful for project-shopping workflows).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseHousing {
    /// 591 housing/project ID. Same value as the URL `id`/`hid` param.
    pub hid: u64,
    pub build_name: String,
    pub address: String,
    /// Display region (e.g. `"台北市"`).
    #[serde(default)]
    pub region: Option<String>,
    pub regionid: u32,
    /// Display section (e.g. `"中山區"`).
    #[serde(default)]
    pub section: Option<String>,
    pub sectionid: u32,
    /// Linked community ID once the project is delivered (0 until then).
    /// 591 sometimes serializes this as `null` for unlinked pre-sales —
    /// the deserializer collapses null/missing/string forms to 0.
    #[serde(default, deserialize_with = "u64_string_or_int_default")]
    pub community_id: u64,
    /// `"預售屋"` (pre-sale), `"新成屋"` (new), `"中古屋"` (resale).
    pub build_type_name: String,
    /// `"住宅大樓"`, `"住商混合"`, etc.
    pub purpose_name: String,
    pub price: PendingPrice,
    pub area: PendingArea,
    /// Project's offered room layouts (e.g. `"2/3/4"`).
    pub layout: PendingRoom,
    /// Free-form description (`"1幢,1棟,118戶住家"`).
    pub households: String,
    /// Per-坪/月 management fee.
    pub manage_cost: PendingPrice,
    /// Cover image URL.
    pub cover: String,
    /// Nearest landmark / 商圈 (`"南京復興生活圈"`).
    pub shop_name: String,
    /// Marketing tags (`["近捷運", "低公設", "景觀宅"]`).
    #[serde(default)]
    pub tag: Vec<String>,
    /// `YYYYMM` integer (e.g. `202510`). 0 for unset / null on the wire.
    #[serde(default, deserialize_with = "u32_string_or_int_default")]
    pub open_sell_time: u32,
    pub deal_time: DealTime,
    /// Construction company.
    pub build_company: String,
    /// Sales agency.
    pub sell_company: String,
    /// `"SRC鋼骨鋼筋混凝土結構"` etc.
    pub structural_engine: String,
    /// `"地上18層,地下4層"`.
    pub floor: String,
    /// `"毛胚屋、標準配備"` etc.
    pub decorate: String,
    /// Parking ratio (`"1:1.03"`).
    pub park_ratio: String,
    /// Pre-construction license (建照).
    pub license: String,
    /// Use license / occupancy permit (使照).
    pub use_license: String,
    /// All-time browse count.
    pub browsenum: u64,
    /// Favourite count.
    pub fav_num: u64,
}

/// One market-data row — either a per-room average (`name: "2房均價"`)
/// or a project-wide aggregate (`name: "成交均價"`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseMarketRoom {
    /// Display label (`"成交均價"`, `"2房均價"`, …).
    pub name: String,
    /// Average per-坪 price as a string (e.g. `"149.1"`, in 萬/坪).
    /// Empty when the project has no transactions yet.
    pub price: String,
}

/// One actual-transaction record from the project's market history.
/// 591 surfaces the most recent N transactions on the project page;
/// older rows can be paginated via the price-list endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseMarketItem {
    pub id: u64,
    /// ISO date (`"2026-03-10"`).
    pub trans_date: String,
    /// ROC year-month (`"115-03"`).
    pub month: String,
    /// Layout (`"2房2廳"`, `"3房2廳"`).
    pub layout_v2: String,
    pub build_area_v: AreaValue,
    pub building_area: AreaValue,
    pub unit_price: PriceValue,
    /// Total transaction price (e.g. `"3,968"` in 萬元 — comma-separated).
    pub total_price_v: String,
    pub shift_floor: String,
}

/// Project market block — average prices + recent transactions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseMarket {
    pub housing_id: u64,
    pub housing_name: String,
    /// Linked community ID once delivered (0 / null until then).
    #[serde(default, deserialize_with = "u64_string_or_int_default")]
    pub community_id: u64,
    /// Per-room average prices (and project-wide aggregate).
    #[serde(default)]
    pub rooms: Vec<NewhouseMarketRoom>,
    /// Recent transactions (most-recent first).
    #[serde(default)]
    pub items: Vec<NewhouseMarketItem>,
    /// Total number of transactions on record (across all pages).
    #[serde(default, deserialize_with = "u64_string_or_int_default")]
    pub total: u64,
    /// MM/DD of the last 591-side data refresh (`"04/21"`).
    #[serde(default)]
    pub update_date: String,
}

/// Floor-plan block. Empty for projects that haven't published plans.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseLayoutBlock {
    /// Total number of floor plans available.
    #[serde(default, deserialize_with = "u64_string_or_int_default")]
    pub total: u64,
    /// Raw items (kept as `Value` because the wire shape is sparse on
    /// our pinned test project — typing it would be guesswork).
    #[serde(default)]
    pub items: Vec<serde_json::Value>,
    #[serde(default)]
    pub room_group: Vec<serde_json::Value>,
}

/// Single listed sales agent for a newhouse project.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseSalesAgent {
    pub user_id: u64,
    /// Display name (often the project name itself, sometimes an
    /// individual rep).
    pub realname: String,
    pub mobile_v2: String,
    #[serde(default)]
    pub email: String,
    #[serde(default)]
    pub introduction: String,
    pub avatar: String,
    /// Marketing-side tags (`["17人諮詢"]`, etc.).
    #[serde(default)]
    pub tags: Vec<String>,
}

/// Aggregate of `/v1/detail/module-info` data — the curated subset
/// across `layout` / `market` / `sales`. `news` and `report` are
/// dropped (mostly empty across the projects we sampled).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseModules {
    pub layout: NewhouseLayoutBlock,
    pub market: Option<NewhouseMarket>,
    /// Listed sales agents.
    pub sales_agents: Vec<NewhouseSalesAgent>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct NewhouseModuleInfoResponse {
    pub status: i32,
    pub msg: Option<String>,
    pub data: Option<NewhouseModuleInfoData>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct NewhouseModuleInfoData {
    #[serde(default = "default_layout")]
    pub layout: NewhouseLayoutBlock,
    pub market: Option<NewhouseMarket>,
    #[serde(default)]
    pub sales: NewhouseSalesData,
}

fn default_layout() -> NewhouseLayoutBlock {
    NewhouseLayoutBlock {
        total: 0,
        items: vec![],
        room_group: vec![],
    }
}

#[derive(Debug, Clone, Default, Deserialize)]
pub(crate) struct NewhouseSalesData {
    #[serde(default)]
    pub data: Vec<NewhouseSalesAgent>,
}

/// Aggregated result of `Client591::newhouse_detail` — the merged
/// output of 6 parallel sub-endpoint calls. Sub-calls that fail
/// independently land their error message in the corresponding
/// `*_error` field rather than failing the whole bundle; callers
/// inspecting the bundle should expect partial coverage on
/// projects with sparse data.
#[derive(Debug, Clone, Serialize)]
pub struct NewhouseDetail {
    pub housing: Option<NewhouseHousing>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub housing_error: Option<String>,

    pub modules: Option<NewhouseModules>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modules_error: Option<String>,

    /// Categorized photo gallery (empty Vec if unavailable, distinct
    /// from `photos_error: Some(_)` which means the call failed).
    pub photos: Vec<NewhousePhotoCategory>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub photos_error: Option<String>,

    pub surrounding: Option<NewhouseSurrounding>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub surrounding_error: Option<String>,

    pub nearby_market: Option<NewhouseNearbyMarket>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nearby_market_error: Option<String>,

    pub price_list: Option<NewhousePriceList>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price_list_error: Option<String>,
}

/// Most-recent sale-control entry (the latest unit 591 has data on for a project).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseSaleCtrlPrice {
    pub id: u64,
    /// Unit address (`"A棟7樓09戶"`).
    pub address: String,
    /// Layout (`"2房"`, `"3房"`, …).
    pub room: String,
    pub unit_price: PriceValue,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseSaleCtrlInfo {
    /// How many price updates have been recorded.
    pub update_count: u64,
    pub price: NewhouseSaleCtrlPrice,
}

/// `/v1/price/list` response — project price catalogue.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhousePriceList {
    pub housing_id: u64,
    pub housing_name: String,
    /// Linked community ID (0 / null if pre-handover).
    #[serde(default, deserialize_with = "u64_string_or_int_default")]
    pub community_id: u64,
    /// Per-room average prices (e.g. 成交均價, 2房均價, …). Same
    /// shape as [`NewhouseMarketRoom`].
    #[serde(default)]
    pub rooms: Vec<NewhouseMarketRoom>,
    /// Whether 591 has sale-control data for this project.
    #[serde(default)]
    pub has_sale_ctrl: u8,
    /// Most-recent recorded unit (when `has_sale_ctrl: 1`).
    pub sale_ctrl_info: Option<NewhouseSaleCtrlInfo>,
    /// Per-unit transaction items (often empty for active pre-sale
    /// projects — module-info's `market.items` is usually richer).
    #[serde(default)]
    pub items: Vec<NewhouseMarketItem>,
    /// Total number of items across all pages.
    #[serde(default, deserialize_with = "u64_string_or_int_default")]
    pub total: u64,
    /// MM/DD of last 591-side refresh (`"04/21"`).
    #[serde(default)]
    pub update_date: String,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct NewhousePriceListResponse {
    pub status: i32,
    pub msg: Option<String>,
    pub data: Option<NewhousePriceList>,
}

/// `{content, unit}` pair — used by nearby-market for compact value+unit display.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContentUnit {
    pub content: String,
    pub unit: String,
}

/// One nearby community resale comp from `/v1/detail/nearby-market`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseNearbyComm {
    pub community_id: u64,
    pub community_name: String,
    /// Total transactions on record.
    pub deal_count: u64,
    /// Average per-坪 price (e.g. `{content: "142.7", unit: "萬/坪"}`).
    pub price: ContentUnit,
    pub community_image: String,
    /// Internal type code (0/1).
    #[serde(default)]
    pub build_type: u8,
    /// Display string (`"預售屋"`, `"3年社區"`, `"5年社區"`, …).
    pub build_type_str: String,
    pub build_purpose: String,
    /// Layout summary (`{content: "1、2", unit: "房"}` = 1- and 2-bed units).
    pub layout: ContentUnit,
    /// Area range (`{content: "13~25", unit: "坪"}`).
    pub area: ContentUnit,
    /// Age in years (0 / null for pre-sale).
    #[serde(default, deserialize_with = "u32_string_or_int_default")]
    pub age: u32,
    /// Distance to the queried project in metres.
    pub distance: u64,
}

/// One nearby business / 商圈 from `/v1/detail/nearby-market`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseNearbyBusiness {
    pub id: u64,
    pub shop_id: u64,
    pub name: String,
    /// Average per-坪 price for the 商圈 (e.g. `"165.0"`).
    pub price_unit: String,
    pub unit: String,
}

/// Aggregate of `/v1/detail/nearby-market` data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseNearbyMarket {
    /// Nearby communities (resale comps).
    #[serde(default)]
    pub community_items: Vec<NewhouseNearbyComm>,
    /// Nearby business districts (`商圈`).
    #[serde(default)]
    pub business_items: Vec<NewhouseNearbyBusiness>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct NewhouseNearbyMarketResponse {
    pub status: i32,
    pub msg: Option<String>,
    pub data: Option<NewhouseNearbyMarket>,
}

/// One nearby POI from `/v1/detail/surrounding`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhousePoi {
    pub name: String,
    /// Walking distance in metres (591's own measurement).
    pub distance: u64,
    /// Pre-formatted distance string (`"距建案約876公尺"`).
    pub distance_text: String,
    pub lat: f64,
    pub lng: f64,
    /// Sub-type code (`"subway_station"`, `"bus_station"`,
    /// `"grade"` (elementary), `"middle"`, `"shopping_mall"`,
    /// `"department_store"`, …).
    pub sub_type: String,
}

/// Categorized POIs around a newhouse project, with totals.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseSurroundingFacility {
    /// Total POIs across all categories (591's own count).
    #[serde(default, deserialize_with = "u64_string_or_int_default")]
    pub total: u64,
    /// Transit (subway, bus, train).
    #[serde(default)]
    pub traffic: Vec<NewhousePoi>,
    /// Schools (elementary, middle, high, college).
    #[serde(default)]
    pub education: Vec<NewhousePoi>,
    /// Daily-life amenities (shops, restaurants, parks, …).
    #[serde(default)]
    pub life: Vec<NewhousePoi>,
}

/// `lat`/`lng` are wire-strings, not numbers — `MapCoord` parses them.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MapCoord {
    pub lat: String,
    pub lng: String,
    #[serde(default)]
    pub pending: u8,
}

/// Project location metadata from `/v1/detail/surrounding`'s housing block.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseSurroundingHousing {
    pub hid: u64,
    pub build_name: String,
    pub address: String,
    /// Project building location.
    pub map: MapCoord,
    /// Sales-office address.
    #[serde(default)]
    pub reception_address: String,
    /// Sales-office location.
    pub reception_map: MapCoord,
}

/// Aggregate of `/v1/detail/surrounding` data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhouseSurrounding {
    pub facility: NewhouseSurroundingFacility,
    pub housing: NewhouseSurroundingHousing,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct NewhouseSurroundingResponse {
    pub status: i32,
    pub msg: Option<String>,
    pub data: Option<NewhouseSurrounding>,
}

/// One photo within a [`NewhousePhotoCategory`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhousePhoto {
    pub id: u64,
    /// Category code (`"logo"`, `"plan"`, `"realistic"`, `"circum"`, …).
    pub cate: String,
    /// Display category name (`"封面圖"`, `"平面圖"`, `"實景圖"`, `"環境圖"`, …).
    pub cate_name: String,
    /// Optional caption (e.g. `"捷運中山國中站"` for an environment photo).
    #[serde(default)]
    pub note: String,
    /// 900px-wide watermarked variant (the "main" gallery image).
    pub src_img: String,
    /// 160×120 thumbnail.
    #[serde(default)]
    pub small_img: String,
    /// 750px-wide variant (mobile-optimized).
    #[serde(default)]
    pub big_img: String,
    #[serde(default)]
    pub description: String,
}

/// One photo category bucket (cover / floor plan / traffic / 3D / real-life / environment).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewhousePhotoCategory {
    /// Category code (`"logo"`, `"plan"`, …).
    pub id: String,
    /// Display name (`"封面圖"`, `"平面圖"`, …).
    pub name: String,
    pub build_name: String,
    pub total: u64,
    #[serde(default)]
    pub items: Vec<NewhousePhoto>,
}

/// `/v1/detail/photos` returns `data` as a top-level array of
/// categories (not an object). This wrapper deserializes the
/// `{status, msg, data: [...]}` envelope into a Vec of categories.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct NewhousePhotosResponse {
    pub status: i32,
    pub msg: Option<String>,
    pub data: Option<Vec<NewhousePhotoCategory>>,
}

/// Top-level wrapper for `/v1/detail/base-info`. Other top-level
/// keys (`meta`, `nearby`, `dynamic`, `same_region_section`, etc.)
/// are dropped intentionally — call other `newhouse_*` methods for
/// those data dimensions.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct NewhouseBaseInfoResponse {
    pub status: i32,
    pub msg: Option<String>,
    pub data: Option<NewhouseBaseInfoData>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct NewhouseBaseInfoData {
    pub housing: Option<NewhouseHousing>,
}

// ---------------------------------------------------------------------------
// /v1/high-value/search — premium-listing curated search
// ---------------------------------------------------------------------------

/// Inclusive numeric range with optional bounds. 591's high-value
/// endpoint accepts an array of these for `price` and `area`
/// filtering — both ends may be `null` to mean "no bound on this side".
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceRange {
    /// Lower bound in 萬 (10,000 NTD). `None` means no lower limit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<u32>,
    /// Upper bound in 萬. `None` means no upper limit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<u32>,
}

/// Inclusive area range in 坪 (Taiwanese unit, ~3.3 m²). Both ends optional.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AreaRange {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<f64>,
}

/// Request body for `Client591::high_value_search`. Most arrays are
/// "preferred" filters — empty Vec means "no preference"; populated
/// Vec biases the result toward matching listings but isn't strictly
/// enforced (591's curation overrides individual filters).
///
/// **Quirks observed live 2026-04-30:**
/// - Two `kind` values populate distinct curated pools: `9` (the
///   default, mostly residential) and `10` (a separate bucket with
///   different streets / `post_id`s). `0` is treated server-side as
///   `9`. Other values (1..8, 11+) yield empty arrays.
/// - The wire-side `kind: 9` here is NOT "land" (as on rent
///   endpoints) — it tags the curated premium pool; returned items
///   are mostly residentials (e.g. `"3房2廳"`).
/// - `section_id` filtering is non-strict (results may include
///   sections not in the requested list).
/// - `type: 2` is the only observed value (sale-side curation).
#[derive(Debug, Clone, Serialize)]
pub struct HighValueParams {
    pub region_id: u32,
    /// Curated-pool tag. Only `9` returns non-empty results today.
    pub kind: u32,
    /// `2` = sale-side curation.
    #[serde(rename = "type")]
    pub kind_type: u32,
    #[serde(default)]
    pub section_id: Vec<u32>,
    /// 591 sends shape codes as strings (e.g. `["2"]`), not ints.
    #[serde(default)]
    pub shape: Vec<String>,
    #[serde(default)]
    pub room: Vec<u32>,
    #[serde(default)]
    pub price: Vec<PriceRange>,
    #[serde(default)]
    pub area: Vec<AreaRange>,
}

impl HighValueParams {
    /// Convenience constructor: every filter empty, `region_id`
    /// defaulted to Taipei, `kind=9` (the only kind that returns
    /// data), `type=2` (sale).
    pub fn for_region(region_id: u32) -> Self {
        Self {
            region_id,
            kind: 9,
            kind_type: 2,
            section_id: vec![],
            shape: vec![],
            room: vec![],
            price: vec![],
            area: vec![],
        }
    }
}

/// One curated premium-listing result from `/v1/high-value/search`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HighValueListing {
    pub post_id: u64,
    pub title: String,
    /// Listing type (`2` = sale, observed).
    #[serde(rename = "type")]
    pub kind_type: u32,
    /// Curated-pool tag (always `9` in observed responses).
    pub kind: u32,
    /// Total price in `unit` (typically 萬 = 10,000 NTD). Always
    /// populated in observed responses (verified across 39 live samples
    /// spanning 6 regions, 2026-04-30); deserializer accepts string-int
    /// for forward-compat with the SaleListData.total wire flip but
    /// fails loudly on null — consistent with the loud-fail policy on
    /// sibling required-numerics (area, room, hall, toilet).
    #[serde(deserialize_with = "u64_string_or_int")]
    pub price: u64,
    /// Price unit string (`"萬"`).
    pub unit: String,
    /// Area in `area_unit`.
    pub area: f64,
    /// Area unit (`"坪"`).
    pub area_unit: String,
    /// Per-坪 price (e.g. `114.1` 萬/坪).
    pub unit_price: f64,
    /// Bedrooms.
    pub room: u32,
    /// 廳 (living rooms).
    pub hall: u32,
    /// 衛 (bathrooms).
    pub toilet: u32,
    /// Pre-formatted layout (`"3房2廳1衛"`).
    pub layout: String,
    pub region_name: String,
    pub section_name: String,
    /// Street name (e.g. `"建國南路一段"`).
    pub street_name: String,
    /// Cover image URL.
    pub cover: String,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct HighValueSearchResponse {
    pub status: i32,
    #[serde(default)]
    pub msg: String,
    #[serde(default)]
    pub data: Vec<HighValueListing>,
}

// ---------------------------------------------------------------------------
// /v1/coordinate/area — GPS lat/lng → 591 region/section reverse-geocode
// ---------------------------------------------------------------------------

/// 591 region+section pair resolved from GPS coordinates.
///
/// Returned by `Client591::coordinate_area`. Field semantics match
/// the existing `REGIONS` table — `region_id` indexes into it (1 =
/// Taipei), and `section_id` is the 591-internal district code
/// within that region (e.g. 信義區 within Taipei is `section_id: 7`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordArea {
    pub region_id: u32,
    pub region_name: String,
    pub section_id: u32,
    pub section_name: String,
}

/// Internal wire-shape wrapper for `/v1/coordinate/area`.
///
/// 591 returns two distinct `data` shapes:
/// - **Hit** (coords in Taiwan): `{"status":1,"data":{"area":{...}}}`
/// - **Miss** (off-Taiwan): `{"status":0,"msg":"坐标不在台湾范围内","data":[]}`
///
/// `data` is typed as raw `serde_json::Value` because the `[]` vs
/// `{area: …}` polymorphism would defeat a typed struct. The
/// adapter dispatches on `status` and only deserializes the hit
/// shape into [`CoordArea`].
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct CoordResponse {
    pub status: i32,
    #[serde(default)]
    pub msg: String,
    #[serde(default)]
    pub data: serde_json::Value,
}

// ---------------------------------------------------------------------------
// /v2/web/rent/detail — single rent listing detail
// /v1/ware/photos     — categorized photo gallery
// ---------------------------------------------------------------------------

/// One labelled key/value pair. Used pervasively in `RentDetail`'s
/// `info` / `cost.data` / `houseInfo.data` arrays — 591 wraps every
/// surfaced fact this way so the website can display label+value
/// rows without front-end string mapping.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LabelledValue {
    /// Display label (`"類型"`, `"押金"`, `"管理費"`, `"租期"`, …).
    pub name: String,
    /// Display value (`"獨立套房"`, `"500元/月"`, `"一年"`, …).
    pub value: String,
    /// Stable key for programmatic lookup (`"kind"`, `"deposit"`,
    /// `"manageprice"`, `"leaseTime"`, …).
    pub key: String,
}

/// One tag attached to a rent listing (`{id: 16, value: "新上架"}`).
/// IDs are stable (e.g. `2` = 近捷運, `16` = 新上架, `19` = 社會住宅).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentTag {
    pub id: u32,
    pub value: String,
}

/// Free-form listing description block.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentRemark {
    /// `"屋況介紹"`.
    #[serde(default)]
    pub title: String,
    /// Stable key (`"remark"`).
    #[serde(default)]
    pub key: String,
    /// Visibility flag (1 = visible).
    #[serde(default)]
    pub active: u32,
    /// Free-form Chinese description text from the lister. Defaults
    /// to empty when 591 omits it for a maintenance-state listing.
    #[serde(default)]
    pub content: String,
}

/// One amenity entry within [`RentServiceTable::facility`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentServiceItem {
    /// Stable amenity key (`"fridge"`, `"washer"`, `"tv"`, `"cold"`,
    /// `"heater"`, `"bed"`, `"closet"`, `"fourth"`, `"net"`, …).
    pub key: String,
    /// Display name (`"冰箱"`, `"洗衣機"`, `"電視"`, …).
    pub name: String,
    /// 1 = provided in this rental, 0 = not provided. The wire
    /// response always carries every amenity in the master list,
    /// even those not provided — `active` is the discriminator.
    #[serde(default)]
    pub active: u32,
}

/// One usage-rule entry within [`RentServiceTable::notice`].
/// Examples: `{key: "leaseTime", name: "最短一年"}`,
/// `{key: "pet", name: "不可養寵物"}`, `{key: "cook", name: "不可開伙"}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentNoticeItem {
    pub key: String,
    pub name: String,
}

/// `RentDetail.service` — provided amenities + usage rules.
///
/// Distinct shape from [`RentFactTable`] (which uses a `data` array).
/// `service` returns `{title, active, facility, notice}` where each
/// facility row carries an `active` discriminator (so callers can
/// filter to *actually-provided* amenities) and `notice` carries
/// usage rules that don't fit the cost-table model.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentServiceTable {
    /// `"提供設備"`.
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub active: u32,
    /// Master amenity list, including not-provided rows
    /// (`active: 0`). Filter by `active == 1` for the "what's actually
    /// provided" subset.
    #[serde(default)]
    pub facility: Vec<RentServiceItem>,
    /// Usage rules / lease constraints (lease term, pet policy,
    /// cooking allowed, …).
    #[serde(default)]
    pub notice: Vec<RentNoticeItem>,
}

/// Listing publish state — when it went online + when it was last refreshed.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RentPublish {
    pub id: u32,
    /// Display name (`"新發佈"`, `"已上架"`, …).
    pub name: String,
    /// Stable key (`"new"`, `"old"`, …).
    pub key: String,
    /// `"此房屋在13小時前發佈"` etc.
    #[serde(default)]
    pub post_time: String,
    /// `"19分鐘內更新"` etc.
    #[serde(default)]
    pub update_time: String,
}

/// Listing address with GPS coordinates.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentAddress {
    /// Display address (`"中山區雙城街50號"`).
    pub data: String,
    /// Sometimes-redundant fuller form (591 occasionally double-prints).
    #[serde(default)]
    pub value: String,
    /// Latitude as wire-string (parse with `.parse::<f64>()`).
    pub lat: String,
    /// Longitude as wire-string.
    pub lng: String,
    /// Nearest transit summary (often empty — see `RentDetail.surround`
    /// for structured POIs).
    #[serde(default)]
    pub traffic: String,
    #[serde(default)]
    pub station: String,
    #[serde(default)]
    pub distance: String,
}

/// Listing's primary contact (agent or owner).
///
/// **Wire shape is polymorphic** — verified live 2026-04-30: 591
/// inconsistently returns this as either a named-field object
/// (`{"name":"程先生","role":3,...}`) OR an array of K/V pairs
/// (`[{"key":"name","value":"程先生"},{"key":"role","value":3},...]`).
/// Both forms carry the same data; the discriminator appears
/// load-balancer- or A/B-driven.
///
/// To handle both, this is stored as a raw `serde_json::Value` and
/// queried via accessor methods (`name()`, `role_name()`, `mobile()`,
/// etc.) that dispatch on the wire shape.
pub type RentLinkInfo = serde_json::Value;

/// Helpers for reading [`RentLinkInfo`] under either wire shape.
pub trait RentLinkInfoExt {
    /// Read a string field by key (e.g. `"name"`, `"mobile"`,
    /// `"roleName"`). Returns `None` if absent or the wire-side value
    /// isn't a string.
    fn link_str(&self, key: &str) -> Option<&str>;
    /// Read a u64 field by key (e.g. `"uid"`, `"imUid"`, `"shopId"`).
    fn link_u64(&self, key: &str) -> Option<u64>;
    /// Read a u32 field by key (e.g. `"role"`, `"isAgent"`).
    fn link_u32(&self, key: &str) -> Option<u32>;
}

impl RentLinkInfoExt for RentLinkInfo {
    fn link_str(&self, key: &str) -> Option<&str> {
        if let Some(obj) = self.as_object() {
            // Object form: direct key lookup.
            obj.get(key).and_then(|v| v.as_str())
        } else if let Some(arr) = self.as_array() {
            // Array form: scan for {key: <key>, value: ...}.
            arr.iter()
                .find(|e| e.get("key").and_then(|k| k.as_str()) == Some(key))
                .and_then(|e| e.get("value").and_then(|v| v.as_str()))
        } else {
            None
        }
    }
    fn link_u64(&self, key: &str) -> Option<u64> {
        if let Some(obj) = self.as_object() {
            obj.get(key).and_then(|v| v.as_u64())
        } else if let Some(arr) = self.as_array() {
            arr.iter()
                .find(|e| e.get("key").and_then(|k| k.as_str()) == Some(key))
                .and_then(|e| e.get("value").and_then(|v| v.as_u64()))
        } else {
            None
        }
    }
    fn link_u32(&self, key: &str) -> Option<u32> {
        self.link_u64(key).and_then(|v| u32::try_from(v).ok())
    }
}

/// One section in the cost / houseInfo / similar fact-tables.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentFactTable {
    pub title: Option<String>,
    /// Visibility flag (1 = active/visible).
    #[serde(default)]
    pub active: u32,
    /// Labelled key/value rows.
    #[serde(default)]
    pub data: Vec<LabelledValue>,
}

/// One nearby POI within `RentDetail.surround.data[].children`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RentSurroundPoi {
    /// `"subway"`, `"bus"`, `"school"`, `"market"`, …
    #[serde(rename = "type")]
    pub kind: String,
    pub name: String,
    /// Walking distance in metres.
    pub distance: u64,
    /// `"距房屋約558公尺"`.
    #[serde(default)]
    pub distance_txt: String,
}

/// One category of surrounding POIs (`{name: "交通", key: "traffic", children: [...]}`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentSurroundCategory {
    /// Display name (`"交通"`, `"教育"`, `"生活"`, …).
    pub name: String,
    /// Stable key (`"traffic"`, `"education"`, `"life"`).
    pub key: String,
    #[serde(default)]
    pub children: Vec<RentSurroundPoi>,
}

/// Surrounding POIs block — categorized like `NewhouseSurroundingFacility`
/// but with a different wire shape (rent-side uses categorized children
/// with `key`/`name`; newhouse-side uses flat top-level keys).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentSurround {
    pub title: String,
    pub key: String,
    pub address: String,
    /// Project lat/lng as wire-strings.
    pub lat: String,
    pub lng: String,
    #[serde(default)]
    pub data: Vec<RentSurroundCategory>,
}

/// Single-listing detail from `bff-house.591.com.tw/v2/web/rent/detail`.
///
/// Curated subset of the wire `data` block (~30 top-level fields →
/// ~17 surfaced). Skipped fields: `gtm_detail_data`, `meta`, `navData`,
/// `shareInfo`, `favData`, `containCost`, `relieved`, `version`,
/// `information` (alt of `info`) — telemetry / SEO / rendering
/// metadata that adds noise without value.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RentDetail {
    pub title: String,
    /// Display price (`"17,800"` — note the comma).
    pub price: String,
    /// Price unit (`"元/月"`).
    pub price_unit: String,
    /// Deposit display (`"押金面議"` or `"2個月"`).
    pub deposit: String,
    /// Pre-formatted headline (`"17,800元/月"`).
    pub head_info: String,
    pub address: RentAddress,
    pub region_id: u32,
    pub section_id: u32,
    /// House-kind code: 1=整層, 2=獨立套房, 3=分租套房, 8=雅房, 6=辦公, 24=車位.
    pub kind: u32,
    /// Listing status (`"open"`, `"closed"`).
    pub status: String,
    /// Quick-fact rows (類型 / 使用坪數 / 樓層 / 型態).
    #[serde(default)]
    pub info: Vec<LabelledValue>,
    /// Cost breakdown (押金 / 管理費 / 仲介費).
    pub cost: RentFactTable,
    /// Detailed house attributes (租期, 入住, 身份, 法定用途, …).
    pub house_info: RentFactTable,
    /// Tenant preferences (養寵物 / 開伙 / 性別偏好 / …) — same fact-table shape.
    pub preference: RentFactTable,
    /// Provided amenities (`facility[]`) + usage rules (`notice[]`).
    /// Distinct shape from the other fact-tables — see [`RentServiceTable`].
    pub service: RentServiceTable,
    /// Surrounding POIs categorized by traffic/education/life.
    pub surround: RentSurround,
    pub tags: Vec<RentTag>,
    /// Publish/refresh metadata.
    pub publish: RentPublish,
    /// Free-form listing description (`{title, key, active, content}`).
    pub remark: RentRemark,
    /// Primary contact (agent / owner).
    pub link_info: RentLinkInfo,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RentDetailResponse {
    pub status: i32,
    #[serde(default)]
    pub msg: String,
    pub data: Option<RentDetail>,
}

/// One photo within a [`RentPhotoGroup`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RentPhoto {
    pub photo_id: u64,
    /// 1000px-wide watermarked variant (the gallery image).
    pub photo: String,
    /// 600px-tall variant.
    #[serde(default)]
    pub orig_photo: String,
    /// 400×300 thumbnail.
    #[serde(default)]
    pub thumb_photo: String,
    /// 1 if this is the cover photo, 0 otherwise.
    #[serde(default)]
    pub is_cover: u32,
    /// Purpose code (10 = cover, 12 = bedroom, etc. — see
    /// `RentPhotosData.purposes` for the lookup table per response).
    #[serde(default)]
    pub purpose: u32,
    /// Optional caption.
    #[serde(default)]
    pub note: String,
    /// Wire type code (3 observed).
    #[serde(default, rename = "type")]
    pub kind: u32,
}

/// One bucket of photos within `/v1/ware/photos`'s `data.list`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RentPhotoGroup {
    /// Group key (`"picture"`, `"floor"`, `"environment"`, …).
    pub key: String,
    #[serde(default)]
    pub items: Vec<RentPhoto>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RentPhotosResponse {
    pub status: i32,
    #[serde(default)]
    pub msg: String,
    pub data: Option<RentPhotosData>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RentPhotosData {
    #[serde(default)]
    pub list: Vec<RentPhotoGroup>,
}

// ---------------------------------------------------------------------------
// /v1/touch/sale/detail   — single sale listing detail
// /v2/web/sale/similar-wares — similar sale listings
// ---------------------------------------------------------------------------

/// Single sale listing detail from `bff-house.591.com.tw/v1/touch/sale/detail`.
///
/// Curated subset of the wire `data` block (~150 fields → ~30 surfaced).
/// Most fields are wire-strings (591 stringly-types numeric IDs and
/// coordinates on this endpoint — `region_id`, `room`, `lat`/`lng`,
/// `houseage` etc. all arrive as strings). To stay loyal to the wire
/// without forcing risky parses, identifiers + coords stay as `String`
/// — callers `.parse::<f64>()` / `.parse::<u32>()` as needed.
///
/// **The wire `id` field has an `S` prefix** (e.g. `"S19599759"`).
/// Pass the bare numeric ID to `Client591::sale_detail` and the
/// adapter prepends `S` for you.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SaleDetail {
    /// Wire ID with `S` prefix (e.g. `"S19599759"`).
    pub id: String,
    pub title: String,
    /// Pre-formatted price (`"1,988萬元"`).
    pub price: String,
    /// Numeric price as a wire-string (`"1988"`, in 萬).
    pub price_value: String,
    /// Per-坪 price string (`"86.02萬/坪"`).
    pub unitprice: String,
    /// Pre-formatted area (`"23.111坪"`).
    pub area: String,
    /// Numeric area as wire-string (`"23.111"`).
    pub area_value: String,
    /// Pre-formatted layout (`"3房2廳3衛"`).
    pub layout: String,
    /// Number of bedrooms as wire-string (`"3"`).
    pub room: String,
    /// Number of living rooms as wire-string.
    pub hall: String,
    /// Number of bathrooms as wire-string.
    pub toilet: String,
    /// Display kind (`"住宅"`, `"商業"`, `"辦公"`, …).
    pub kind: String,
    /// Numeric kind code as wire-string (`"9"` = residential, …).
    pub kind_id: String,
    pub region: String,
    /// Wire-string region ID — `.parse::<u32>()` for numeric.
    pub region_id: String,
    pub section: String,
    pub section_id: String,
    /// Display address (often empty for owner-direct rentals — see
    /// `lat`/`lng` for coordinates).
    #[serde(default)]
    pub addr: String,
    /// Latitude as wire-string.
    pub lat: String,
    /// Longitude as wire-string.
    pub lng: String,
    /// Age string (`"56年"`).
    #[serde(default)]
    pub age: String,
    /// Numeric age as wire-string (`"56"`).
    #[serde(default)]
    pub houseage: String,
    /// Building shape (`"透天厝"`, `"電梯大樓"`, `"公寓"`, …).
    #[serde(default)]
    pub shape: String,
    /// Decoration level (`"中檔裝潢"`, `"無"`, …).
    #[serde(default)]
    pub fitment: String,
    /// Direction (`"東南"`, `"南"`, …).
    #[serde(default)]
    pub direction: String,
    /// Lift-availability flag as wire-string (`"0"` / `"1"`).
    #[serde(default)]
    pub lift: String,
    /// Pre-formatted parking text (`"無"`, `"1個"`, …).
    #[serde(default)]
    pub parking: String,
    /// Main usable area (`"20.69坪"`).
    #[serde(default)]
    pub mainarea: String,
    /// Management fee text (`"500元/月"`, `"無"`, …). Sentinel
    /// `"99999"` on the numeric `manageprice` indicates "not applicable".
    #[serde(default)]
    pub managefee: String,
    /// Unix timestamp of post (as wire-string).
    pub posttime: String,
    /// Linked community name (empty for owner-direct without community).
    #[serde(default)]
    pub community: String,
    /// Linked community ID (empty string for unlinked).
    #[serde(default)]
    pub community_id: String,
    /// Listing's primary contact (the `linkman` / agent / owner).
    pub linkman: String,
    /// Mobile phone (`"0965-109-089"`).
    #[serde(default)]
    pub mobile: String,
    /// Landline.
    #[serde(default)]
    pub telephone: String,
    /// Email address.
    #[serde(default)]
    pub email: String,
    /// Display contact role (`"仲介"` / `"屋主"`).
    pub identity: String,
    /// Agent shop / company.
    #[serde(default)]
    pub company_name: String,
    /// Agent certificate type (`"Middleman"` etc.).
    #[serde(default)]
    pub certificate_type: String,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct SaleDetailResponse {
    pub status: i32,
    /// `Option<String>` because 591 returns `"msg": null` on this
    /// endpoint when status=1 — `#[serde(default)]` alone wouldn't
    /// cover the explicit-null case (it only covers missing keys).
    #[serde(default)]
    pub msg: Option<String>,
    pub data: Option<SaleDetail>,
}

/// One similar sale listing from `bff-house.591.com.tw/v2/web/sale/similar-wares`.
/// Wire is heavily stringly-typed (every numeric is a string) — the
/// type stays loyal to that and lets callers parse as needed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SaleSimilarWare {
    /// Wire-string listing type code (`"2"` = sale).
    #[serde(rename = "type")]
    pub kind_type: String,
    pub post_id: String,
    pub title: String,
    /// Pre-formatted price (`"1980"` in 萬, no thousands separator).
    pub price: String,
    /// Pre-formatted area (`"20.808"` in 坪).
    pub area: String,
    /// Wire-string house-kind code.
    pub kind: String,
    /// Layout summary (`"6房6衛"`).
    #[serde(default)]
    pub room: String,
    pub section_name: String,
    /// Cover image URL.
    pub photo_url: String,
    /// Marketing tag string (often empty).
    #[serde(default)]
    pub tag: String,
    /// `"vip"`/`"refresh"`/etc. — empty when no special boost.
    #[serde(default)]
    pub similar_type: String,
    /// 1 = boosted/premium listing.
    #[serde(default)]
    pub is_vip: String,
    /// 1 = recently refreshed.
    #[serde(default)]
    pub is_refresh: String,
    /// 1 = combined / bundled ad slot (591 groups some listings for
    /// joint promotion). Useful for filtering boost-grouped duplicates.
    #[serde(default)]
    pub is_combine: String,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct SaleSimilarWaresResponse {
    pub status: i32,
    /// `Option<String>` for the same reason as `SaleDetailResponse.msg` —
    /// 591 occasionally returns `"msg": null` on these envelopes.
    #[serde(default)]
    pub msg: Option<String>,
    #[serde(default)]
    pub data: Vec<SaleSimilarWare>,
}

// ---------------------------------------------------------------------------
// Internal response wrappers (not exposed publicly)
// ---------------------------------------------------------------------------

#[derive(Deserialize)]
pub(crate) struct HotResponse {
    pub status: i32,
    pub data: Option<Vec<Community>>,
}

#[derive(Deserialize)]
pub(crate) struct NearbyResponse {
    pub status: i32,
    pub data: Option<Vec<NearbyApiItem>>,
}

/// 591's nearby payload uses snake_case keys that don't match
/// `NearbyCommunity` exactly (e.g. `regionid`/`sectionid` vs
/// `region_id`/`section_id`). This wrapper deserializes the wire
/// shape verbatim; `Client591::nearby` maps to `NearbyCommunity`.
///
/// **Maintenance:** when adding a new field to `NearbyCommunity`,
/// add the matching field here AND extend the `From` impl below.
/// Alternative would be `#[serde(rename = "regionid")]` directly on
/// `NearbyCommunity`, but the wrapper-pattern matches the rest of
/// this crate's response types.
#[derive(Deserialize)]
pub(crate) struct NearbyApiItem {
    pub id: u64,
    pub name: String,
    pub regionid: u32,
    pub sectionid: u32,
    pub region: String,
    pub section: String,
    pub price_unit: PriceValue,
    pub address: String,
    pub full_address: String,
    pub age: String,
    pub house_holds: String,
    pub build_purpose: String,
    pub distance: String,
    // TODO: `sale_num` is a sibling count-field on the same wire
    // shape as `min_price`. 591 has historically type-flipped count
    // fields (saw min_price flip from int → string in early 2026).
    // If `sale_num` flips next, wrap it the same way; the live test
    // `nearby_eat_returns_taipei_neighbours` will catch it.
    pub sale_num: u32,
    /// 591 returns this as either a JSON int or a JSON string
    /// depending on the day. Custom deserializer accepts both.
    #[serde(deserialize_with = "u64_string_or_int")]
    pub min_price: u64,
}

impl From<NearbyApiItem> for NearbyCommunity {
    fn from(v: NearbyApiItem) -> Self {
        NearbyCommunity {
            id: v.id,
            name: v.name,
            region_id: v.regionid,
            section_id: v.sectionid,
            region: v.region,
            section: v.section,
            price_unit: v.price_unit,
            address: v.address,
            full_address: v.full_address,
            age: v.age,
            house_holds: v.house_holds,
            build_purpose: v.build_purpose,
            distance: v.distance,
            sale_num: v.sale_num,
            min_price: v.min_price,
        }
    }
}

#[derive(Deserialize)]
pub(crate) struct DetailResponse {
    pub status: i32,
    pub data: Option<DetailData>,
}

#[derive(Deserialize)]
pub(crate) struct SaleListResponse {
    pub status: i32,
    pub data: Option<SaleListData>,
}

#[derive(Deserialize, Default)]
pub(crate) struct SaleListData {
    /// 591 returns this as a string (`"23899"`) on this endpoint —
    /// not an int like elsewhere. `u32_string_or_int` handles both.
    #[serde(default, deserialize_with = "u32_string_or_int_default")]
    pub total: u32,
    /// Raw items — 591 mixes paid newhouse ads (with a different
    /// schema) into the sale-listing array. We deserialize per-item
    /// in the adapter and drop ads.
    #[serde(default)]
    pub house_list: Vec<serde_json::Value>,
}

/// `u64` variant of [`u32_string_or_int`]. Used for `NearbyApiItem::
/// min_price` — 591 sometimes serializes this as a string (`"2380"`),
/// sometimes as an integer (`2380`); empirically the wire form
/// changed without notice in early 2026.
fn u64_string_or_int<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
    let v = serde_json::Value::deserialize(d)?;
    match v {
        serde_json::Value::String(s) => s.parse().map_err(serde::de::Error::custom),
        serde_json::Value::Number(n) => n
            .as_u64()
            .ok_or_else(|| serde::de::Error::custom(format!("u64 out of range: {n}"))),
        other => Err(serde::de::Error::custom(format!(
            "expected string or integer for u64, got {other:?}"
        ))),
    }
}

/// Like [`u64_string_or_int`] but also accepts `null` (returns 0) so
/// it composes with `#[serde(default)]`.
fn u64_string_or_int_default<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
    let v = serde_json::Value::deserialize(d)?;
    match v {
        serde_json::Value::Null => Ok(0),
        serde_json::Value::String(s) => s.parse().map_err(serde::de::Error::custom),
        serde_json::Value::Number(n) => n
            .as_u64()
            .ok_or_else(|| serde::de::Error::custom(format!("u64 out of range: {n}"))),
        other => Err(serde::de::Error::custom(format!(
            "expected null/string/integer, got {other:?}"
        ))),
    }
}

/// Like [`u32_string_or_int`] but also accepts `null` (returns 0) so
/// it composes with `#[serde(default)]`.
fn u32_string_or_int_default<'de, D: Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
    let v = serde_json::Value::deserialize(d)?;
    match v {
        serde_json::Value::Null => Ok(0),
        serde_json::Value::String(s) => s.parse().map_err(serde::de::Error::custom),
        serde_json::Value::Number(n) => n
            .as_u64()
            .and_then(|n| u32::try_from(n).ok())
            .ok_or_else(|| serde::de::Error::custom(format!("u32 out of range: {n}"))),
        other => Err(serde::de::Error::custom(format!(
            "expected null/string/integer, got {other:?}"
        ))),
    }
}

#[derive(Deserialize)]
pub(crate) struct NewhouseListResponse {
    pub status: i32,
    pub data: Option<NewhouseListData>,
}

#[derive(Deserialize)]
pub(crate) struct NewhouseListData {
    pub total: u32,
    pub online_total: u32,
    pub page: u32,
    pub per_page: u32,
    pub total_page: u32,
    /// Raw items — 591 mixes empty placeholder slots into the array.
    /// Per-item `from_value` + filter_map drops them.
    pub items: Vec<serde_json::Value>,
}

#[derive(Deserialize)]
pub(crate) struct CommunityRankResponse {
    pub status: i32,
    pub data: Option<CommunityRankApiData>,
}

#[derive(Deserialize)]
pub(crate) struct CommunityRankApiData {
    pub price_data: CommunityRankSlot,
    pub sale_data: CommunityRankSlot,
}

#[derive(Deserialize)]
pub(crate) struct CommunityRankSlot {
    pub data: Vec<CommunityRankItem>,
    pub time: String,
}

#[derive(Deserialize)]
pub(crate) struct DetailData {
    pub community: Option<CommunityDetail>,
    pub price: Option<PriceData>,
    pub sale: Option<SaleData>,
}

#[derive(Deserialize)]
pub(crate) struct PriceData {
    pub items: Vec<PriceRecord>,
}

#[derive(Deserialize)]
pub(crate) struct SaleData {
    pub total: u32,
    pub rooms: Vec<SaleRoom>,
}

#[derive(Deserialize)]
pub(crate) struct SaleRoom {
    pub items: Vec<SaleListing>,
}