omni-dev 0.24.0

A powerful Git commit message analysis and amendment toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
//! MCP tool handlers for Confluence operations.
//!
//! Each handler builds an [`AtlassianClient`] via [`create_client`] and then
//! delegates to the same API methods that the CLI uses under
//! `src/cli/atlassian/confluence/`, so the MCP surface and the CLI share a
//! single implementation.

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;

use anyhow::{Context, Result};
use rmcp::{
    handler::server::wrapper::Parameters,
    model::{CallToolResult, Content},
    schemars, tool, tool_router, ErrorData as McpError,
};
use serde::{Deserialize, Serialize};

use crate::atlassian::adf::AdfDocument;
use crate::atlassian::api::{AtlassianApi, ContentItem};
use crate::atlassian::client::AtlassianClient;
use crate::atlassian::confluence_api::{ChildPage, ConfluenceApi};
use crate::atlassian::convert::markdown_to_adf;
use crate::atlassian::document::{content_item_to_document, JfmDocument, JfmFrontmatter};
use crate::cli::atlassian::confluence::download::{
    run_download, DownloadParams, ManifestEntry, OnConflict,
};
use crate::cli::atlassian::format::ContentFormat;
use crate::cli::atlassian::helpers::create_client;
use crate::data::yaml::to_yaml;

use super::error::tool_error;
use super::output_file::write_to_file_yaml;
use super::server::OmniDevServer;

// ── Parameter structs ───────────────────────────────────────────────

/// Parameters for the `confluence_read` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceReadParams {
    /// Confluence page ID (e.g., "12345678").
    pub id: String,
    /// Output format: `"jfm"` (default, AI-friendly markdown) or `"adf"`
    /// (raw ADF JSON).
    #[serde(default)]
    pub format: Option<String>,
    /// When set, writes the rendered content to this path and returns a
    /// short YAML summary (path/bytes/format) instead of the inline body.
    /// Useful for large pages that would otherwise blow past the context
    /// window — the assistant can then read the file with offset/limit.
    #[serde(default)]
    pub output_file: Option<String>,
}

/// Parameters for the `confluence_search` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceSearchParams {
    /// Confluence CQL query (e.g., `space = ENG AND title ~ "architecture"`).
    pub cql: String,
    /// Maximum number of results. Defaults to 20.
    #[serde(default)]
    pub limit: Option<u32>,
}

/// Parameters for the `confluence_create` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceCreateParams {
    /// Target Confluence space key (e.g., `"ENG"`).
    pub space_key: String,
    /// Page title.
    pub title: String,
    /// Page body. Parsed according to `format`.
    pub content: String,
    /// Optional parent page ID for nesting under an existing page.
    #[serde(default)]
    pub parent_id: Option<String>,
    /// Format of `content`: `"jfm"` (default markdown) or `"adf"` (raw ADF JSON).
    #[serde(default)]
    pub format: Option<String>,
}

/// Parameters for the `confluence_write` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceWriteParams {
    /// Confluence page ID.
    pub id: String,
    /// New page body.
    pub content: String,
    /// Format of `content`: `"jfm"` (default markdown) or `"adf"` (raw ADF JSON).
    #[serde(default)]
    pub format: Option<String>,
}

/// Parameters for the `confluence_delete` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceDeleteParams {
    /// Confluence page ID.
    pub id: String,
    /// Must be `true` to confirm this destructive, irreversible operation.
    pub confirm: bool,
    /// Permanently purges the page instead of moving to trash.
    /// Requires space admin permission.
    #[serde(default)]
    pub purge: Option<bool>,
}

/// Parameters for the `confluence_download` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceDownloadParams {
    /// Root page ID to download from. Either this or `space` must be set.
    #[serde(default)]
    pub id: Option<String>,
    /// Space key to download from — every top-level page becomes a root.
    #[serde(default)]
    pub space: Option<String>,
    /// Target directory for downloaded files. Defaults to a fresh tempdir
    /// when omitted; the manifest summary reports the path used.
    #[serde(default)]
    pub output_dir: Option<String>,
    /// Only download pages whose title contains this substring (case-insensitive).
    #[serde(default)]
    pub title_filter: Option<String>,
    /// Maximum number of concurrent fetches. Defaults to 8.
    #[serde(default)]
    pub concurrency: Option<usize>,
    /// Maximum tree depth. 0 = unlimited (default).
    #[serde(default)]
    pub max_depth: Option<u32>,
    /// Output format: `"jfm"` (default) or `"adf"`.
    #[serde(default)]
    pub format: Option<String>,
}

/// Parameters for the `confluence_children` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceChildrenParams {
    /// Page ID whose children should be listed. Omit when using `space`.
    #[serde(default)]
    pub id: Option<String>,
    /// Space key (mutually exclusive with `id`): list top-level pages in
    /// the space.
    #[serde(default)]
    pub space: Option<String>,
    /// Recursively fetch descendants.
    #[serde(default)]
    pub recursive: Option<bool>,
    /// Maximum tree depth when `recursive` is set (0 = unlimited).
    #[serde(default)]
    pub max_depth: Option<u32>,
}

/// Parameters for the `confluence_comment_list` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceCommentListParams {
    /// Confluence page ID.
    pub id: String,
    /// Maximum number of comments to return (0 = unlimited).
    #[serde(default)]
    pub limit: Option<usize>,
}

/// Parameters for the `confluence_comment_add` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceCommentAddParams {
    /// Confluence page ID.
    pub id: String,
    /// Markdown content of the comment body. Converted to ADF before posting.
    pub content: String,
}

/// Parameters for the `confluence_label_list` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceLabelListParams {
    /// Confluence page ID.
    pub id: String,
    /// Maximum number of labels to return (0 = unlimited).
    #[serde(default)]
    pub limit: Option<usize>,
}

/// Parameters for the `confluence_label_add` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceLabelAddParams {
    /// Confluence page ID.
    pub id: String,
    /// Labels to add to the page.
    pub labels: Vec<String>,
}

/// Parameters for the `confluence_label_remove` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceLabelRemoveParams {
    /// Confluence page ID.
    pub id: String,
    /// Labels to remove from the page.
    pub labels: Vec<String>,
}

/// Parameters for the `confluence_user_search` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ConfluenceUserSearchParams {
    /// Search text; matches display name or email.
    pub query: String,
    /// Maximum number of results (0 = unlimited). Defaults to 25.
    #[serde(default)]
    pub limit: Option<u32>,
}

// ── Output summaries ────────────────────────────────────────────────

/// Manifest summary returned by `confluence_download`.
#[derive(Debug, Serialize)]
struct DownloadSummary {
    output_dir: String,
    page_count: usize,
    pages: Vec<DownloadSummaryEntry>,
}

#[derive(Debug, Serialize)]
struct DownloadSummaryEntry {
    id: String,
    title: String,
    path: String,
}

/// A children-tree entry returned by `confluence_children`.
///
/// Mirrors the CLI output shape (see
/// `crate::cli::atlassian::confluence::children::ChildrenEntry`) so that
/// downstream consumers see a stable schema.
#[derive(Debug, Clone, Serialize)]
pub struct ChildrenEntry {
    /// Page ID.
    pub id: String,
    /// Page title.
    pub title: String,
    /// Page status (e.g. "current", "draft"); empty when unknown.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub status: String,
    /// Parent page ID, if known.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<String>,
    /// Space key, if known.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub space_key: Option<String>,
    /// Nested children (populated when `recursive` is set).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<Self>,
}

impl From<ChildPage> for ChildrenEntry {
    fn from(p: ChildPage) -> Self {
        Self {
            id: p.id,
            title: p.title,
            status: p.status,
            parent_id: p.parent_id,
            space_key: p.space_key,
            children: Vec::new(),
        }
    }
}

/// Envelope for a mutation's YAML response.
#[derive(Debug, Serialize)]
struct MutationResult<'a> {
    ok: bool,
    message: String,
    /// Page ID the mutation targeted.
    id: &'a str,
    /// Labels touched by the mutation (empty for comment operations).
    #[serde(skip_serializing_if = "<[String]>::is_empty")]
    labels: &'a [String],
}

// ── Helpers ─────────────────────────────────────────────────────────

/// Parses a `format` param (`"jfm"`/`"adf"`, case-insensitive).
fn parse_format(raw: Option<&str>) -> Result<ContentFormat> {
    match raw.map(str::to_ascii_lowercase).as_deref() {
        None | Some("jfm") => Ok(ContentFormat::Jfm),
        Some("adf") => Ok(ContentFormat::Adf),
        Some(other) => anyhow::bail!("Invalid format \"{other}\": must be \"jfm\" or \"adf\""),
    }
}

/// Renders a [`ContentItem`] as either JFM markdown or pretty ADF JSON.
fn render_content_item(
    item: &ContentItem,
    format: ContentFormat,
    instance_url: &str,
) -> Result<String> {
    match format {
        ContentFormat::Jfm => {
            let doc = content_item_to_document(item, instance_url)?;
            doc.render()
        }
        ContentFormat::Adf => {
            let body = item.body_adf.clone().unwrap_or(serde_json::Value::Null);
            serde_json::to_string_pretty(&body).context("Failed to serialize ADF JSON")
        }
    }
}

/// Parses `content` into an ADF document, given its format.
///
/// For JFM the frontmatter `title` is returned alongside; for ADF the title
/// is empty (callers provide it separately).
fn parse_write_content(content: &str, format: ContentFormat) -> Result<(AdfDocument, String)> {
    match format {
        ContentFormat::Jfm => {
            // JFM inputs with frontmatter are passed as-is; inputs without
            // frontmatter are treated as raw markdown. The CLI requires
            // frontmatter, but the MCP caller already passes `id`/`title`
            // separately, so we don't force it here.
            if content.starts_with("---\n") {
                let doc = JfmDocument::parse(content)?;
                let adf = markdown_to_adf(&doc.body)?;
                let title = match &doc.frontmatter {
                    JfmFrontmatter::Confluence(fm) => fm.title.clone(),
                    JfmFrontmatter::Jira(fm) => fm.summary.clone(),
                };
                Ok((adf, title))
            } else {
                let adf = markdown_to_adf(content)?;
                Ok((adf, String::new()))
            }
        }
        ContentFormat::Adf => {
            let adf = AdfDocument::from_json_str(content)?;
            Ok((adf, String::new()))
        }
    }
}

/// Serializes search results as YAML for the tool response body.
fn serialize_search_results(
    results: &crate::atlassian::client::ConfluenceSearchResults,
) -> Result<String> {
    serde_yaml::to_string(results).context("Failed to serialize search results")
}

/// Build the download summary from the manifest produced by `run_download`.
fn build_download_summary(output_dir: &std::path::Path) -> Result<String> {
    let manifest_path = output_dir.join("manifest.json");
    let pages: Vec<DownloadSummaryEntry> = if manifest_path.exists() {
        let json = std::fs::read_to_string(&manifest_path)
            .with_context(|| format!("Failed to read manifest at {}", manifest_path.display()))?;
        let parsed: BTreeMap<String, ManifestEntry> =
            serde_json::from_str(&json).context("Failed to parse download manifest")?;
        parsed
            .into_iter()
            .map(|(id, entry)| DownloadSummaryEntry {
                id,
                title: entry.title,
                path: entry.path,
            })
            .collect()
    } else {
        Vec::new()
    };

    let summary = DownloadSummary {
        output_dir: output_dir.to_string_lossy().to_string(),
        page_count: pages.len(),
        pages,
    };
    serde_yaml::to_string(&summary).context("Failed to serialize download summary")
}

/// Resolves the download output directory, creating a tempdir when omitted.
///
/// Returns the path plus an optional [`tempfile::TempDir`] guard that must be
/// kept alive for the duration of the download when a tempdir was created.
fn resolve_output_dir(requested: Option<String>) -> Result<(PathBuf, Option<tempfile::TempDir>)> {
    if let Some(raw) = requested {
        let path = PathBuf::from(raw);
        std::fs::create_dir_all(&path)
            .with_context(|| format!("Failed to create output dir {}", path.display()))?;
        Ok((path, None))
    } else {
        let tmp = tempfile::Builder::new()
            .prefix("omni-dev-confluence-download-")
            .tempdir()
            .context("Failed to create download tempdir")?;
        let path = tmp.path().to_path_buf();
        Ok((path, Some(tmp)))
    }
}

// ── Children / comment / label / user-search helpers ───────────────

/// Builds the YAML output for the `confluence_children` tool.
///
/// Either `id` or `space` must be set. When `recursive` is true,
/// descendants are fetched up to `max_depth` (0 = unlimited).
pub async fn fetch_children_yaml(
    api: &ConfluenceApi,
    id: Option<&str>,
    space: Option<&str>,
    recursive: bool,
    max_depth: u32,
) -> Result<String> {
    let space_key = space.map(ToString::to_string);
    let top = fetch_top_level(api, id, space).await?;
    let mut entries = to_entries(top, space_key.as_deref());

    if recursive {
        for entry in &mut entries {
            populate_descendants(api, entry, 1, max_depth, space_key.as_deref()).await?;
        }
    }

    to_yaml(&entries)
}

/// Fetches the top-level list for either a page id or a space key.
///
/// `id` takes precedence over `space`. Returns an error if neither is set.
async fn fetch_top_level(
    api: &ConfluenceApi,
    id: Option<&str>,
    space: Option<&str>,
) -> Result<Vec<ChildPage>> {
    if let Some(page_id) = id {
        return api.get_children(page_id).await;
    }
    let space_key = space.context("Provide either `id` or `space`")?;
    let space_id = api.resolve_space_id(space_key).await?;
    api.get_space_root_pages(&space_id).await
}

/// Whether recursion should continue at the given depth.
fn should_recurse(depth: u32, max_depth: u32) -> bool {
    max_depth == 0 || depth < max_depth
}

/// Converts `ChildPage` values into `ChildrenEntry`, filling in a
/// missing `space_key` from the provided key when present.
fn to_entries(pages: Vec<ChildPage>, space_key: Option<&str>) -> Vec<ChildrenEntry> {
    let mut entries = Vec::with_capacity(pages.len());
    for mut page in pages {
        if page.space_key.is_none() {
            page.space_key = space_key.map(str::to_string);
        }
        entries.push(ChildrenEntry::from(page));
    }
    entries
}

/// Recursively fetches descendants and populates the `children` field.
fn populate_descendants<'a>(
    api: &'a ConfluenceApi,
    entry: &'a mut ChildrenEntry,
    depth: u32,
    max_depth: u32,
    space_key: Option<&'a str>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> {
    Box::pin(async move {
        if !should_recurse(depth, max_depth) {
            return Ok(());
        }
        entry.children = to_entries(api.get_children(&entry.id).await?, space_key);
        for child in &mut entry.children {
            populate_descendants(api, child, depth + 1, max_depth, space_key).await?;
        }
        Ok(())
    })
}

/// Builds the YAML output for the `confluence_comment_list` tool.
///
/// `limit` of 0 returns every comment; otherwise the list is truncated to
/// the requested size (matching the CLI `--limit` semantics).
pub async fn list_comments_yaml(api: &ConfluenceApi, id: &str, limit: usize) -> Result<String> {
    let mut comments = api.get_page_comments(id).await?;
    if limit > 0 {
        comments.truncate(limit);
    }
    to_yaml(&comments)
}

/// Posts a comment to a Confluence page.
///
/// The markdown `content` is converted to ADF before posting.
pub async fn add_comment_result(api: &ConfluenceApi, id: &str, content: &str) -> Result<String> {
    let adf: AdfDocument = markdown_to_adf(content).context("Failed to convert markdown to ADF")?;
    api.add_page_comment(id, &adf).await?;

    let result = MutationResult {
        ok: true,
        message: format!("Comment added to page {id}."),
        id,
        labels: &[],
    };
    to_yaml(&result)
}

/// Builds the YAML output for the `confluence_label_list` tool.
pub async fn list_labels_yaml(api: &ConfluenceApi, id: &str, limit: usize) -> Result<String> {
    let mut labels = api.get_labels(id).await?;
    if limit > 0 {
        labels.truncate(limit);
    }
    to_yaml(&labels)
}

/// Adds labels to a Confluence page and returns a YAML confirmation.
pub async fn add_labels_result(api: &ConfluenceApi, id: &str, labels: &[String]) -> Result<String> {
    if labels.is_empty() {
        anyhow::bail!("`labels` must contain at least one label");
    }

    api.add_labels(id, labels).await?;
    let result = MutationResult {
        ok: true,
        message: format!("Added {} label(s) to page {id}.", labels.len()),
        id,
        labels,
    };
    to_yaml(&result)
}

/// Removes labels from a Confluence page and returns a YAML confirmation.
pub async fn remove_labels_result(
    api: &ConfluenceApi,
    id: &str,
    labels: &[String],
) -> Result<String> {
    if labels.is_empty() {
        anyhow::bail!("`labels` must contain at least one label");
    }

    for label in labels {
        api.remove_label(id, label).await?;
    }

    let result = MutationResult {
        ok: true,
        message: format!("Removed {} label(s) from page {id}.", labels.len()),
        id,
        labels,
    };
    to_yaml(&result)
}

/// Builds the YAML output for the `confluence_user_search` tool.
///
/// `limit` of `None` defaults to 25, matching the CLI. A limit of `0`
/// requests every match.
pub async fn search_users_yaml(
    client: &AtlassianClient,
    query: &str,
    limit: u32,
) -> Result<String> {
    let results = client.search_confluence_users(query, limit).await?;
    to_yaml(&results)
}

// ── Tool handlers ────────────────────────────────────────────────────

#[allow(missing_docs)] // #[tool_router] generates a pub `confluence_tool_router` fn.
#[tool_router(router = confluence_tool_router, vis = "pub")]
impl OmniDevServer {
    /// Tool: fetch a Confluence page as JFM markdown (default) or ADF JSON.
    #[tool(
        description = "Fetch a Confluence page by ID. Returns JFM markdown by default, or raw ADF JSON when format=\"adf\". \
                       When `output_file` is set, the content is written to that path and the tool returns \
                       a short YAML summary (path/bytes/format) — useful for large pages. \
                       Mirrors `omni-dev atlassian confluence read`."
    )]
    pub async fn confluence_read(
        &self,
        Parameters(params): Parameters<ConfluenceReadParams>,
    ) -> Result<CallToolResult, McpError> {
        let format = parse_format(params.format.as_deref()).map_err(tool_error)?;
        let rendered = run_confluence_read(&params.id, format, params.output_file.as_deref())
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(rendered)]))
    }

    /// Tool: search Confluence pages by CQL.
    #[tool(
        description = "Search Confluence pages using CQL. Returns YAML with matching page IDs, titles, and space keys. \
                       Mirrors `omni-dev atlassian confluence search --cql`."
    )]
    pub async fn confluence_search(
        &self,
        Parameters(params): Parameters<ConfluenceSearchParams>,
    ) -> Result<CallToolResult, McpError> {
        let yaml = run_confluence_search(&params.cql, params.limit.unwrap_or(20))
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(yaml)]))
    }

    /// Tool: create a new Confluence page.
    #[tool(
        description = "Create a new Confluence page. Returns the new page's ID. \
                       Mirrors `omni-dev atlassian confluence create`."
    )]
    pub async fn confluence_create(
        &self,
        Parameters(params): Parameters<ConfluenceCreateParams>,
    ) -> Result<CallToolResult, McpError> {
        let format = parse_format(params.format.as_deref()).map_err(tool_error)?;
        let page_id = run_confluence_create(&params, format)
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(page_id)]))
    }

    /// Tool: update a Confluence page's body (and optionally title).
    #[tool(description = "Overwrite a Confluence page's body. \
                       Accepts JFM markdown (default) or ADF JSON. \
                       Mirrors `omni-dev atlassian confluence write --force`.")]
    pub async fn confluence_write(
        &self,
        Parameters(params): Parameters<ConfluenceWriteParams>,
    ) -> Result<CallToolResult, McpError> {
        let format = parse_format(params.format.as_deref()).map_err(tool_error)?;
        run_confluence_write(&params.id, &params.content, format)
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "Updated {}",
            params.id
        ))]))
    }

    /// Tool: delete a Confluence page. Destructive — requires `confirm: true`.
    #[tool(
        description = "Delete a Confluence page. IRREVERSIBLE. Requires the caller to pass `confirm: true` \
                       to prevent accidental deletions. Set `purge: true` to permanently purge instead of \
                       moving to trash (requires space admin). Mirrors `omni-dev atlassian confluence delete --force`."
    )]
    pub async fn confluence_delete(
        &self,
        Parameters(params): Parameters<ConfluenceDeleteParams>,
    ) -> Result<CallToolResult, McpError> {
        run_confluence_delete(&params).await.map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "Deleted page {}",
            params.id
        ))]))
    }

    /// Tool: recursively download a Confluence page tree.
    #[tool(
        description = "Recursively download a Confluence page or an entire space into a directory. \
                       Either `id` (root page) or `space` (space key) must be provided. \
                       Returns a YAML manifest summary of downloaded pages. \
                       Mirrors `omni-dev atlassian confluence download`."
    )]
    pub async fn confluence_download(
        &self,
        Parameters(params): Parameters<ConfluenceDownloadParams>,
    ) -> Result<CallToolResult, McpError> {
        let summary = run_confluence_download(params).await.map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(summary)]))
    }

    /// Lists children of a Confluence page, or top-level pages in a space,
    /// with optional recursion.
    #[tool(
        description = "List children of a Confluence page, or top-level pages in a space. \
                       Supports optional recursion with a max depth. Mirrors \
                       `omni-dev atlassian confluence children`."
    )]
    pub async fn confluence_children(
        &self,
        Parameters(params): Parameters<ConfluenceChildrenParams>,
    ) -> Result<CallToolResult, McpError> {
        let (client, _url) = create_client().map_err(tool_error)?;
        let api = ConfluenceApi::new(client);
        let yaml = fetch_children_yaml(
            &api,
            params.id.as_deref(),
            params.space.as_deref(),
            params.recursive.unwrap_or(false),
            params.max_depth.unwrap_or(0),
        )
        .await
        .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(yaml)]))
    }

    /// Lists footer comments on a Confluence page.
    #[tool(
        description = "List footer comments on a Confluence page (auto-paginated). \
                       `limit` of 0 returns every comment. Mirrors \
                       `omni-dev atlassian confluence comment list`."
    )]
    pub async fn confluence_comment_list(
        &self,
        Parameters(params): Parameters<ConfluenceCommentListParams>,
    ) -> Result<CallToolResult, McpError> {
        let (client, _url) = create_client().map_err(tool_error)?;
        let api = ConfluenceApi::new(client);
        let yaml = list_comments_yaml(&api, &params.id, params.limit.unwrap_or(25))
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(yaml)]))
    }

    /// Posts a comment to a Confluence page.
    #[tool(
        description = "Post a markdown comment to a Confluence page. The content is \
                       converted to ADF before posting. Mirrors \
                       `omni-dev atlassian confluence comment add`."
    )]
    pub async fn confluence_comment_add(
        &self,
        Parameters(params): Parameters<ConfluenceCommentAddParams>,
    ) -> Result<CallToolResult, McpError> {
        let (client, _url) = create_client().map_err(tool_error)?;
        let api = ConfluenceApi::new(client);
        let yaml = add_comment_result(&api, &params.id, &params.content)
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(yaml)]))
    }

    /// Lists labels on a Confluence page.
    #[tool(description = "List labels on a Confluence page (auto-paginated). \
                       `limit` of 0 returns every label. Mirrors \
                       `omni-dev atlassian confluence label list`.")]
    pub async fn confluence_label_list(
        &self,
        Parameters(params): Parameters<ConfluenceLabelListParams>,
    ) -> Result<CallToolResult, McpError> {
        let (client, _url) = create_client().map_err(tool_error)?;
        let api = ConfluenceApi::new(client);
        let yaml = list_labels_yaml(&api, &params.id, params.limit.unwrap_or(0))
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(yaml)]))
    }

    /// Adds labels to a Confluence page.
    #[tool(description = "Add one or more labels to a Confluence page. Mirrors \
                       `omni-dev atlassian confluence label add`.")]
    pub async fn confluence_label_add(
        &self,
        Parameters(params): Parameters<ConfluenceLabelAddParams>,
    ) -> Result<CallToolResult, McpError> {
        let (client, _url) = create_client().map_err(tool_error)?;
        let api = ConfluenceApi::new(client);
        let yaml = add_labels_result(&api, &params.id, &params.labels)
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(yaml)]))
    }

    /// Removes labels from a Confluence page.
    #[tool(
        description = "Remove one or more labels from a Confluence page. Mirrors \
                       `omni-dev atlassian confluence label remove`."
    )]
    pub async fn confluence_label_remove(
        &self,
        Parameters(params): Parameters<ConfluenceLabelRemoveParams>,
    ) -> Result<CallToolResult, McpError> {
        let (client, _url) = create_client().map_err(tool_error)?;
        let api = ConfluenceApi::new(client);
        let yaml = remove_labels_result(&api, &params.id, &params.labels)
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(yaml)]))
    }

    /// Searches Confluence users by display name or email.
    #[tool(
        description = "Search Confluence users by display name or email. `limit` of 0 \
                       returns every match; defaults to 25. Mirrors \
                       `omni-dev atlassian confluence user search`."
    )]
    pub async fn confluence_user_search(
        &self,
        Parameters(params): Parameters<ConfluenceUserSearchParams>,
    ) -> Result<CallToolResult, McpError> {
        let (client, _url) = create_client().map_err(tool_error)?;
        let yaml = search_users_yaml(&client, &params.query, params.limit.unwrap_or(25))
            .await
            .map_err(tool_error)?;
        Ok(CallToolResult::success(vec![Content::text(yaml)]))
    }
}

// ── Internal run_* helpers ──────────────────────────────────────────

async fn run_confluence_read(
    id: &str,
    format: ContentFormat,
    output_file: Option<&str>,
) -> Result<String> {
    let (client, instance_url) = create_client()?;
    let api = ConfluenceApi::new(client);
    let item = api.get_content(id).await?;
    let label = format_label(&format);
    let rendered = render_content_item(&item, format, &instance_url)?;
    match output_file {
        Some(path) => write_to_file_yaml(path, &rendered, label),
        None => Ok(rendered),
    }
}

/// String label for a [`ContentFormat`], used in write summaries.
fn format_label(format: &ContentFormat) -> &'static str {
    match format {
        ContentFormat::Jfm => "jfm",
        ContentFormat::Adf => "adf",
    }
}

async fn run_confluence_search(cql: &str, limit: u32) -> Result<String> {
    let (client, _instance_url) = create_client()?;
    let result = client.search_confluence(cql, limit).await?;
    serialize_search_results(&result)
}

async fn run_confluence_create(
    params: &ConfluenceCreateParams,
    format: ContentFormat,
) -> Result<String> {
    let adf = match format {
        ContentFormat::Jfm => markdown_to_adf(&params.content)?,
        ContentFormat::Adf => AdfDocument::from_json_str(&params.content)?,
    };

    let (client, _instance_url) = create_client()?;
    let api = ConfluenceApi::new(client);
    let id = api
        .create_page(
            &params.space_key,
            &params.title,
            &adf,
            params.parent_id.as_deref(),
        )
        .await?;
    Ok(id)
}

async fn run_confluence_write(id: &str, content: &str, format: ContentFormat) -> Result<()> {
    let (adf, title) = parse_write_content(content, format)?;
    let (client, _instance_url) = create_client()?;
    let api = ConfluenceApi::new(client);
    let title_ref = if title.is_empty() {
        None
    } else {
        Some(title.as_str())
    };
    api.update_content(id, &adf, title_ref).await
}

async fn run_confluence_delete(params: &ConfluenceDeleteParams) -> Result<()> {
    if !params.confirm {
        anyhow::bail!("confluence_delete is irreversible — pass `confirm: true` to proceed.");
    }
    let (client, _instance_url) = create_client()?;
    let api = ConfluenceApi::new(client);
    api.delete_page(&params.id, params.purge.unwrap_or(false))
        .await
}

async fn run_confluence_download(params: ConfluenceDownloadParams) -> Result<String> {
    if params.id.is_none() && params.space.is_none() {
        anyhow::bail!("confluence_download requires either `id` or `space`");
    }

    let (client, instance_url) = create_client()?;
    let api = Arc::new(ConfluenceApi::new(client));

    // Hold the TempDir guard (if any) across the entire download so the
    // directory is not deleted before the manifest is read.
    let (output_dir, _guard) = resolve_output_dir(params.output_dir)?;
    let format = parse_format(params.format.as_deref())?;

    let download_params = DownloadParams {
        id: params.id,
        space: params.space,
        output_dir: output_dir.clone(),
        format,
        concurrency: params.concurrency.unwrap_or(8),
        max_depth: params.max_depth.unwrap_or(0),
        title_filter: params.title_filter,
        resume: false,
        on_conflict: OnConflict::Overwrite,
        instance_url,
    };

    run_download(&api, &download_params).await?;
    build_download_summary(&output_dir)
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::await_holding_lock // env lock intentionally held across await on a single-thread runtime
)]
mod tests {
    use super::*;

    use crate::atlassian::auth::{ATLASSIAN_API_TOKEN, ATLASSIAN_EMAIL, ATLASSIAN_INSTANCE_URL};

    /// Serialize env-backed tests — `create_client()` reads process-wide
    /// environment variables, so concurrent tests would race without a lock.
    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
        use std::sync::Mutex;
        static LOCK: Mutex<()> = Mutex::new(());
        LOCK.lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    struct EnvGuard;

    impl EnvGuard {
        fn set(instance_url: &str) -> Self {
            std::env::set_var(ATLASSIAN_INSTANCE_URL, instance_url);
            std::env::set_var(ATLASSIAN_EMAIL, "user@test.com");
            std::env::set_var(ATLASSIAN_API_TOKEN, "fake-token");
            Self
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            std::env::remove_var(ATLASSIAN_INSTANCE_URL);
            std::env::remove_var(ATLASSIAN_EMAIL);
            std::env::remove_var(ATLASSIAN_API_TOKEN);
        }
    }

    // ── parse_format ────────────────────────────────────────────────

    #[test]
    fn parse_format_default_is_jfm() {
        assert!(matches!(parse_format(None).unwrap(), ContentFormat::Jfm));
    }

    #[test]
    fn parse_format_jfm_case_insensitive() {
        assert!(matches!(
            parse_format(Some("JFM")).unwrap(),
            ContentFormat::Jfm
        ));
    }

    #[test]
    fn parse_format_adf() {
        assert!(matches!(
            parse_format(Some("adf")).unwrap(),
            ContentFormat::Adf
        ));
    }

    #[test]
    fn parse_format_invalid_errors() {
        let err = parse_format(Some("xml")).unwrap_err();
        assert!(err.to_string().contains("Invalid format"));
    }

    // ── parse_write_content ────────────────────────────────────────

    #[test]
    fn parse_write_content_jfm_without_frontmatter_yields_empty_title() {
        let (adf, title) = parse_write_content("Hello world", ContentFormat::Jfm).unwrap();
        assert!(title.is_empty());
        assert!(!adf.content.is_empty());
    }

    #[test]
    fn parse_write_content_jfm_with_frontmatter_extracts_title() {
        let input = "---\ntype: confluence\ninstance: https://org.atlassian.net\ntitle: My Page\nspace_key: ENG\n---\n\nBody\n";
        let (adf, title) = parse_write_content(input, ContentFormat::Jfm).unwrap();
        assert_eq!(title, "My Page");
        assert!(!adf.content.is_empty());
    }

    #[test]
    fn parse_write_content_jfm_with_jira_frontmatter_uses_summary() {
        let input = "---\ntype: jira\ninstance: https://org.atlassian.net\nkey: PROJ-1\nsummary: Jira Summary\n---\n\nBody\n";
        let (_adf, title) = parse_write_content(input, ContentFormat::Jfm).unwrap();
        assert_eq!(title, "Jira Summary");
    }

    #[test]
    fn parse_write_content_adf_roundtrips() {
        let adf_json = r#"{"version":1,"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hi"}]}]}"#;
        let (adf, title) = parse_write_content(adf_json, ContentFormat::Adf).unwrap();
        assert!(title.is_empty());
        assert_eq!(adf.content.len(), 1);
    }

    #[test]
    fn parse_write_content_adf_invalid_errors() {
        assert!(parse_write_content("not json", ContentFormat::Adf).is_err());
    }

    // ── build_download_summary ─────────────────────────────────────

    #[test]
    fn build_download_summary_missing_manifest_is_empty() {
        let tmp = tempfile::tempdir().unwrap();
        let yaml = build_download_summary(tmp.path()).unwrap();
        assert!(yaml.contains("page_count: 0"));
    }

    #[test]
    fn build_download_summary_reads_manifest() {
        let tmp = tempfile::tempdir().unwrap();
        let manifest = serde_json::json!({
            "12345": {"title": "Root Page", "path": "12345-root-page/index.md"},
            "67890": {"title": "Child", "path": "12345-root-page/67890-child/index.md", "parent_id": "12345"}
        });
        std::fs::write(
            tmp.path().join("manifest.json"),
            serde_json::to_string(&manifest).unwrap(),
        )
        .unwrap();

        let yaml = build_download_summary(tmp.path()).unwrap();
        assert!(yaml.contains("page_count: 2"));
        assert!(yaml.contains("Root Page"));
        assert!(yaml.contains("Child"));
    }

    #[test]
    fn build_download_summary_corrupt_manifest_errors() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("manifest.json"), "not json").unwrap();
        assert!(build_download_summary(tmp.path()).is_err());
    }

    // ── resolve_output_dir ─────────────────────────────────────────

    #[test]
    fn resolve_output_dir_creates_tempdir_when_absent() {
        let (path, guard) = resolve_output_dir(None).unwrap();
        assert!(path.exists());
        assert!(guard.is_some(), "tempdir guard must be returned");
    }

    #[test]
    fn resolve_output_dir_uses_provided_path() {
        let tmp = tempfile::tempdir().unwrap();
        let requested = tmp.path().join("sub");
        let (path, guard) =
            resolve_output_dir(Some(requested.to_string_lossy().to_string())).unwrap();
        assert_eq!(path, requested);
        assert!(path.exists());
        assert!(guard.is_none());
    }

    // ── serialize_search_results ───────────────────────────────────

    #[test]
    fn serialize_search_results_emits_yaml() {
        use crate::atlassian::client::{ConfluenceSearchResult, ConfluenceSearchResults};
        let results = ConfluenceSearchResults {
            results: vec![ConfluenceSearchResult {
                id: "12345".to_string(),
                title: "Architecture".to_string(),
                space_key: "ENG".to_string(),
            }],
            total: 1,
        };
        let yaml = serialize_search_results(&results).unwrap();
        assert!(yaml.contains("12345"));
        assert!(yaml.contains("ENG"));
        assert!(yaml.contains("total: 1"));
    }

    // ── render_content_item ────────────────────────────────────────

    #[test]
    fn render_content_item_jfm_and_adf() {
        use crate::atlassian::api::{ContentItem, ContentMetadata};

        let item = ContentItem {
            id: "12345".to_string(),
            title: "Page".to_string(),
            body_adf: Some(serde_json::json!({
                "version": 1,
                "type": "doc",
                "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hi"}]}]
            })),
            metadata: ContentMetadata::Confluence {
                space_key: "ENG".to_string(),
                status: Some("current".to_string()),
                version: Some(1),
                parent_id: None,
            },
        };

        let jfm =
            render_content_item(&item, ContentFormat::Jfm, "https://org.atlassian.net").unwrap();
        assert!(
            jfm.contains("12345"),
            "expected page id in JFM output: {jfm}"
        );
        assert!(jfm.contains("page_id"), "expected page_id field: {jfm}");

        let adf =
            render_content_item(&item, ContentFormat::Adf, "https://org.atlassian.net").unwrap();
        assert!(adf.contains("\"doc\""));
    }

    #[test]
    fn render_content_item_adf_null_body() {
        use crate::atlassian::api::{ContentItem, ContentMetadata};
        let item = ContentItem {
            id: "1".to_string(),
            title: "t".to_string(),
            body_adf: None,
            metadata: ContentMetadata::Confluence {
                space_key: "S".to_string(),
                status: None,
                version: None,
                parent_id: None,
            },
        };
        let adf = render_content_item(&item, ContentFormat::Adf, "https://org").unwrap();
        assert!(adf.contains("null"));
    }

    // ── run_confluence_read ────────────────────────────────────────

    async fn mock_page(server: &wiremock::MockServer, id: &str) {
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(format!("/wiki/api/v2/pages/{id}")))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": id,
                "title": "Mock Page",
                "status": "current",
                "spaceId": "98765",
                "version": {"number": 1},
                "body": {
                    "atlas_doc_format": {
                        "value": "{\"version\":1,\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"Mocked\"}]}]}"
                    }
                }
            })))
            .mount(server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/98765"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"key": "ENG"})),
            )
            .mount(server)
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_read_jfm_success() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        mock_page(&server, "12345").await;
        let _env = EnvGuard::set(&server.uri());

        let out = run_confluence_read("12345", ContentFormat::Jfm, None)
            .await
            .unwrap();
        assert!(out.contains("Mocked"));
        assert!(out.contains("page_id"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_read_adf_success() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        mock_page(&server, "12345").await;
        let _env = EnvGuard::set(&server.uri());

        let out = run_confluence_read("12345", ContentFormat::Adf, None)
            .await
            .unwrap();
        assert!(out.contains("\"doc\""));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_read_404_errors() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/99"))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let err = run_confluence_read("99", ContentFormat::Jfm, None)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("404"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_read_jfm_writes_to_output_file() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        mock_page(&server, "12345").await;
        let _env = EnvGuard::set(&server.uri());

        let tmp = tempfile::tempdir().unwrap();
        let out_path = tmp.path().join("page.md");
        let path_str = out_path.to_str().unwrap();

        let summary = run_confluence_read("12345", ContentFormat::Jfm, Some(path_str))
            .await
            .unwrap();

        assert!(summary.contains(&format!("path: {path_str}")));
        assert!(summary.contains("format: jfm"));
        assert!(summary.contains("bytes:"));
        // Inline content must NOT leak into the summary.
        assert!(!summary.contains("Mocked"));

        let written = std::fs::read_to_string(&out_path).unwrap();
        assert!(written.contains("Mocked"));
        assert!(written.contains("page_id"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_read_adf_writes_to_output_file() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        mock_page(&server, "12345").await;
        let _env = EnvGuard::set(&server.uri());

        let tmp = tempfile::tempdir().unwrap();
        let out_path = tmp.path().join("page.json");
        let path_str = out_path.to_str().unwrap();

        let summary = run_confluence_read("12345", ContentFormat::Adf, Some(path_str))
            .await
            .unwrap();

        assert!(summary.contains("format: adf"));
        let written = std::fs::read_to_string(&out_path).unwrap();
        assert!(written.contains("\"doc\""));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_read_output_file_invalid_path_errors() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        mock_page(&server, "12345").await;
        let _env = EnvGuard::set(&server.uri());

        let err = run_confluence_read(
            "12345",
            ContentFormat::Jfm,
            Some("/nonexistent_dir_zxq/out.md"),
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("Failed to write"));
    }

    #[test]
    fn format_label_matches_expected_strings() {
        assert_eq!(format_label(&ContentFormat::Jfm), "jfm");
        assert_eq!(format_label(&ContentFormat::Adf), "adf");
    }

    /// Mocks a Confluence page whose body ADF is a JSON string instead of an
    /// ADF document — parses past the API layer (the API just stores the
    /// `Value`) but fails inside `content_item_to_document`, exercising the
    /// `?` partial on `render_content_item(...)?` in [`run_confluence_read`].
    async fn mock_page_with_bad_adf(server: &wiremock::MockServer, id: &str) {
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(format!("/wiki/api/v2/pages/{id}")))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": id,
                    "title": "Bad ADF",
                    "status": "current",
                    "spaceId": "98765",
                    "version": {"number": 1},
                    "body": {
                        "atlas_doc_format": {
                            "value": "\"this is a JSON string, not an ADF doc\""
                        }
                    }
                })),
            )
            .mount(server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/98765"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"key": "ENG"})),
            )
            .mount(server)
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_read_propagates_render_error() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        mock_page_with_bad_adf(&server, "12345").await;
        let _env = EnvGuard::set(&server.uri());

        let err = run_confluence_read("12345", ContentFormat::Jfm, None)
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("Failed to parse ADF"),
            "got: {err}"
        );
    }

    // ── run_confluence_search ──────────────────────────────────────

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_search_returns_yaml() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/rest/api/content/search"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [{
                        "id": "12345",
                        "title": "Arch",
                        "space": {"key": "ENG"}
                    }],
                    "totalSize": 1
                })),
            )
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let yaml = run_confluence_search("space = ENG", 20).await.unwrap();
        assert!(yaml.contains("12345"));
        assert!(yaml.contains("Arch"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_search_400_errors() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/rest/api/content/search"))
            .respond_with(wiremock::ResponseTemplate::new(400).set_body_string("bad cql"))
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let err = run_confluence_search("bogus", 20).await.unwrap_err();
        assert!(err.to_string().contains("400"));
    }

    // ── run_confluence_create ──────────────────────────────────────

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_create_jfm_success() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": [{"id": "98765"}]})),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "54321"})),
            )
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let params = ConfluenceCreateParams {
            space_key: "ENG".to_string(),
            title: "New Page".to_string(),
            content: "Body".to_string(),
            parent_id: None,
            format: None,
        };
        let id = run_confluence_create(&params, ContentFormat::Jfm)
            .await
            .unwrap();
        assert_eq!(id, "54321");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_create_adf_success() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": [{"id": "98765"}]})),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "999"})),
            )
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let params = ConfluenceCreateParams {
            space_key: "ENG".to_string(),
            title: "ADF Page".to_string(),
            content: r#"{"version":1,"type":"doc","content":[]}"#.to_string(),
            parent_id: Some("11111".to_string()),
            format: Some("adf".to_string()),
        };
        let id = run_confluence_create(&params, ContentFormat::Adf)
            .await
            .unwrap();
        assert_eq!(id, "999");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_create_invalid_adf_errors() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        let _env = EnvGuard::set(&server.uri());

        let params = ConfluenceCreateParams {
            space_key: "ENG".to_string(),
            title: "Bad".to_string(),
            content: "not json".to_string(),
            parent_id: None,
            format: Some("adf".to_string()),
        };
        assert!(run_confluence_create(&params, ContentFormat::Adf)
            .await
            .is_err());
    }

    // ── run_confluence_write ───────────────────────────────────────

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_write_jfm_success() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        // GET to fetch current version
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "12345",
                "title": "Old",
                "status": "current",
                "spaceId": "98765",
                "version": {"number": 3},
                "body": {"atlas_doc_format": {"value": "{\"version\":1,\"type\":\"doc\",\"content\":[]}"}}
            })))
            .mount(&server)
            .await;
        // PUT to update
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let result = run_confluence_write("12345", "New body", ContentFormat::Jfm).await;
        assert!(result.is_ok(), "got: {result:?}");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_write_adf_success() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "12345",
                "title": "Old",
                "status": "current",
                "spaceId": "98765",
                "version": {"number": 3},
                "body": {"atlas_doc_format": {"value": "{\"version\":1,\"type\":\"doc\",\"content\":[]}"}}
            })))
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let adf_json = r#"{"version":1,"type":"doc","content":[]}"#;
        let result = run_confluence_write("12345", adf_json, ContentFormat::Adf).await;
        assert!(result.is_ok(), "got: {result:?}");
    }

    // ── run_confluence_delete ──────────────────────────────────────

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_delete_requires_confirm() {
        let params = ConfluenceDeleteParams {
            id: "12345".to_string(),
            confirm: false,
            purge: None,
        };
        let err = run_confluence_delete(&params).await.unwrap_err();
        assert!(err.to_string().contains("confirm"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_delete_success() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(204))
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let params = ConfluenceDeleteParams {
            id: "12345".to_string(),
            confirm: true,
            purge: None,
        };
        assert!(run_confluence_delete(&params).await.is_ok());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_delete_purge_success() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .and(wiremock::matchers::query_param("purge", "true"))
            .respond_with(wiremock::ResponseTemplate::new(204))
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let params = ConfluenceDeleteParams {
            id: "12345".to_string(),
            confirm: true,
            purge: Some(true),
        };
        assert!(run_confluence_delete(&params).await.is_ok());
    }

    // ── run_confluence_download ────────────────────────────────────

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_download_requires_id_or_space() {
        let params = ConfluenceDownloadParams {
            id: None,
            space: None,
            output_dir: None,
            title_filter: None,
            concurrency: None,
            max_depth: None,
            format: None,
        };
        let err = run_confluence_download(params).await.unwrap_err();
        assert!(err.to_string().contains("`id` or `space`"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_download_single_page_returns_manifest() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;

        // Root page lookup
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "12345",
                "title": "Root Page",
                "status": "current",
                "spaceId": "98765",
                "version": {"number": 1},
                "body": {"atlas_doc_format": {"value": "{\"version\":1,\"type\":\"doc\",\"content\":[]}"}}
            })))
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/98765"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"key": "ENG"})),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/12345/child/page",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        let _env = EnvGuard::set(&server.uri());
        let tmp = tempfile::tempdir().unwrap();

        let params = ConfluenceDownloadParams {
            id: Some("12345".to_string()),
            space: None,
            output_dir: Some(tmp.path().to_string_lossy().to_string()),
            title_filter: None,
            concurrency: Some(1),
            max_depth: None,
            format: None,
        };

        let summary = run_confluence_download(params).await.unwrap();
        assert!(summary.contains("page_count: 1"));
        assert!(summary.contains("Root Page"));
    }

    // ── run_confluence_write JFM with frontmatter (covers title.as_str() branch) ────

    #[tokio::test(flavor = "current_thread")]
    async fn run_confluence_write_jfm_with_frontmatter_sends_title() {
        let _lock = env_lock();
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "12345",
                "title": "Old",
                "status": "current",
                "spaceId": "98765",
                "version": {"number": 3},
                "body": {"atlas_doc_format": {"value": "{\"version\":1,\"type\":\"doc\",\"content\":[]}"}}
            })))
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
            .mount(&server)
            .await;
        let _env = EnvGuard::set(&server.uri());

        let content = "---\ntype: confluence\ninstance: https://org.atlassian.net\npage_id: '12345'\ntitle: New Title\nspace_key: ENG\n---\n\nBody\n";
        let result = run_confluence_write("12345", content, ContentFormat::Jfm).await;
        assert!(result.is_ok(), "got: {result:?}");
    }

    // ── Tool handler bodies (direct invocation via Parameters) ────

    use rmcp::handler::server::wrapper::Parameters;

    fn make_server() -> OmniDevServer {
        OmniDevServer::new()
    }

    /// Clear env vars so `create_client()` fails cleanly — lets us drive the
    /// tool handler body all the way through the error path.
    fn clear_env() {
        std::env::remove_var(ATLASSIAN_INSTANCE_URL);
        std::env::remove_var(ATLASSIAN_EMAIL);
        std::env::remove_var(ATLASSIAN_API_TOKEN);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_read_handler_invalid_format_returns_tool_error() {
        let server = make_server();
        let params = ConfluenceReadParams {
            id: "12345".to_string(),
            format: Some("xml".to_string()),
            output_file: None,
        };
        let result = server.confluence_read(Parameters(params)).await;
        let err = result.unwrap_err();
        assert!(
            err.message.contains("Invalid format"),
            "got: {}",
            err.message
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_read_handler_success_path_via_mock() {
        let _lock = env_lock();
        let srv = wiremock::MockServer::start().await;
        mock_page(&srv, "12345").await;
        let _env = EnvGuard::set(&srv.uri());

        let server = make_server();
        let result = server
            .confluence_read(Parameters(ConfluenceReadParams {
                id: "12345".to_string(),
                format: Some("jfm".to_string()),
                output_file: None,
            }))
            .await
            .unwrap();
        assert!(!result.is_error.unwrap_or(false));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_search_handler_success_path_via_mock() {
        let _lock = env_lock();
        let srv = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/rest/api/content/search"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": [], "totalSize": 0})),
            )
            .mount(&srv)
            .await;
        let _env = EnvGuard::set(&srv.uri());

        let server = make_server();
        let result = server
            .confluence_search(Parameters(ConfluenceSearchParams {
                cql: "type = page".to_string(),
                limit: None,
            }))
            .await
            .unwrap();
        assert!(!result.is_error.unwrap_or(false));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_search_handler_error_path() {
        let _lock = env_lock();
        clear_env();
        let server = make_server();
        let result = server
            .confluence_search(Parameters(ConfluenceSearchParams {
                cql: "type = page".to_string(),
                limit: Some(5),
            }))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_create_handler_invalid_format_returns_tool_error() {
        let server = make_server();
        let result = server
            .confluence_create(Parameters(ConfluenceCreateParams {
                space_key: "ENG".to_string(),
                title: "T".to_string(),
                content: "body".to_string(),
                parent_id: None,
                format: Some("xml".to_string()),
            }))
            .await;
        let err = result.unwrap_err();
        assert!(err.message.contains("Invalid format"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_create_handler_error_path_without_credentials() {
        let _lock = env_lock();
        clear_env();
        let server = make_server();
        let result = server
            .confluence_create(Parameters(ConfluenceCreateParams {
                space_key: "ENG".to_string(),
                title: "T".to_string(),
                content: "body".to_string(),
                parent_id: None,
                format: None,
            }))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_create_handler_success_path_via_mock() {
        let _lock = env_lock();
        let srv = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": [{"id": "98765"}]})),
            )
            .mount(&srv)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "54321"})),
            )
            .mount(&srv)
            .await;
        let _env = EnvGuard::set(&srv.uri());

        let server = make_server();
        let result = server
            .confluence_create(Parameters(ConfluenceCreateParams {
                space_key: "ENG".to_string(),
                title: "T".to_string(),
                content: "Body".to_string(),
                parent_id: None,
                format: None,
            }))
            .await
            .unwrap();
        assert!(!result.is_error.unwrap_or(false));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_write_handler_success_path_via_mock() {
        let _lock = env_lock();
        let srv = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "12345",
                "title": "Old",
                "status": "current",
                "spaceId": "98765",
                "version": {"number": 3},
                "body": {"atlas_doc_format": {"value": "{\"version\":1,\"type\":\"doc\",\"content\":[]}"}}
            })))
            .mount(&srv)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
            .mount(&srv)
            .await;
        let _env = EnvGuard::set(&srv.uri());

        let server = make_server();
        let result = server
            .confluence_write(Parameters(ConfluenceWriteParams {
                id: "12345".to_string(),
                content: "New body".to_string(),
                format: None,
            }))
            .await
            .unwrap();
        assert!(!result.is_error.unwrap_or(false));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_write_handler_invalid_format_returns_tool_error() {
        let server = make_server();
        let result = server
            .confluence_write(Parameters(ConfluenceWriteParams {
                id: "12345".to_string(),
                content: "body".to_string(),
                format: Some("xml".to_string()),
            }))
            .await;
        let err = result.unwrap_err();
        assert!(err.message.contains("Invalid format"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_write_handler_error_path_without_credentials() {
        let _lock = env_lock();
        clear_env();
        let server = make_server();
        let result = server
            .confluence_write(Parameters(ConfluenceWriteParams {
                id: "12345".to_string(),
                content: "body".to_string(),
                format: None,
            }))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_delete_handler_success_message() {
        let _lock = env_lock();
        let srv = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(204))
            .mount(&srv)
            .await;
        let _env = EnvGuard::set(&srv.uri());

        let server = make_server();
        let result = server
            .confluence_delete(Parameters(ConfluenceDeleteParams {
                id: "12345".to_string(),
                confirm: true,
                purge: None,
            }))
            .await
            .unwrap();
        assert!(!result.is_error.unwrap_or(false));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_delete_handler_without_confirm_returns_tool_error() {
        let server = make_server();
        let result = server
            .confluence_delete(Parameters(ConfluenceDeleteParams {
                id: "12345".to_string(),
                confirm: false,
                purge: None,
            }))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_download_handler_missing_id_and_space_returns_tool_error() {
        let server = make_server();
        let result = server
            .confluence_download(Parameters(ConfluenceDownloadParams {
                id: None,
                space: None,
                output_dir: None,
                title_filter: None,
                concurrency: None,
                max_depth: None,
                format: None,
            }))
            .await;
        let err = result.unwrap_err();
        assert!(err.message.contains("`id` or `space`"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn confluence_download_handler_success_via_mock() {
        let _lock = env_lock();
        let srv = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "12345",
                "title": "Root",
                "status": "current",
                "spaceId": "98765",
                "version": {"number": 1},
                "body": {"atlas_doc_format": {"value": "{\"version\":1,\"type\":\"doc\",\"content\":[]}"}}
            })))
            .mount(&srv)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/98765"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"key": "ENG"})),
            )
            .mount(&srv)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/12345/child/page",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&srv)
            .await;
        let _env = EnvGuard::set(&srv.uri());

        let tmp = tempfile::tempdir().unwrap();
        let server = make_server();
        let result = server
            .confluence_download(Parameters(ConfluenceDownloadParams {
                id: Some("12345".to_string()),
                space: None,
                output_dir: Some(tmp.path().to_string_lossy().to_string()),
                title_filter: None,
                concurrency: Some(1),
                max_depth: None,
                format: None,
            }))
            .await
            .unwrap();
        assert!(!result.is_error.unwrap_or(false));
    }

    // ── router registration ────────────────────────────────────────

    #[test]
    fn tool_router_registers_all_confluence_tools() {
        let router = OmniDevServer::confluence_tool_router();
        for name in [
            "confluence_read",
            "confluence_search",
            "confluence_create",
            "confluence_write",
            "confluence_delete",
            "confluence_download",
            "confluence_children",
            "confluence_comment_list",
            "confluence_comment_add",
            "confluence_label_list",
            "confluence_label_add",
            "confluence_label_remove",
            "confluence_user_search",
        ] {
            assert!(router.has_route(name), "missing tool: {name}");
        }
    }

    // ── Phase 2d: children / comment / label / user-search tests ───

    fn phase2d_mock_client(uri: &str) -> AtlassianClient {
        AtlassianClient::new(uri, "user@test.com", "token").unwrap()
    }

    fn phase2d_mock_api(server: &wiremock::MockServer) -> ConfluenceApi {
        ConfluenceApi::new(phase2d_mock_client(&server.uri()))
    }

    // ── ChildrenEntry::from ────────────────────────────────────────

    #[test]
    fn children_entry_from_child_page_copies_fields() {
        let entry = ChildrenEntry::from(ChildPage {
            id: "1".to_string(),
            title: "Page".to_string(),
            status: "current".to_string(),
            parent_id: Some("100".to_string()),
            space_key: Some("ENG".to_string()),
        });
        assert_eq!(entry.id, "1");
        assert_eq!(entry.title, "Page");
        assert_eq!(entry.status, "current");
        assert_eq!(entry.parent_id.as_deref(), Some("100"));
        assert_eq!(entry.space_key.as_deref(), Some("ENG"));
        assert!(entry.children.is_empty());
    }

    #[test]
    fn children_entry_serialize_skips_empty() {
        let entry = ChildrenEntry {
            id: "1".to_string(),
            title: "P".to_string(),
            status: String::new(),
            parent_id: None,
            space_key: None,
            children: Vec::new(),
        };
        let json = serde_json::to_string(&entry).unwrap();
        assert!(!json.contains("status"));
        assert!(!json.contains("parent_id"));
        assert!(!json.contains("space_key"));
        assert!(!json.contains("children"));
    }

    // ── should_recurse ─────────────────────────────────────────────

    #[test]
    fn should_recurse_unlimited_when_max_is_zero() {
        assert!(should_recurse(1, 0));
        assert!(should_recurse(100, 0));
    }

    #[test]
    fn should_recurse_strictly_less_than_max() {
        assert!(should_recurse(1, 3));
        assert!(should_recurse(2, 3));
        assert!(!should_recurse(3, 3));
        assert!(!should_recurse(10, 3));
    }

    // ── to_entries ─────────────────────────────────────────────────

    #[test]
    fn to_entries_fills_missing_space_key() {
        let pages = vec![ChildPage {
            id: "1".to_string(),
            title: "P".to_string(),
            status: "current".to_string(),
            parent_id: None,
            space_key: None,
        }];
        let entries = to_entries(pages, Some("ENG"));
        assert_eq!(entries[0].space_key.as_deref(), Some("ENG"));
    }

    #[test]
    fn to_entries_preserves_existing_space_key() {
        let pages = vec![ChildPage {
            id: "1".to_string(),
            title: "P".to_string(),
            status: "current".to_string(),
            parent_id: None,
            space_key: Some("ORIG".to_string()),
        }];
        let entries = to_entries(pages, Some("OTHER"));
        assert_eq!(entries[0].space_key.as_deref(), Some("ORIG"));
    }

    #[test]
    fn to_entries_empty_input() {
        let entries = to_entries(Vec::new(), Some("ENG"));
        assert!(entries.is_empty());
    }

    // ── fetch_children_yaml ────────────────────────────────────────

    #[tokio::test]
    async fn fetch_children_yaml_requires_target() {
        let server = wiremock::MockServer::start().await;
        let api = phase2d_mock_api(&server);
        let err = fetch_children_yaml(&api, None, None, false, 0)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("Provide either"));
    }

    #[tokio::test]
    async fn fetch_children_yaml_by_id_non_recursive() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/100/child/page",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [
                        {"id": "1", "title": "Alpha", "status": "current"},
                        {"id": "2", "title": "Beta", "status": "current"}
                    ]
                })),
            )
            .mount(&server)
            .await;

        let yaml = fetch_children_yaml(&phase2d_mock_api(&server), Some("100"), None, false, 0)
            .await
            .unwrap();
        assert!(yaml.contains("Alpha"));
        assert!(yaml.contains("Beta"));
    }

    #[tokio::test]
    async fn fetch_children_yaml_by_space_propagates_space_key() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": [{"id": "77"}]})),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/77/pages"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [{"id": "1", "title": "Home", "status": "current"}]
                })),
            )
            .mount(&server)
            .await;

        let yaml = fetch_children_yaml(&phase2d_mock_api(&server), None, Some("ENG"), false, 0)
            .await
            .unwrap();
        assert!(yaml.contains("space_key: ENG"));
    }

    #[tokio::test]
    async fn fetch_children_yaml_recursive_respects_max_depth() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/1/child/page",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [{"id": "2", "title": "Child", "status": "current"}]
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/2/child/page",
            ))
            .respond_with(wiremock::ResponseTemplate::new(500))
            .expect(0)
            .mount(&server)
            .await;

        let yaml = fetch_children_yaml(&phase2d_mock_api(&server), Some("1"), None, true, 1)
            .await
            .unwrap();
        assert!(yaml.contains("Child"));
    }

    #[tokio::test]
    async fn fetch_children_yaml_recursive_walks_tree() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/1/child/page",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [{"id": "2", "title": "Mid", "status": "current"}]
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/2/child/page",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [{"id": "3", "title": "Leaf", "status": "current"}]
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/3/child/page",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        let yaml = fetch_children_yaml(&phase2d_mock_api(&server), Some("1"), None, true, 0)
            .await
            .unwrap();
        assert!(yaml.contains("Mid"));
        assert!(yaml.contains("Leaf"));
    }

    #[tokio::test]
    async fn fetch_children_yaml_api_error_propagates() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/99/child/page",
            ))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;

        let err = fetch_children_yaml(&phase2d_mock_api(&server), Some("99"), None, false, 0)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("404"));
    }

    // ── list_comments_yaml ─────────────────────────────────────────

    #[tokio::test]
    async fn list_comments_yaml_returns_yaml_sequence() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/footer-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [
                        {
                            "id": "c1",
                            "version": {"authorId": "alice", "createdAt": "2026-04-01T10:00:00Z"}
                        }
                    ]
                })),
            )
            .mount(&server)
            .await;

        let yaml = list_comments_yaml(&phase2d_mock_api(&server), "12345", 25)
            .await
            .unwrap();
        assert!(yaml.contains("id: c1"));
        assert!(yaml.contains("alice"));
    }

    #[tokio::test]
    async fn list_comments_yaml_unlimited_when_limit_zero() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/footer-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [
                        {"id": "c1", "version": {"authorId": "a", "createdAt": "t"}},
                        {"id": "c2", "version": {"authorId": "b", "createdAt": "t"}}
                    ]
                })),
            )
            .mount(&server)
            .await;

        let yaml = list_comments_yaml(&phase2d_mock_api(&server), "12345", 0)
            .await
            .unwrap();
        assert!(yaml.contains("id: c1"));
        assert!(yaml.contains("id: c2"));
    }

    #[tokio::test]
    async fn list_comments_yaml_truncates_to_limit() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/footer-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [
                        {"id": "c1", "version": {"authorId": "a", "createdAt": "t"}},
                        {"id": "c2", "version": {"authorId": "b", "createdAt": "t"}},
                        {"id": "c3", "version": {"authorId": "c", "createdAt": "t"}}
                    ]
                })),
            )
            .mount(&server)
            .await;

        let yaml = list_comments_yaml(&phase2d_mock_api(&server), "12345", 1)
            .await
            .unwrap();
        assert!(yaml.contains("id: c1"));
        assert!(!yaml.contains("id: c2"));
    }

    #[tokio::test]
    async fn list_comments_yaml_api_error_propagates() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/99/footer-comments",
            ))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;

        let err = list_comments_yaml(&phase2d_mock_api(&server), "99", 25)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("404"));
    }

    // ── add_comment_result ─────────────────────────────────────────

    #[tokio::test]
    async fn add_comment_result_converts_markdown_and_posts() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/footer-comments"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "c9"})),
            )
            .expect(1)
            .mount(&server)
            .await;

        let yaml = add_comment_result(&phase2d_mock_api(&server), "12345", "Hello **world**")
            .await
            .unwrap();
        assert!(yaml.contains("ok: true"));
        assert!(yaml.contains("id: '12345'") || yaml.contains("id: \"12345\""));
        assert!(yaml.contains("Comment added"));
    }

    #[tokio::test]
    async fn add_comment_result_api_error_propagates() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/footer-comments"))
            .respond_with(wiremock::ResponseTemplate::new(403).set_body_string("Forbidden"))
            .mount(&server)
            .await;

        let err = add_comment_result(&phase2d_mock_api(&server), "12345", "hello")
            .await
            .unwrap_err();
        assert!(err.to_string().contains("403"));
    }

    // ── list_labels_yaml ───────────────────────────────────────────

    #[tokio::test]
    async fn list_labels_yaml_returns_yaml_sequence() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345/labels"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [
                        {"id": "1", "name": "architecture", "prefix": "global"},
                        {"id": "2", "name": "draft", "prefix": "global"}
                    ]
                })),
            )
            .mount(&server)
            .await;

        let yaml = list_labels_yaml(&phase2d_mock_api(&server), "12345", 0)
            .await
            .unwrap();
        assert!(yaml.contains("architecture"));
        assert!(yaml.contains("draft"));
    }

    #[tokio::test]
    async fn list_labels_yaml_respects_limit() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345/labels"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [
                        {"id": "1", "name": "architecture", "prefix": "global"},
                        {"id": "2", "name": "draft", "prefix": "global"}
                    ]
                })),
            )
            .mount(&server)
            .await;

        let yaml = list_labels_yaml(&phase2d_mock_api(&server), "12345", 1)
            .await
            .unwrap();
        assert!(yaml.contains("architecture"));
        assert!(!yaml.contains("draft"));
    }

    #[tokio::test]
    async fn list_labels_yaml_api_error_propagates() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/404/labels"))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;

        let err = list_labels_yaml(&phase2d_mock_api(&server), "404", 0)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("404"));
    }

    // ── add_labels_result ──────────────────────────────────────────

    #[tokio::test]
    async fn add_labels_result_posts_and_returns_confirmation() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/12345/label",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [{"prefix": "global", "name": "arch", "id": "1"}]
                })),
            )
            .expect(1)
            .mount(&server)
            .await;

        let yaml = add_labels_result(&phase2d_mock_api(&server), "12345", &["arch".to_string()])
            .await
            .unwrap();
        assert!(yaml.contains("ok: true"));
        assert!(yaml.contains("arch"));
        assert!(yaml.contains("Added 1 label"));
    }

    #[tokio::test]
    async fn add_labels_result_rejects_empty_labels() {
        let server = wiremock::MockServer::start().await;
        let err = add_labels_result(&phase2d_mock_api(&server), "12345", &[])
            .await
            .unwrap_err();
        assert!(err.to_string().contains("at least one label"));
    }

    #[tokio::test]
    async fn add_labels_result_api_error_propagates() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/12345/label",
            ))
            .respond_with(wiremock::ResponseTemplate::new(400).set_body_string("Bad Request"))
            .mount(&server)
            .await;

        let err = add_labels_result(&phase2d_mock_api(&server), "12345", &["x".to_string()])
            .await
            .unwrap_err();
        assert!(err.to_string().contains("400"));
    }

    // ── remove_labels_result ───────────────────────────────────────

    #[tokio::test]
    async fn remove_labels_result_deletes_each_label() {
        let server = wiremock::MockServer::start().await;
        for label in &["draft", "old"] {
            wiremock::Mock::given(wiremock::matchers::method("DELETE"))
                .and(wiremock::matchers::path(format!(
                    "/wiki/rest/api/content/12345/label/{label}"
                )))
                .respond_with(wiremock::ResponseTemplate::new(204))
                .expect(1)
                .mount(&server)
                .await;
        }

        let yaml = remove_labels_result(
            &phase2d_mock_api(&server),
            "12345",
            &["draft".to_string(), "old".to_string()],
        )
        .await
        .unwrap();
        assert!(yaml.contains("ok: true"));
        assert!(yaml.contains("Removed 2 label"));
    }

    #[tokio::test]
    async fn remove_labels_result_rejects_empty_labels() {
        let server = wiremock::MockServer::start().await;
        let err = remove_labels_result(&phase2d_mock_api(&server), "12345", &[])
            .await
            .unwrap_err();
        assert!(err.to_string().contains("at least one label"));
    }

    #[tokio::test]
    async fn remove_labels_result_api_error_propagates() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path(
                "/wiki/rest/api/content/12345/label/draft",
            ))
            .respond_with(wiremock::ResponseTemplate::new(403).set_body_string("Forbidden"))
            .mount(&server)
            .await;

        let err = remove_labels_result(&phase2d_mock_api(&server), "12345", &["draft".to_string()])
            .await
            .unwrap_err();
        assert!(err.to_string().contains("403"));
    }

    // ── search_users_yaml ──────────────────────────────────────────

    #[tokio::test]
    async fn search_users_yaml_returns_users() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/rest/api/search/user"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [
                        {"user": {"accountId": "abc", "displayName": "Alice", "email": "a@x.com"}}
                    ]
                })),
            )
            .mount(&server)
            .await;

        let yaml = search_users_yaml(&phase2d_mock_client(&server.uri()), "alice", 25)
            .await
            .unwrap();
        assert!(yaml.contains("Alice"));
        assert!(yaml.contains("abc"));
    }

    #[tokio::test]
    async fn search_users_yaml_empty_results() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/rest/api/search/user"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        let yaml = search_users_yaml(&phase2d_mock_client(&server.uri()), "nobody", 10)
            .await
            .unwrap();
        assert!(yaml.contains("total: 0"));
    }

    #[tokio::test]
    async fn search_users_yaml_api_error_propagates() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/rest/api/search/user"))
            .respond_with(wiremock::ResponseTemplate::new(403).set_body_string("Forbidden"))
            .mount(&server)
            .await;

        let err = search_users_yaml(&phase2d_mock_client(&server.uri()), "alice", 25)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("403"));
    }
}