omni-dev 0.36.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, and Datadog.
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
//! CLI commands for Confluence page comments.

use std::io::{self, BufRead, Write};

use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};

use crate::atlassian::adf::AdfDocument;
use crate::atlassian::adf_validated::{markdown_to_validated_adf, ValidatedAdfDocument};
use crate::atlassian::confluence_api::ConfluenceApi;
use crate::atlassian::confluence_types::{CommentKind, ConfluenceComment, InlineAnchor};
use crate::atlassian::convert::adf_to_markdown;
use crate::atlassian::document::JfmDocument;
use crate::atlassian::inline_comment::{
    audit_inline_comments, reanchor_inline_comment, CommentDrift, DriftStatus,
};
use crate::cli::atlassian::confirm::{guard_destructive_with_io, GuardOptions, GuardOutcome};
use crate::cli::atlassian::format::{output_as, ContentFormat, OutputFormat};
use crate::cli::atlassian::helpers::{create_client, read_input};

/// Manages comments on a Confluence page.
#[derive(Parser)]
pub struct CommentCommand {
    /// The comment subcommand to execute.
    #[command(subcommand)]
    pub command: CommentSubcommands,
}

/// Comment subcommands.
#[derive(Subcommand)]
pub enum CommentSubcommands {
    /// Lists comments on a Confluence page (mirrors the `confluence_comment_list` MCP tool).
    List(ListCommand),
    /// Adds a footer comment to a Confluence page (mirrors the `confluence_comment_add` MCP tool).
    Add(AddCommand),
    /// Adds an inline (anchored) comment to a Confluence page (mirrors the `confluence_comment_add_inline` MCP tool).
    AddInline(AddInlineCommand),
    /// Lists the replies of a comment (mirrors the `confluence_comment_replies` MCP tool).
    Replies(RepliesCommand),
    /// Audits inline comments for anchor drift (mirrors the `confluence_comment_audit` MCP tool).
    Audit(AuditCommand),
    /// Moves an inline comment's anchor to a new text run (mirrors the `confluence_comment_reanchor` MCP tool).
    Reanchor(ReanchorCommand),
    /// Edits an existing comment's body (mirrors the `confluence_comment_edit` MCP tool).
    Edit(EditCommand),
    /// Deletes a comment (mirrors the `confluence_comment_delete` MCP tool).
    Delete(DeleteCommand),
    /// Resolves an inline comment (mirrors the `confluence_comment_resolve` MCP tool).
    Resolve(ResolveCommand),
    /// Reopens a resolved inline comment (mirrors the `confluence_comment_reopen` MCP tool).
    Reopen(ReopenCommand),
}

impl CommentCommand {
    /// Executes the comment command.
    pub async fn execute(self) -> Result<()> {
        match self.command {
            CommentSubcommands::List(cmd) => cmd.execute().await,
            CommentSubcommands::Add(cmd) => cmd.execute().await,
            CommentSubcommands::AddInline(cmd) => cmd.execute().await,
            CommentSubcommands::Replies(cmd) => cmd.execute().await,
            CommentSubcommands::Audit(cmd) => cmd.execute().await,
            CommentSubcommands::Reanchor(cmd) => cmd.execute().await,
            CommentSubcommands::Edit(cmd) => cmd.execute().await,
            CommentSubcommands::Delete(cmd) => cmd.execute().await,
            CommentSubcommands::Resolve(cmd) => cmd.execute().await,
            CommentSubcommands::Reopen(cmd) => cmd.execute().await,
        }
    }
}

/// `--kind` filter for `confluence comment list`.
///
/// `All` (the default) issues both the footer and inline list calls and
/// concatenates the results so a single invocation surfaces every comment on
/// the page.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
pub enum CommentKindFilter {
    /// Page-level footer comments only.
    Footer,
    /// Inline (anchored) comments only.
    Inline,
    /// Both kinds, concatenated and sorted by creation time.
    All,
}

/// `--kind` selector for `confluence comment replies` (no `All` — replies live
/// on a kind-specific endpoint, so the caller must commit to one).
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
pub enum CommentKindArg {
    /// Replies under a footer comment.
    Footer,
    /// Replies under an inline comment.
    Inline,
}

impl From<CommentKindArg> for CommentKind {
    fn from(k: CommentKindArg) -> Self {
        match k {
            CommentKindArg::Footer => Self::Footer,
            CommentKindArg::Inline => Self::Inline,
        }
    }
}

/// Lists comments on a Confluence page.
///
/// Comment authors are returned as Atlassian account IDs — resolve them to
/// display names with `omni-dev atlassian confluence user get`.
#[derive(Parser)]
pub struct ListCommand {
    /// Confluence page ID.
    pub id: String,

    /// Which kind of comments to show.
    #[arg(long, value_enum, default_value_t = CommentKindFilter::All)]
    pub kind: CommentKindFilter,

    /// Maximum number of comments to display.
    #[arg(long, default_value_t = 25)]
    pub limit: usize,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

impl ListCommand {
    /// Fetches and displays comments.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        run_list_comments(&api, &self.id, self.kind, self.limit, &self.output).await
    }
}

/// Adds a footer comment to a Confluence page.
#[derive(Parser)]
pub struct AddCommand {
    /// Confluence page ID.
    pub id: String,

    /// Input file (reads from stdin if omitted or "-").
    pub file: Option<String>,

    /// Input format.
    #[arg(long, value_enum, default_value_t = ContentFormat::Jfm)]
    pub format: ContentFormat,
}

impl AddCommand {
    /// Reads input, converts to ADF, and posts the comment.
    pub async fn execute(self) -> Result<()> {
        let adf = parse_comment_input(self.file.as_deref(), self.format)?;

        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        run_add_comment(&api, &self.id, &adf).await
    }
}

/// Adds an inline (anchored) comment to a Confluence page.
#[derive(Parser)]
pub struct AddInlineCommand {
    /// Confluence page ID.
    pub id: String,

    /// Input file (reads from stdin if omitted or "-").
    pub file: Option<String>,

    /// Input format.
    #[arg(long, value_enum, default_value_t = ContentFormat::Jfm)]
    pub format: ContentFormat,

    /// Exact text on the page that the comment should anchor to.
    #[arg(long)]
    pub anchor_text: String,

    /// 1-based occurrence to anchor to when `--anchor-text` appears more than
    /// once on the page. Required for ambiguous anchors; rejected if out of
    /// range.
    #[arg(long)]
    pub match_index: Option<usize>,
}

impl AddInlineCommand {
    /// Reads input, resolves the anchor, and posts the inline comment.
    pub async fn execute(self) -> Result<()> {
        let adf = parse_comment_input(self.file.as_deref(), self.format)?;

        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        let anchor = api
            .resolve_anchor(&self.id, &self.anchor_text, self.match_index)
            .await?;
        run_add_inline_comment(&api, &self.id, &adf, &anchor).await
    }
}

/// Lists the replies of a comment.
#[derive(Parser)]
pub struct RepliesCommand {
    /// Comment ID.
    pub id: String,

    /// Whether the parent is a footer or inline comment (the Confluence API
    /// requires this to pick the right endpoint).
    #[arg(long, value_enum)]
    pub kind: CommentKindArg,

    /// Maximum number of replies to display.
    #[arg(long, default_value_t = 25)]
    pub limit: usize,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

impl RepliesCommand {
    /// Fetches and displays the replies of a comment.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        run_list_replies(&api, &self.id, self.kind.into(), self.limit, &self.output).await
    }
}

/// Audits every inline comment on a page for anchor drift.
///
/// Inline-comment anchors do NOT follow text edits: when the annotated text is
/// rewritten, Confluence keeps the mark on whatever original characters survive.
/// This compares each comment's currently-anchored text against the reviewer's
/// original highlight and reports the drift. Read-only.
#[derive(Parser)]
pub struct AuditCommand {
    /// Confluence page ID.
    pub id: String,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

impl AuditCommand {
    /// Fetches inline comments and the page ADF, then reports drift.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        let drifts = audit_inline_comments(&api, &self.id).await?;
        if output_as(&drifts, &self.output)? {
            return Ok(());
        }
        print_drifts(&drifts);
        Ok(())
    }
}

/// Moves an inline comment's anchor to a new run of text in the current-version
/// ADF and writes the page back.
///
/// Operates entirely on ADF (it never round-trips through JFM, which would
/// discard the annotation marks the anchor depends on). Destructive — the page
/// is updated — so it prompts for confirmation unless `--force`.
#[derive(Parser)]
pub struct ReanchorCommand {
    /// Confluence page ID.
    pub id: String,

    /// The inline comment ID to re-anchor.
    #[arg(long)]
    pub comment: String,

    /// Exact text on the current page to move the comment's anchor to.
    #[arg(long)]
    pub anchor_text: String,

    /// 1-based occurrence to anchor to when `--anchor-text` appears more than
    /// once on the page. Required for ambiguous anchors; rejected if out of range.
    #[arg(long)]
    pub match_index: Option<usize>,

    /// Skips the confirmation prompt.
    #[arg(long)]
    pub force: bool,

    /// Prints what would change without writing the page.
    #[arg(long)]
    pub dry_run: bool,
}

impl ReanchorCommand {
    /// Executes the re-anchor command.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        let mut reader = io::BufReader::new(io::stdin());
        let mut writer = io::stdout();
        self.execute_with_io(&api, &mut reader, &mut writer).await
    }

    /// Inner form taking explicit API and IO handles, for unit tests.
    async fn execute_with_io(
        self,
        api: &ConfluenceApi,
        reader: &mut (dyn BufRead + Send),
        writer: &mut (dyn Write + Send),
    ) -> Result<()> {
        let prompt = format!(
            "Re-anchor inline comment {} on page {} to {:?}? [y/N] ",
            self.comment, self.id, self.anchor_text
        );
        let dry_run_message = format!(
            "Would re-anchor inline comment {} on page {} to {:?}.",
            self.comment, self.id, self.anchor_text
        );
        let outcome = guard_destructive_with_io(
            &GuardOptions {
                prompt: &prompt,
                dry_run_message: &dry_run_message,
                force: self.force,
                dry_run: self.dry_run,
            },
            reader,
            writer,
        )?;
        match outcome {
            GuardOutcome::Cancelled | GuardOutcome::DryRun => return Ok(()),
            GuardOutcome::Proceed => {}
        }

        let outcome = reanchor_inline_comment(
            api,
            &self.id,
            &self.comment,
            &self.anchor_text,
            self.match_index,
            false,
        )
        .await?;
        writeln!(
            writer,
            "Re-anchored inline comment {} to {:?}.",
            outcome.comment_id, outcome.new_anchor_text
        )?;
        Ok(())
    }
}

/// Edits an existing comment's body on a Confluence page.
#[derive(Parser)]
pub struct EditCommand {
    /// Comment ID to edit (from `comment list`).
    pub comment_id: String,

    /// Whether the target is a footer or inline comment (the v2 API uses
    /// separate endpoints).
    #[arg(long, value_enum)]
    pub kind: CommentKindArg,

    /// Input file (reads from stdin if omitted or "-").
    pub file: Option<String>,

    /// Input format.
    #[arg(long, value_enum, default_value_t = ContentFormat::Jfm)]
    pub format: ContentFormat,
}

impl EditCommand {
    /// Reads input, converts to ADF, and updates the comment.
    pub async fn execute(self) -> Result<()> {
        let adf = parse_comment_input(self.file.as_deref(), self.format)?;
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        api.update_page_comment(&self.comment_id, self.kind.into(), &adf)
            .await?;
        println!("Comment {} updated.", self.comment_id);
        Ok(())
    }
}

/// Deletes a comment from a Confluence page.
#[derive(Parser)]
pub struct DeleteCommand {
    /// Comment ID to delete (from `comment list`).
    pub comment_id: String,

    /// Whether the target is a footer or inline comment (the v2 API uses
    /// separate endpoints).
    #[arg(long, value_enum)]
    pub kind: CommentKindArg,

    /// Skips the confirmation prompt.
    #[arg(long)]
    pub force: bool,

    /// Prints what would be deleted without making any API calls.
    #[arg(long)]
    pub dry_run: bool,
}

impl DeleteCommand {
    /// Executes the delete command.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        let mut reader = io::BufReader::new(io::stdin());
        let mut writer = io::stdout();
        self.execute_with_io(&api, &mut reader, &mut writer).await
    }

    /// Inner form taking explicit API and IO handles, for unit tests.
    async fn execute_with_io(
        self,
        api: &ConfluenceApi,
        reader: &mut (dyn BufRead + Send),
        writer: &mut (dyn Write + Send),
    ) -> Result<()> {
        let kind: CommentKind = self.kind.into();
        let prompt = format!("Delete {kind} comment {}? [y/N] ", self.comment_id);
        let dry_run_message = format!("Would delete {kind} comment {}.", self.comment_id);
        let outcome = guard_destructive_with_io(
            &GuardOptions {
                prompt: &prompt,
                dry_run_message: &dry_run_message,
                force: self.force,
                dry_run: self.dry_run,
            },
            reader,
            writer,
        )?;
        match outcome {
            GuardOutcome::Cancelled | GuardOutcome::DryRun => return Ok(()),
            GuardOutcome::Proceed => {}
        }

        api.delete_page_comment(&self.comment_id, kind).await?;
        writeln!(writer, "Deleted comment {}.", self.comment_id)?;
        Ok(())
    }
}

/// Resolves an inline comment on a Confluence page.
#[derive(Parser)]
pub struct ResolveCommand {
    /// Inline comment ID to resolve (from `comment list`).
    pub comment_id: String,
}

impl ResolveCommand {
    /// Resolves the inline comment.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        api.set_inline_comment_resolved(&self.comment_id, true)
            .await?;
        println!("Resolved inline comment {}.", self.comment_id);
        Ok(())
    }
}

/// Reopens a resolved inline comment on a Confluence page.
#[derive(Parser)]
pub struct ReopenCommand {
    /// Inline comment ID to reopen (from `comment list`).
    pub comment_id: String,
}

impl ReopenCommand {
    /// Reopens the inline comment.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        api.set_inline_comment_resolved(&self.comment_id, false)
            .await?;
        println!("Reopened inline comment {}.", self.comment_id);
        Ok(())
    }
}

/// Prints inline-comment drift reports in a readable format.
fn print_drifts(drifts: &[CommentDrift]) {
    if drifts.is_empty() {
        println!("No inline comments.");
        return;
    }

    for (i, drift) in drifts.iter().enumerate() {
        if i > 0 {
            println!();
        }
        let status = match drift.status {
            DriftStatus::Ok => "OK",
            DriftStatus::Torn => "TORN",
            DriftStatus::MarkLost => "MARK LOST",
            DriftStatus::Drifted => "DRIFTED",
        };
        println!("--- {} | {} ---", drift.comment_id, status);
        println!("  original:  {:?}", drift.original_selection);
        match &drift.current_anchored_text {
            Some(text) => println!("  current:   {text:?}"),
            None => println!("  current:   (mark not present)"),
        }
        if let Some(suggestion) = &drift.suggested_new_anchor {
            let count = drift.suggested_match_count.unwrap_or(0);
            println!("  suggested: {suggestion:?} (appears {count}x on the current page)");
        }
    }
}

/// Parses a comment input file (or stdin) into a validated ADF document.
///
/// Shared by `comment add` (footer) and `comment add-inline` so both surfaces
/// accept the same input formats — JFM with frontmatter, raw markdown, or
/// pre-built ADF JSON.
fn parse_comment_input(file: Option<&str>, format: ContentFormat) -> Result<ValidatedAdfDocument> {
    let input = read_input(file)?;

    let validated: ValidatedAdfDocument = match format {
        ContentFormat::Jfm => {
            if input.starts_with("---\n") {
                let doc = JfmDocument::parse(&input)?;
                markdown_to_validated_adf(&doc.body)?
            } else {
                markdown_to_validated_adf(&input)?
            }
        }
        ContentFormat::Adf => {
            let adf: AdfDocument =
                serde_json::from_str(&input).context("Failed to parse ADF JSON input")?;
            ValidatedAdfDocument::try_new(adf)?
        }
    };
    Ok(validated)
}

/// Fetches and displays comments for a page.
async fn run_list_comments(
    api: &ConfluenceApi,
    id: &str,
    kind: CommentKindFilter,
    limit: usize,
    output: &OutputFormat,
) -> Result<()> {
    let mut comments = match kind {
        CommentKindFilter::Footer => api.get_page_comments(id).await?,
        CommentKindFilter::Inline => api.get_page_inline_comments(id).await?,
        CommentKindFilter::All => {
            let mut footer = api.get_page_comments(id).await?;
            let inline = api.get_page_inline_comments(id).await?;
            footer.extend(inline);
            footer.sort_by(|a, b| a.created.cmp(&b.created));
            footer
        }
    };
    comments.truncate(limit);
    if output_as(&comments, output)? {
        return Ok(());
    }
    print_comments(&comments);
    Ok(())
}

/// Fetches and displays the replies of a single comment.
async fn run_list_replies(
    api: &ConfluenceApi,
    comment_id: &str,
    kind: CommentKind,
    limit: usize,
    output: &OutputFormat,
) -> Result<()> {
    let mut replies = api.get_comment_replies(comment_id, kind).await?;
    replies.truncate(limit);
    if output_as(&replies, output)? {
        return Ok(());
    }
    print_comments(&replies);
    Ok(())
}

/// Posts a footer comment to a page.
async fn run_add_comment(api: &ConfluenceApi, id: &str, adf: &ValidatedAdfDocument) -> Result<()> {
    api.add_page_comment(id, adf).await?;
    println!("Comment added to page {id}.");
    Ok(())
}

/// Posts an inline comment to a page.
async fn run_add_inline_comment(
    api: &ConfluenceApi,
    id: &str,
    adf: &ValidatedAdfDocument,
    anchor: &InlineAnchor,
) -> Result<()> {
    api.add_inline_page_comment(id, adf, anchor).await?;
    println!(
        "Inline comment added to page {id} anchored to {:?} (occurrence {} of {}).",
        anchor.text,
        anchor.match_index + 1,
        anchor.match_count
    );
    Ok(())
}

/// Prints comments in a readable format.
fn print_comments(comments: &[ConfluenceComment]) {
    if comments.is_empty() {
        println!("No comments.");
        return;
    }

    for (i, comment) in comments.iter().enumerate() {
        if i > 0 {
            println!();
        }

        let timestamp = format_timestamp(&comment.created);
        println!(
            "--- {} | {} | {} ---",
            comment.author, timestamp, comment.kind
        );
        println!("{}", format_comment_body(&comment.body_adf));
    }
}

/// Formats a comment body for display.
fn format_comment_body(body_adf: &Option<serde_json::Value>) -> String {
    let Some(adf_value) = body_adf else {
        return "[empty]".to_string();
    };

    let Ok(adf) = serde_json::from_value::<AdfDocument>(adf_value.clone()) else {
        return "[ADF content]".to_string();
    };

    let Ok(md) = adf_to_markdown(&adf) else {
        return "[ADF content]".to_string();
    };

    let trimmed = md.trim();
    if trimmed.is_empty() {
        "[empty]".to_string()
    } else {
        trimmed.to_string()
    }
}

/// Formats an ISO 8601 timestamp to a shorter display format.
fn format_timestamp(ts: &str) -> &str {
    // Return just the date+time portion (before the timezone offset or milliseconds)
    // e.g., "2026-04-01T10:00:00.000Z" -> "2026-04-01T10:00:00"
    ts.split('.').next().unwrap_or(ts)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::await_holding_lock)]
mod tests {
    use super::*;
    use std::fs;

    fn sample_comment(
        id: &str,
        author: &str,
        body_adf: Option<serde_json::Value>,
    ) -> ConfluenceComment {
        ConfluenceComment {
            id: id.to_string(),
            author: author.to_string(),
            kind: CommentKind::Footer,
            body_adf,
            created: "2026-04-01T10:30:00.000Z".to_string(),
            inline_marker_ref: None,
            inline_original_selection: None,
        }
    }

    fn sample_inline_comment(
        id: &str,
        author: &str,
        body_adf: Option<serde_json::Value>,
    ) -> ConfluenceComment {
        ConfluenceComment {
            id: id.to_string(),
            author: author.to_string(),
            kind: CommentKind::Inline,
            body_adf,
            created: "2026-04-02T10:30:00.000Z".to_string(),
            inline_marker_ref: Some("marker-1".to_string()),
            inline_original_selection: Some("original highlighted text".to_string()),
        }
    }

    // ── print_comments ─────────────────────────────────────────────

    #[test]
    fn print_comments_empty() {
        print_comments(&[]);
    }

    #[test]
    fn print_comments_with_adf_body() {
        let adf = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hello world"}]}]
        });
        let comments = vec![sample_comment("1", "Alice", Some(adf))];
        print_comments(&comments);
    }

    #[test]
    fn print_comments_with_null_body() {
        let comments = vec![sample_comment("1", "Bob", None)];
        print_comments(&comments);
    }

    #[test]
    fn print_comments_with_invalid_adf() {
        let invalid = serde_json::json!({"not": "adf"});
        let comments = vec![sample_comment("1", "Carol", Some(invalid))];
        print_comments(&comments);
    }

    #[test]
    fn print_comments_multiple() {
        let adf = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "First"}]}]
        });
        let comments = vec![
            sample_comment("1", "Alice", Some(adf)),
            sample_inline_comment("2", "Bob", None),
        ];
        print_comments(&comments);
    }

    // ── format_comment_body ─────────────────────────────────────────

    #[test]
    fn format_body_none() {
        assert_eq!(format_comment_body(&None), "[empty]");
    }

    #[test]
    fn format_body_valid_adf_with_text() {
        let adf = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hello"}]}]
        });
        let result = format_comment_body(&Some(adf));
        assert_eq!(result, "Hello");
    }

    #[test]
    fn format_body_valid_adf_empty_content() {
        let adf = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": []
        });
        let result = format_comment_body(&Some(adf));
        assert_eq!(result, "[empty]");
    }

    #[test]
    fn format_body_invalid_adf() {
        let invalid = serde_json::json!({"not": "adf"});
        assert_eq!(format_comment_body(&Some(invalid)), "[ADF content]");
    }

    // ── format_timestamp ───────────────────────────────────────────

    #[test]
    fn format_timestamp_with_millis() {
        assert_eq!(
            format_timestamp("2026-04-01T10:30:00.000Z"),
            "2026-04-01T10:30:00"
        );
    }

    #[test]
    fn format_timestamp_without_millis() {
        assert_eq!(
            format_timestamp("2026-04-01T10:30:00"),
            "2026-04-01T10:30:00"
        );
    }

    #[test]
    fn format_timestamp_empty() {
        assert_eq!(format_timestamp(""), "");
    }

    // ── parse_comment_input ────────────────────────────────────────

    #[test]
    fn parse_input_raw_markdown() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("comment.md");
        fs::write(&file_path, "Hello **world**\n").unwrap();

        let adf =
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Jfm).unwrap();
        assert!(!adf.content.is_empty());
    }

    #[test]
    fn parse_input_jfm_with_frontmatter() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("comment.md");
        let content =
            "---\ntype: confluence\ninstance: https://org.atlassian.net\nid: \"12345\"\ntitle: Test\nspace_key: ENG\n---\n\nComment body\n";
        fs::write(&file_path, content).unwrap();

        let adf =
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Jfm).unwrap();
        assert!(!adf.content.is_empty());
    }

    #[test]
    fn parse_input_adf_format() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("comment.json");
        let adf_json = r#"{"version":1,"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}"#;
        fs::write(&file_path, adf_json).unwrap();

        let adf =
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Adf).unwrap();
        assert_eq!(adf.content.len(), 1);
    }

    #[test]
    fn parse_input_invalid_adf() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("bad.json");
        fs::write(&file_path, "not json").unwrap();

        assert!(
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Adf).is_err()
        );
    }

    #[test]
    fn parse_input_jfm_rejects_invalid_adf_nesting() {
        // Issue #714: JFM that converts to invalid ADF (panel→expand) must
        // be rejected at parse time, before the API call.
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("bad.md");
        fs::write(
            &file_path,
            ":::panel{type=info}\n:::expand{title=\"x\"}\nbody\n:::\n:::",
        )
        .unwrap();

        let err =
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Jfm).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("invalid ADF nesting"));
        assert!(msg.contains("`expand` cannot be a child of `panel`"));
    }

    // ── CommentCommand dispatch ────────────────────────────────────

    #[test]
    fn comment_command_list_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::List(ListCommand {
                id: "12345".to_string(),
                kind: CommentKindFilter::All,
                limit: 25,
                output: OutputFormat::Table,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::List(_)));
    }

    #[test]
    fn comment_command_add_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::Add(AddCommand {
                id: "12345".to_string(),
                file: None,
                format: ContentFormat::Jfm,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::Add(_)));
    }

    #[test]
    fn comment_command_add_inline_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::AddInline(AddInlineCommand {
                id: "12345".to_string(),
                file: None,
                format: ContentFormat::Jfm,
                anchor_text: "phrase".to_string(),
                match_index: None,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::AddInline(_)));
    }

    #[test]
    fn comment_command_replies_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::Replies(RepliesCommand {
                id: "abc".to_string(),
                kind: CommentKindArg::Inline,
                limit: 25,
                output: OutputFormat::Table,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::Replies(_)));
    }

    // ── CommentKindArg → CommentKind conversion ────────────────────

    #[test]
    fn comment_kind_arg_into_footer() {
        let k: CommentKind = CommentKindArg::Footer.into();
        assert_eq!(k, CommentKind::Footer);
    }

    #[test]
    fn comment_kind_arg_into_inline() {
        let k: CommentKind = CommentKindArg::Inline.into();
        assert_eq!(k, CommentKind::Inline);
    }

    // ── edit / delete / resolve / reopen ───────────────────────────

    #[test]
    fn comment_command_edit_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::Edit(EditCommand {
                comment_id: "555".to_string(),
                kind: CommentKindArg::Footer,
                file: None,
                format: ContentFormat::Jfm,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::Edit(_)));
    }

    #[test]
    fn comment_command_delete_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::Delete(DeleteCommand {
                comment_id: "555".to_string(),
                kind: CommentKindArg::Inline,
                force: false,
                dry_run: false,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::Delete(_)));
    }

    #[test]
    fn comment_command_resolve_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::Resolve(ResolveCommand {
                comment_id: "555".to_string(),
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::Resolve(_)));
    }

    #[test]
    fn comment_command_reopen_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::Reopen(ReopenCommand {
                comment_id: "555".to_string(),
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::Reopen(_)));
    }

    #[tokio::test]
    async fn delete_comment_force_calls_delete() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path("/wiki/api/v2/footer-comments/555"))
            .respond_with(wiremock::ResponseTemplate::new(204))
            .expect(1)
            .mount(&server)
            .await;

        let api = mock_api(&server);
        let cmd = DeleteCommand {
            comment_id: "555".to_string(),
            kind: CommentKindArg::Footer,
            force: true,
            dry_run: false,
        };
        let mut input = std::io::Cursor::new(Vec::<u8>::new());
        let mut output = Vec::<u8>::new();
        cmd.execute_with_io(&api, &mut input, &mut output)
            .await
            .unwrap();
        assert!(String::from_utf8(output)
            .unwrap()
            .contains("Deleted comment 555."));
    }

    #[tokio::test]
    async fn delete_comment_dry_run_makes_no_api_call() {
        // No mocks mounted: a real DELETE would 404/connect-fail.
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);
        let cmd = DeleteCommand {
            comment_id: "555".to_string(),
            kind: CommentKindArg::Inline,
            force: false,
            dry_run: true,
        };
        let mut input = std::io::Cursor::new(Vec::<u8>::new());
        let mut output = Vec::<u8>::new();
        cmd.execute_with_io(&api, &mut input, &mut output)
            .await
            .unwrap();
        let out = String::from_utf8(output).unwrap();
        assert!(out.contains("Would delete inline comment 555."));
        assert!(!out.contains("Deleted comment"));
    }

    // ── CommentCommand::execute() end-to-end ───────────────────────
    //
    // Drives the top-level dispatch arm *and* each subcommand's execute()
    // wrapper (create_client + API call) against a wiremock.

    fn comment_detail_mock(segment: &str) -> wiremock::Mock {
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(format!(
                "/wiki/api/v2/{segment}/555"
            )))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "version": {"number": 1},
                    "body": {"atlas_doc_format": {"value": "{}"}}
                })),
            )
    }

    fn comment_put_mock(segment: &str) -> wiremock::Mock {
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .and(wiremock::matchers::path(format!(
                "/wiki/api/v2/{segment}/555"
            )))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "555"})),
            )
    }

    #[tokio::test]
    async fn comment_command_execute_edit_drives_create_client() {
        use crate::test_support::atlassian_env::AtlassianEnvGuard;
        let server = wiremock::MockServer::start().await;
        comment_detail_mock("footer-comments").mount(&server).await;
        comment_put_mock("footer-comments").mount(&server).await;

        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("body.md");
        std::fs::write(&file, "revised body\n").unwrap();

        let _env = AtlassianEnvGuard::new(&server.uri(), "u@t.com", "tok");
        CommentCommand {
            command: CommentSubcommands::Edit(EditCommand {
                comment_id: "555".to_string(),
                kind: CommentKindArg::Footer,
                file: Some(file.to_string_lossy().into_owned()),
                format: ContentFormat::Jfm,
            }),
        }
        .execute()
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn comment_command_execute_delete_drives_create_client() {
        use crate::test_support::atlassian_env::AtlassianEnvGuard;
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path("/wiki/api/v2/inline-comments/555"))
            .respond_with(wiremock::ResponseTemplate::new(204))
            .mount(&server)
            .await;
        let _env = AtlassianEnvGuard::new(&server.uri(), "u@t.com", "tok");
        // `--force` skips the prompt, so the wrapper's real stdin is not read.
        CommentCommand {
            command: CommentSubcommands::Delete(DeleteCommand {
                comment_id: "555".to_string(),
                kind: CommentKindArg::Inline,
                force: true,
                dry_run: false,
            }),
        }
        .execute()
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn comment_command_execute_resolve_drives_create_client() {
        use crate::test_support::atlassian_env::AtlassianEnvGuard;
        let server = wiremock::MockServer::start().await;
        comment_detail_mock("inline-comments").mount(&server).await;
        comment_put_mock("inline-comments").mount(&server).await;
        let _env = AtlassianEnvGuard::new(&server.uri(), "u@t.com", "tok");
        CommentCommand {
            command: CommentSubcommands::Resolve(ResolveCommand {
                comment_id: "555".to_string(),
            }),
        }
        .execute()
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn comment_command_execute_reopen_drives_create_client() {
        use crate::test_support::atlassian_env::AtlassianEnvGuard;
        let server = wiremock::MockServer::start().await;
        comment_detail_mock("inline-comments").mount(&server).await;
        comment_put_mock("inline-comments").mount(&server).await;
        let _env = AtlassianEnvGuard::new(&server.uri(), "u@t.com", "tok");
        CommentCommand {
            command: CommentSubcommands::Reopen(ReopenCommand {
                comment_id: "555".to_string(),
            }),
        }
        .execute()
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn delete_comment_prompt_no_makes_no_delete() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);
        let cmd = DeleteCommand {
            comment_id: "555".to_string(),
            kind: CommentKindArg::Footer,
            force: false,
            dry_run: false,
        };
        let mut input = std::io::Cursor::new(b"n\n".to_vec());
        let mut output = Vec::<u8>::new();
        cmd.execute_with_io(&api, &mut input, &mut output)
            .await
            .unwrap();
        assert!(!String::from_utf8(output)
            .unwrap()
            .contains("Deleted comment"));
    }

    // ── run_list_comments / run_add_comment ────────────────────────

    fn mock_api(server: &wiremock::MockServer) -> ConfluenceApi {
        let client =
            crate::atlassian::client::AtlassianClient::new(&server.uri(), "user@test.com", "token")
                .unwrap();
        ConfluenceApi::new(client)
    }

    #[tokio::test]
    async fn run_list_comments_success() {
        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": []})),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        assert!(run_list_comments(
            &api,
            "12345",
            CommentKindFilter::Footer,
            25,
            &OutputFormat::Table,
        )
        .await
        .is_ok());
    }

    #[tokio::test]
    async fn run_list_comments_json_output() {
        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": []})),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        assert!(run_list_comments(
            &api,
            "12345",
            CommentKindFilter::Footer,
            25,
            &OutputFormat::Json,
        )
        .await
        .is_ok());
    }

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

        let api = mock_api(&server);
        let err = run_list_comments(
            &api,
            "99999",
            CommentKindFilter::Footer,
            25,
            &OutputFormat::Table,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("404"));
    }

    #[tokio::test]
    async fn run_list_comments_inline_kind_hits_inline_endpoint() {
        // `Inline` filter must NOT touch the footer endpoint.
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/inline-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .expect(1)
            .mount(&server)
            .await;

        let api = mock_api(&server);
        assert!(run_list_comments(
            &api,
            "12345",
            CommentKindFilter::Inline,
            25,
            &OutputFormat::Json,
        )
        .await
        .is_ok());
    }

    #[tokio::test]
    async fn run_list_comments_all_kind_fetches_both() {
        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": "f1",
                        "version": {"authorId": "alice", "createdAt": "2026-04-01T10:00:00Z"}
                    }]
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/inline-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [{
                        "id": "i1",
                        "version": {"authorId": "bob", "createdAt": "2026-04-02T10:00:00Z"}
                    }]
                })),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        assert!(run_list_comments(
            &api,
            "12345",
            CommentKindFilter::All,
            25,
            &OutputFormat::Json,
        )
        .await
        .is_ok());
    }

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

        let api = mock_api(&server);
        assert!(
            run_list_replies(&api, "abc", CommentKind::Inline, 25, &OutputFormat::Table,)
                .await
                .is_ok()
        );
    }

    #[tokio::test]
    async fn run_add_comment_success() {
        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": "200"})),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        let adf = ValidatedAdfDocument::empty();
        assert!(run_add_comment(&api, "12345", &adf).await.is_ok());
    }

    #[tokio::test]
    async fn run_add_comment_api_error() {
        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 api = mock_api(&server);
        let adf = ValidatedAdfDocument::empty();
        let err = run_add_comment(&api, "12345", &adf).await.unwrap_err();
        assert!(err.to_string().contains("403"));
    }

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

        let api = mock_api(&server);
        let adf = ValidatedAdfDocument::empty();
        let anchor = InlineAnchor {
            text: "phrase".to_string(),
            match_index: 0,
            match_count: 1,
        };
        assert!(run_add_inline_comment(&api, "12345", &adf, &anchor)
            .await
            .is_ok());
    }

    // ── *Command::execute (env-mutex serialised) ───────────────────
    //
    // Each `*::execute()` is a thin wrapper around `create_client()` and a
    // `run_*` helper. Exercising the `Err` propagation through `?` plus one
    // happy-path dispatch is enough to cover the wrapper; the underlying
    // helper logic is covered by the `run_*` tests above.

    fn set_atlassian_env(uri: &str) {
        std::env::set_var(crate::atlassian::auth::ATLASSIAN_INSTANCE_URL, uri);
        std::env::set_var(crate::atlassian::auth::ATLASSIAN_EMAIL, "user@test.com");
        std::env::set_var(crate::atlassian::auth::ATLASSIAN_API_TOKEN, "t");
    }

    fn clear_atlassian_env() {
        std::env::remove_var(crate::atlassian::auth::ATLASSIAN_INSTANCE_URL);
        std::env::remove_var(crate::atlassian::auth::ATLASSIAN_EMAIL);
        std::env::remove_var(crate::atlassian::auth::ATLASSIAN_API_TOKEN);
    }

    #[tokio::test]
    async fn list_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = ListCommand {
            id: "12345".to_string(),
            kind: CommentKindFilter::All,
            limit: 25,
            output: OutputFormat::Yaml,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn list_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        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": []})),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/inline-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::List(ListCommand {
                id: "12345".to_string(),
                kind: CommentKindFilter::All,
                limit: 25,
                output: OutputFormat::Json,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn add_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let temp_dir = tempfile::tempdir().unwrap();
        let body_path = temp_dir.path().join("body.md");
        fs::write(&body_path, "Hello").unwrap();

        let cmd = AddCommand {
            id: "12345".to_string(),
            file: Some(body_path.to_str().unwrap().to_string()),
            format: ContentFormat::Jfm,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn add_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        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"})),
            )
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let body_path = temp_dir.path().join("body.md");
        fs::write(&body_path, "Hello").unwrap();

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::Add(AddCommand {
                id: "12345".to_string(),
                file: Some(body_path.to_str().unwrap().to_string()),
                format: ContentFormat::Jfm,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn add_inline_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let temp_dir = tempfile::tempdir().unwrap();
        let body_path = temp_dir.path().join("body.md");
        fs::write(&body_path, "Hello").unwrap();

        let cmd = AddInlineCommand {
            id: "12345".to_string(),
            file: Some(body_path.to_str().unwrap().to_string()),
            format: ContentFormat::Jfm,
            anchor_text: "phrase".to_string(),
            match_index: None,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn add_inline_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        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": "Mock",
                    "status": "current",
                    "spaceId": "98",
                    "version": {"number": 1},
                    "body": {"atlas_doc_format": {
                        "value": "{\"version\":1,\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"the anchor\"}]}]}"
                    }}
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/98"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"key": "ENG"})),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/inline-comments"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "ic1"})),
            )
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let body_path = temp_dir.path().join("body.md");
        fs::write(&body_path, "Inline note").unwrap();

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::AddInline(AddInlineCommand {
                id: "12345".to_string(),
                file: Some(body_path.to_str().unwrap().to_string()),
                format: ContentFormat::Jfm,
                anchor_text: "the anchor".to_string(),
                match_index: None,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn replies_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = RepliesCommand {
            id: "abc".to_string(),
            kind: CommentKindArg::Inline,
            limit: 25,
            output: OutputFormat::Yaml,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn replies_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/inline-comments/abc/children",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::Replies(RepliesCommand {
                id: "abc".to_string(),
                kind: CommentKindArg::Inline,
                limit: 25,
                output: OutputFormat::Json,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    // ── print_drifts ───────────────────────────────────────────────

    fn sample_drift(id: &str, status: DriftStatus) -> CommentDrift {
        CommentDrift {
            comment_id: id.to_string(),
            author: "alice".to_string(),
            created: "2026-04-01T10:00:00.000Z".to_string(),
            marker_ref: "marker-1".to_string(),
            status,
            original_selection: "original text".to_string(),
            current_anchored_text: Some("current text".to_string()),
            suggested_new_anchor: None,
            suggested_match_count: None,
        }
    }

    #[test]
    fn print_drifts_empty() {
        print_drifts(&[]);
    }

    #[test]
    fn print_drifts_all_statuses() {
        let mut lost = sample_drift("c3", DriftStatus::MarkLost);
        lost.current_anchored_text = None;
        lost.suggested_new_anchor = Some("original text".to_string());
        lost.suggested_match_count = Some(2);
        let mut drifted = sample_drift("c4", DriftStatus::Drifted);
        // Suggestion without a count exercises the `unwrap_or(0)` fallback.
        drifted.suggested_new_anchor = Some("original text".to_string());
        let drifts = vec![
            sample_drift("c1", DriftStatus::Ok),
            sample_drift("c2", DriftStatus::Torn),
            lost,
            drifted,
        ];
        print_drifts(&drifts);
    }

    // ── audit / reanchor command execution ──────────────────────────

    /// Mounts the endpoints a reanchor (and audit) needs: the page (whose ADF
    /// contains "the anchor"), its space, one inline comment `ic1` bearing
    /// marker `aaa`, and the page-update PUT.
    async fn mount_reanchor_fixture(server: &wiremock::MockServer) {
        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": "Mock",
                    "status": "current",
                    "spaceId": "98",
                    "version": {"number": 1},
                    "body": {"atlas_doc_format": {
                        "value": "{\"version\":1,\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"the anchor\"}]}]}"
                    }}
                })),
            )
            .mount(server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/98"))
            .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/api/v2/pages/12345/inline-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [
                        {"id": "ic1", "version": {"authorId": "a", "createdAt": "t"},
                         "properties": {"inlineMarkerRef": "aaa", "inlineOriginalSelection": "old"}}
                    ]
                })),
            )
            .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;
    }

    #[tokio::test]
    async fn audit_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = AuditCommand {
            id: "12345".to_string(),
            output: OutputFormat::Yaml,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn audit_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::Audit(AuditCommand {
                id: "12345".to_string(),
                output: OutputFormat::Json,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn audit_command_execute_table_output_prints_drifts() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;

        set_atlassian_env(&server.uri());
        let cmd = AuditCommand {
            id: "12345".to_string(),
            output: OutputFormat::Table,
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    fn reanchor_command(force: bool, dry_run: bool) -> ReanchorCommand {
        ReanchorCommand {
            id: "12345".to_string(),
            comment: "ic1".to_string(),
            anchor_text: "the anchor".to_string(),
            match_index: None,
            force,
            dry_run,
        }
    }

    #[tokio::test]
    async fn reanchor_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = reanchor_command(true, false);
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn reanchor_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::Reanchor(reanchor_command(true, false)),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_cancelled_makes_no_api_calls() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);

        let cmd = reanchor_command(false, false);
        let mut reader = io::Cursor::new(b"n\n".to_vec());
        let mut writer: Vec<u8> = Vec::new();
        cmd.execute_with_io(&api, &mut reader, &mut writer)
            .await
            .unwrap();

        let out = String::from_utf8(writer).unwrap();
        assert!(out.contains("Re-anchor inline comment ic1"));
        assert!(out.contains("Cancelled."));
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_dry_run_makes_no_api_calls() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);

        let cmd = reanchor_command(false, true);
        let mut reader = io::Cursor::new(Vec::new());
        let mut writer: Vec<u8> = Vec::new();
        cmd.execute_with_io(&api, &mut reader, &mut writer)
            .await
            .unwrap();

        let out = String::from_utf8(writer).unwrap();
        assert!(out.contains("Would re-anchor inline comment ic1"));
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_confirmed_proceeds() {
        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;
        let api = mock_api(&server);

        let cmd = reanchor_command(false, false);
        let mut reader = io::Cursor::new(b"y\n".to_vec());
        let mut writer: Vec<u8> = Vec::new();
        cmd.execute_with_io(&api, &mut reader, &mut writer)
            .await
            .unwrap();

        let out = String::from_utf8(writer).unwrap();
        assert!(out.contains("Re-anchored inline comment ic1"));
        let requests = server.received_requests().await.unwrap();
        assert!(requests
            .iter()
            .any(|r| r.method == wiremock::http::Method::PUT));
    }

    /// A writer that fails at a chosen point (`write` or, when writes are
    /// allowed through, `flush`), for exercising IO-error propagation through
    /// `execute_with_io`.
    struct FailingWriter {
        fail_write: bool,
    }

    impl Write for FailingWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            if self.fail_write {
                Err(io::Error::other("writer failed"))
            } else {
                Ok(buf.len())
            }
        }

        fn flush(&mut self) -> io::Result<()> {
            Err(io::Error::other("writer failed"))
        }
    }

    /// A dry-run with a failing writer makes the guard's own `writeln` fail,
    /// covering the `?` propagation on `guard_destructive_with_io` in
    /// `DeleteCommand::execute_with_io` — the last uncovered line of #1117.
    #[tokio::test]
    async fn delete_comment_dry_run_propagates_guard_error() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);
        let cmd = DeleteCommand {
            comment_id: "555".to_string(),
            kind: CommentKindArg::Inline,
            force: false,
            dry_run: true,
        };
        let mut input = std::io::Cursor::new(Vec::<u8>::new());
        let mut writer = FailingWriter { fail_write: true };
        let err = cmd
            .execute_with_io(&api, &mut input, &mut writer)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("writer failed"));
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_propagates_prompt_write_error() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);

        // Without --force the guard writes the prompt first; the failing
        // writer surfaces that IO error before any API call.
        let cmd = reanchor_command(false, false);
        let mut reader = io::Cursor::new(b"y\n".to_vec());
        let mut writer = FailingWriter { fail_write: true };
        assert!(cmd
            .execute_with_io(&api, &mut reader, &mut writer)
            .await
            .is_err());
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_propagates_prompt_flush_error() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);

        // Writes go through but the guard's flush after the prompt fails.
        let cmd = reanchor_command(false, false);
        let mut reader = io::Cursor::new(b"y\n".to_vec());
        let mut writer = FailingWriter { fail_write: false };
        assert!(cmd
            .execute_with_io(&api, &mut reader, &mut writer)
            .await
            .is_err());
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_propagates_result_write_error() {
        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;
        let api = mock_api(&server);

        // With --force the guard writes nothing; the re-anchor succeeds and
        // the failure comes from writing the success message.
        let cmd = reanchor_command(true, false);
        let mut reader = io::Cursor::new(Vec::new());
        let mut writer = FailingWriter { fail_write: true };
        assert!(cmd
            .execute_with_io(&api, &mut reader, &mut writer)
            .await
            .is_err());
        let requests = server.received_requests().await.unwrap();
        assert!(requests
            .iter()
            .any(|r| r.method == wiremock::http::Method::PUT));
    }
}