vimanam 1.1.0

OpenAPI/Swagger to Markdown documentation generator with grouping, filtering, and detail levels for docs and LLM context
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
use assert_cmd::Command;
use predicates::prelude::*;
use std::io::Write;

const OAS3: &str = "tests/fixtures/petstore_oas3.json";
const OAS2: &str = "tests/fixtures/petstore_oas2.json";
const OAS3_SCHEMA_REFS: &str = "tests/fixtures/schema_refs_oas3.json";
const OAS3_MULTI_AUTH: &str = "tests/fixtures/multi_auth_oas3.json";
const OAS2_MULTI_AUTH: &str = "tests/fixtures/multi_auth_oas2.json";
const OAS3_EXAMPLES: &str = "tests/fixtures/examples_oas3.json";
const OAS3_REF_BODY: &str = "tests/fixtures/ref_request_body_oas3.json";

// YAML twin of petstore_oas3.json — must parse to identical documentation (#4).
const OAS3_YAML: &str = "tests/fixtures/petstore_oas3.yaml";
const OAS2_YAML: &str = "tests/fixtures/petstore_oas2.yaml";
const OAS3_SCHEMA_REFS_YAML: &str = "tests/fixtures/schema_refs_oas3.yaml";

// Parse-layer correctness cluster (issues #48, #50, #51, #54, #56, #60).
const MULTI_TAG: &str = "tests/fixtures/multi_tag_oas3.json";
const OAS2_HTTP_SCHEME: &str = "tests/fixtures/http_scheme_oas2.json";
const REF_PARAMETER: &str = "tests/fixtures/ref_parameter.json";
const REF_PATH_ITEM: &str = "tests/fixtures/ref_path_item.json";
const TYPE_ARRAY: &str = "tests/fixtures/type_array_nullable.json";
const MISSING_RESPONSES: &str = "tests/fixtures/missing_responses.json";
const OVERRIDE_PARAM: &str = "tests/fixtures/override_param.json";
const UNKNOWN_TAG: &str = "tests/fixtures/unknown_tag.json";

// --stats alignment with a service name wider than the SERVICE header (#42).
const STATS_LONG_SERVICE: &str = "tests/fixtures/stats_long_service_oas3.json";

fn vimanam() -> Command {
    Command::cargo_bin("vimanam").unwrap()
}

#[test]
fn version_flag_reports_crate_version() {
    vimanam()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn summary_lists_services_and_operations() {
    vimanam()
        .arg(OAS3)
        .assert()
        .success()
        .stdout(predicate::str::contains("# Petstore API"))
        .stdout(predicate::str::contains("- Pets"))
        .stdout(predicate::str::contains("- Store"))
        // Service prefix is stripped from operation IDs in the summary view
        .stdout(predicate::str::contains("* ListPets"));
}

#[test]
fn basic_detail_writes_endpoint_sections() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic"])
        .assert()
        .success()
        .stdout(predicate::str::contains("### Pets_ListPets"))
        .stdout(predicate::str::contains("**Operation:** GET /pets"))
        .stdout(predicate::str::contains("**Operation:** POST /pets"));
}

// Regression test: optional request bodies (no `required: true`) used to be
// dropped from the parameter table entirely.
#[test]
fn optional_request_body_is_documented() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `requestBody` | body | No | Pet to add |",
        ));
}

// `--required-only` drops parameters that are not required (explicit
// `required: false` or unspecified), keeping required ones.
#[test]
fn required_only_excludes_non_required_parameters() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard", "--required-only"])
        .assert()
        .success()
        // Required path parameter is kept.
        .stdout(predicate::str::contains("| `petId` | path | Yes |"))
        // Optional query parameter is dropped.
        .stdout(predicate::str::contains("| `limit` |").not());
}

#[test]
fn required_path_param_is_documented() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `petId` | path | Yes | ID of the pet |",
        ));
}

#[test]
fn exclude_deprecated_hides_endpoint() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Store_ListOrders"));

    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--exclude-deprecated"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Store_ListOrders").not());
}

#[test]
fn method_filter_excludes_other_methods() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--method-filter", "GET"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Pets_ListPets"))
        .stdout(predicate::str::contains("Pets_CreatePet").not());
}

// Regression test for #13: methods are stored uppercase, so a lowercase
// `--method-filter` value used to match nothing and silently empty the output.
#[test]
fn method_filter_is_case_insensitive() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--method-filter", "get"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Pets_ListPets"))
        .stdout(predicate::str::contains("Pets_CreatePet").not());
}

// Regression test for #19: a case-mismatched `--service-filter` used to
// silently omit all endpoints.
#[test]
fn service_filter_is_case_insensitive() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--service-filter", "pets"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Pets_ListPets"))
        .stdout(predicate::str::contains("Store_ListOrders").not());
}

#[test]
fn path_filter_excludes_other_paths() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--path-filter", "/store"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Store_ListOrders"))
        .stdout(predicate::str::contains("Pets_ListPets").not());
}

#[test]
fn include_auth_shows_servers_and_schemes() {
    vimanam()
        .arg(OAS3)
        .arg("--include-auth")
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "https://api.petstore.example.com/v1",
        ))
        .stdout(predicate::str::contains("apiKeyAuth"));
}

#[test]
fn flat_grouping_lists_all_endpoints() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--flat"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Endpoints"))
        .stdout(predicate::str::contains("### Pets_ListPets"))
        .stdout(predicate::str::contains("### Store_ListOrders"));
}

#[test]
fn oas2_spec_is_supported() {
    vimanam()
        .arg(OAS2)
        .args(["--detail", "standard", "--include-auth"])
        .assert()
        .success()
        .stdout(predicate::str::contains("# Petstore Legacy API"))
        // host + basePath are combined into a server URL
        .stdout(predicate::str::contains(
            "https://legacy.petstore.example.com/v2",
        ))
        .stdout(predicate::str::contains("Pets_CreatePet"))
        // OpenAPI 2.0 body responses infer application/json
        .stdout(predicate::str::contains(
            "| 200 | application/json | Created |",
        ));
}

// The OAS2 `schemes` field names the transfer protocol; a plain-HTTP spec must
// not be rendered with an assumed `https://` prefix. (Specs without `schemes`
// still default to https — covered by `oas2_spec_is_supported` above.)
#[test]
fn oas2_http_scheme_is_respected() {
    vimanam()
        .arg(OAS2_HTTP_SCHEME)
        .arg("--include-auth")
        .assert()
        .success()
        .stdout(predicate::str::contains("http://internal.example.com/v1"))
        .stdout(predicate::str::contains("https://internal.example.com").not());
}

#[test]
fn output_flag_writes_file() {
    let dir = tempfile::tempdir().unwrap();
    let out_path = dir.path().join("out.md");

    vimanam()
        .arg(OAS3)
        .args(["-o", out_path.to_str().unwrap()])
        .assert()
        .success();

    let content = std::fs::read_to_string(&out_path).unwrap();
    assert!(content.contains("# Petstore API"));
}

// --- YAML input support (#4) ---

// A YAML OpenAPI 3 spec parses just like its JSON counterpart.
#[test]
fn yaml_spec_is_parsed() {
    vimanam()
        .arg(OAS3_YAML)
        .args(["--detail", "basic"])
        .assert()
        .success()
        .stdout(predicate::str::contains("# Petstore API"))
        .stdout(predicate::str::contains("### Pets_ListPets"))
        .stdout(predicate::str::contains("**Operation:** GET /pets"));
}

// The YAML twin and the JSON fixture must produce byte-identical documentation:
// format is an input detail, not a semantic one. Also guards key-order determinism
// (IndexMap) across the YAML deserializer.
#[test]
fn yaml_and_json_produce_identical_output() {
    let render = |spec: &str| {
        vimanam()
            .arg(spec)
            .args(["--detail", "full", "--include-schemas", "--include-auth"])
            .output()
            .unwrap()
            .stdout
    };
    assert_eq!(
        render(OAS3),
        render(OAS3_YAML),
        "YAML and JSON inputs produced different output"
    );
}

// The Swagger 2.0 (OAS2) YAML twin and its JSON counterpart must produce byte-identical documentation.
#[test]
fn yaml_and_json_produce_identical_output_oas2() {
    let render = |spec: &str| {
        vimanam()
            .arg(spec)
            .args(["--detail", "full", "--include-schemas", "--include-auth"])
            .output()
            .unwrap()
            .stdout
    };
    assert_eq!(
        render(OAS2),
        render(OAS2_YAML),
        "OAS2 YAML and JSON inputs produced different output"
    );
}

// The $ref-heavy YAML twin of schema_refs_oas3.json must produce identical output.
#[test]
fn yaml_and_json_produce_identical_output_schema_refs() {
    let render = |spec: &str| {
        vimanam()
            .arg(spec)
            .args(["--detail", "full", "--include-schemas"])
            .output()
            .unwrap()
            .stdout
    };
    assert_eq!(
        render(OAS3_SCHEMA_REFS),
        render(OAS3_SCHEMA_REFS_YAML),
        "schema_refs YAML and JSON inputs produced different output"
    );
}

// Extension detection is case-insensitive (`.YAML` routes to the YAML parser).
#[test]
fn yaml_extension_is_case_insensitive() {
    let yaml = std::fs::read_to_string(OAS3_YAML).unwrap();
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("spec.YAML");
    std::fs::write(&path, yaml).unwrap();

    vimanam()
        .arg(&path)
        .assert()
        .success()
        .stdout(predicate::str::contains("# Petstore API"));
}

// A YAML spec with a non-YAML/JSON extension still parses: the JSON-first path
// falls back to the YAML parser.
#[test]
fn yaml_content_with_unknown_extension_falls_back() {
    let yaml = std::fs::read_to_string(OAS3_YAML).unwrap();
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("spec.txt");
    std::fs::write(&path, yaml).unwrap();

    vimanam()
        .arg(&path)
        .assert()
        .success()
        .stdout(predicate::str::contains("# Petstore API"));
}

// Malformed YAML fails with an error rather than panicking.
#[test]
fn invalid_yaml_fails() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("broken.yaml");
    std::fs::write(&path, "openapi: \"3.0.0\"\n  bad: : indentation:").unwrap();

    vimanam()
        .arg(&path)
        .assert()
        .failure()
        .stderr(predicate::str::contains("Error:"));
}

// A structurally-valid YAML document that isn't an OpenAPI spec reports the
// targeted missing-field error (and only that — no doubled fallback noise).
#[test]
fn yaml_without_openapi_fields_fails() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("notspec.yaml");
    std::fs::write(&path, "hello: world\n").unwrap();

    vimanam()
        .arg(&path)
        .assert()
        .failure()
        .stderr(predicate::str::contains(
            "Missing 'swagger' or 'openapi' field",
        ));
}

#[test]
fn invalid_json_fails() {
    let mut file = tempfile::NamedTempFile::new().unwrap();
    write!(file, "this is not json").unwrap();

    vimanam()
        .arg(file.path())
        .assert()
        .failure()
        .stderr(predicate::str::contains("Error:"));
}

#[test]
fn json_without_openapi_fields_fails() {
    let mut file = tempfile::NamedTempFile::new().unwrap();
    write!(file, "{{\"hello\": \"world\"}}").unwrap();

    vimanam()
        .arg(file.path())
        .assert()
        .failure()
        .stderr(predicate::str::contains("Error:"));
}

// Output must be byte-identical across runs, even with sorting disabled.
// Guards the IndexMap-based ordering of paths, responses, and content types.
#[test]
fn output_is_deterministic() {
    let run = || {
        vimanam()
            .arg(OAS3)
            .args([
                "--detail",
                "full",
                "--include-schemas",
                "--include-auth",
                "--sort",
                "none",
            ])
            .output()
            .unwrap()
            .stdout
    };

    let first = run();
    for _ in 0..4 {
        assert_eq!(first, run(), "output differed between identical runs");
    }
}

// By default (#58) component schemas are linked from their use site and expanded
// once in a trailing "Schema Definitions" section, rather than re-inlined.
#[test]
fn full_detail_links_schema_refs_to_definitions() {
    vimanam()
        .arg(OAS3_SCHEMA_REFS)
        .args(["--detail", "full", "--include-schemas"])
        .assert()
        .success()
        // The use site is a single linked row, not a re-inlined subtree.
        .stdout(predicate::str::contains(
            "| `request` | [CreatePetRequest](#schema-createpetrequest) | - | - |",
        ))
        .stdout(predicate::str::contains(
            "| `response` | [Pet](#schema-pet) | - | - |",
        ))
        // The shared schemas are expanded once in the definitions section.
        .stdout(predicate::str::contains("## Schema Definitions"))
        .stdout(predicate::str::contains(
            "### CreatePetRequest {#schema-createpetrequest}",
        ))
        .stdout(predicate::str::contains(
            "| `CreatePetRequest.name` | string | Yes | Pet name |",
        ))
        .stdout(predicate::str::contains(
            "| `CreatePetRequest.category` | [Category](#schema-category) | Yes |",
        ))
        .stdout(predicate::str::contains(
            "| `Category.id` | string | Yes | Category identifier |",
        ))
        .stdout(predicate::str::contains(
            "| `Pet.allOf[1].id` | string | Yes | Pet identifier |",
        ));
}

// CreatePetRequest is referenced from the /pets request body and again from
// Pet's `allOf`; it must be expanded exactly once (the #58 win).
#[test]
fn shared_schema_is_expanded_once() {
    let output = String::from_utf8(
        vimanam()
            .arg(OAS3_SCHEMA_REFS)
            .args(["--detail", "full", "--include-schemas"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    let definitions = output
        .matches("### CreatePetRequest {#schema-createpetrequest}")
        .count();
    assert_eq!(
        definitions, 1,
        "CreatePetRequest expanded {definitions} times"
    );
}

// A self-referential schema (Node.next -> Node) renders once and links back to
// itself instead of looping or printing a "cycle detected" row.
#[test]
fn linked_mode_handles_self_reference_with_a_link() {
    vimanam()
        .arg(OAS3_SCHEMA_REFS)
        .args(["--detail", "full", "--include-schemas"])
        .assert()
        .success()
        .stdout(predicate::str::contains("### Node {#schema-node}"))
        .stdout(predicate::str::contains(
            "| `Node.next` | [Node](#schema-node) | No |",
        ))
        .stdout(predicate::str::contains("Cycle detected").not());
}

// `--inline-schemas` restores the fully self-contained output: every `$ref` is
// expanded inline at each use site, with no shared definitions section.
#[test]
fn inline_schemas_expands_refs_at_each_use_site() {
    vimanam()
        .arg(OAS3_SCHEMA_REFS)
        .args(["--detail", "full", "--include-schemas", "--inline-schemas"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `request.name` | string | Yes | Pet name |",
        ))
        .stdout(predicate::str::contains(
            "| `request.category.id` | string | Yes | Category identifier |",
        ))
        .stdout(predicate::str::contains(
            "| `response.allOf[1].id` | string | Yes | Pet identifier |",
        ))
        .stdout(predicate::str::contains("request.variant.oneOf[0]"))
        .stdout(predicate::str::contains("## Schema Definitions").not());
}

// #69 follow-up: the "no effect" warning reports the current detail level in the
// same lowercase spelling the user types (`standard`), not the Debug-derived
// `Standard`.
#[test]
fn include_schemas_warning_uses_lowercase_detail_name() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard", "--include-schemas"])
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "--include-schemas has no effect at --detail standard; use --detail full.",
        ));
}

// At `--detail full` the flag takes effect, so no warning is emitted.
#[test]
fn include_schemas_at_full_detail_emits_no_warning() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "full", "--include-schemas"])
        .assert()
        .success()
        .stderr(predicate::str::contains("no effect").not());
}

// `--inline-schemas` only changes how schemas render, so it warns when used
// without `--include-schemas`.
#[test]
fn inline_schemas_without_include_schemas_warns() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "full", "--inline-schemas"])
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "--inline-schemas has no effect without --include-schemas.",
        ));
}

// `--required-only` only filters the parameters table, which basic/summary
// detail never renders — so it warns there like the other no-effect flags.
#[test]
fn required_only_at_basic_detail_warns() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--required-only"])
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "--required-only has no effect at --detail basic; use --detail standard or full.",
        ));
}

// At `--detail standard` the flag takes effect, so no warning is emitted.
#[test]
fn required_only_at_standard_detail_emits_no_warning() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard", "--required-only"])
        .assert()
        .success()
        .stderr(predicate::str::contains("no effect").not());
}

// `--toc` is the explicit opposite of `--no-toc`; the TOC is on by default, and
// when both flags are given the later one wins.
#[test]
fn toc_flag_is_accepted_and_last_one_wins() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--toc"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Services"));

    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--no-toc", "--toc"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Services"));

    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--toc", "--no-toc"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Services").not());
}

// #70 follow-up: an operation carrying multiple tags is rendered under each
// service section, so its heading anchor must be scoped per service to stay
// unique — and each TOC link must point at the matching copy.
#[test]
fn multi_tag_endpoint_gets_unique_anchors_per_service() {
    let output = String::from_utf8(
        vimanam()
            .arg(MULTI_TAG)
            .args(["--detail", "basic"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    // Distinct, service-scoped heading anchors (no duplicate `#delete-pets-petid`).
    assert!(
        output.contains("### DeletePet {#pets-delete-pets-petid}"),
        "missing Pets-scoped anchor:\n{output}"
    );
    assert!(
        output.contains("### DeletePet {#admin-delete-pets-petid}"),
        "missing Admin-scoped anchor:\n{output}"
    );

    // Each TOC entry links to the copy under its own service.
    assert!(
        output.contains("* [DeletePet](#pets-delete-pets-petid)")
            && output.contains("* [DeletePet](#admin-delete-pets-petid)"),
        "TOC links do not match per-service anchors:\n{output}"
    );
}

// Regression test for #16: the Authentication section is emitted in spec
// (file) order, not the random order of a HashMap, and is stable across runs.
#[test]
fn multiple_security_schemes_preserve_spec_order() {
    let run = || {
        String::from_utf8(
            vimanam()
                .arg(OAS3_MULTI_AUTH)
                .arg("--include-auth")
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap()
    };

    let output = run();

    let zebra = output.find("zebraAuth").expect("zebraAuth missing");
    let api_key = output.find("apiKeyAuth").expect("apiKeyAuth missing");
    let middle = output.find("middleAuth").expect("middleAuth missing");

    // Schemes appear in the order they are declared in the spec file.
    assert!(
        zebra < api_key && api_key < middle,
        "security schemes not in spec order: {output}"
    );

    // And that order is deterministic across runs.
    for _ in 0..4 {
        assert_eq!(output, run(), "authentication order differed between runs");
    }
}

// Companion to #16 for OpenAPI 2.0: `securityDefinitions` are read through the
// extensions map, so they only preserve spec order with serde_json's
// `preserve_order` feature (otherwise they sort alphabetically). The schemes
// are declared zebra/apiKey/middle, which is not alphabetical.
#[test]
fn oas2_security_schemes_preserve_spec_order() {
    let output = String::from_utf8(
        vimanam()
            .arg(OAS2_MULTI_AUTH)
            .arg("--include-auth")
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    let zebra = output.find("zebraAuth").expect("zebraAuth missing");
    let api_key = output.find("apiKey").expect("apiKey missing");
    let middle = output.find("middleAuth").expect("middleAuth missing");

    assert!(
        zebra < api_key && api_key < middle,
        "OAS2 security schemes not in spec order: {output}"
    );
}

// Regression test for #20: `--group-by method` must behave like `--method`,
// producing HTTP-method sections rather than service sections.
#[test]
fn group_by_method_groups_by_http_method() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--group-by", "method"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## GET"))
        .stdout(predicate::str::contains("## POST"));
}

// Regression test for #18: under alphabetical sort the TOC operation links must
// appear in the same order as the endpoint sections in the body.
#[test]
fn toc_order_matches_body_order() {
    let output = String::from_utf8(
        vimanam()
            .arg(OAS3)
            .args(["--detail", "basic", "--sort", "alpha"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    // The Pets service has CreatePet (POST /pets) and ListPets (GET /pets);
    // sorted by path then method, GET sorts before POST, so ListPets precedes
    // CreatePet in both the TOC and the body.
    let toc_list = output
        .find("[Pets_ListPets]")
        .expect("ListPets TOC link missing");
    let toc_create = output
        .find("[Pets_CreatePet]")
        .expect("CreatePet TOC link missing");
    let body_list = output
        .find("### Pets_ListPets")
        .expect("ListPets section missing");
    let body_create = output
        .find("### Pets_CreatePet")
        .expect("CreatePet section missing");

    assert!(toc_list < toc_create, "TOC order unexpected: {output}");
    assert!(body_list < body_create, "body order unexpected: {output}");
}

// #6: `--include-examples` at `--detail full` renders the request body's inline
// example and the response example resolved from a `$ref` into
// `components/examples`.
#[test]
fn include_examples_renders_request_and_response() {
    vimanam()
        .arg(OAS3_EXAMPLES)
        .args(["--detail", "full", "--include-examples"])
        .assert()
        .success()
        .stdout(predicate::str::contains("#### Examples"))
        // Inline request body example.
        .stdout(predicate::str::contains("**Request**"))
        .stdout(predicate::str::contains("\"name\": \"Fluffy\""))
        // Response example resolved through #/components/examples/CreatedPet.
        .stdout(predicate::str::contains("Response `201`"))
        .stdout(predicate::str::contains("\"id\": 7"));
}

// Examples only render at `--detail full`, matching `--include-schemas`.
#[test]
fn include_examples_only_at_full_detail() {
    vimanam()
        .arg(OAS3_EXAMPLES)
        .args(["--detail", "standard", "--include-examples"])
        .assert()
        .success()
        .stdout(predicate::str::contains("#### Examples").not());
}

// A `requestBody` given as a `$ref` into `components/requestBodies` is resolved
// during parsing: its description/required surface in the parameter table, and
// at `--detail full` its referenced schema expands. Before resolution such a
// spec failed to parse at all.
#[test]
fn ref_request_body_is_resolved() {
    vimanam()
        .arg(OAS3_REF_BODY)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `requestBody` | body | Yes | Pet to add |",
        ));

    vimanam()
        .arg(OAS3_REF_BODY)
        .args(["--detail", "full", "--include-schemas"])
        .assert()
        .success()
        // The resolved body schema is linked and expanded in the definitions
        // section.
        .stdout(predicate::str::contains("## Schema Definitions"))
        .stdout(predicate::str::contains(
            "| `Pet.name` | string | Yes | Pet name |",
        ));
}

// #8: `--group-by path` produces one section per path with its operations
// underneath.
#[test]
fn group_by_path_groups_by_path() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--group-by", "path"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Paths"))
        .stdout(predicate::str::contains("## /pets/{petId}"))
        .stdout(predicate::str::contains("## /store/orders"))
        .stdout(predicate::str::contains("### Pets_ListPets"))
        .stdout(predicate::str::contains("### Pets_CreatePet"));
}

// #7: a tiny `--max-tokens` budget forces a full-detail request down to a lower
// detail level and reports the reduction on stderr.
#[test]
fn max_tokens_steps_down_detail_level() {
    vimanam()
        .arg(OAS3)
        .args([
            "--detail",
            "full",
            "--include-schemas",
            "--max-tokens",
            "40",
        ])
        .assert()
        .success()
        .stderr(predicate::str::contains("token budget"))
        .stderr(predicate::str::contains("--detail summary"));
}

// A generous `--max-tokens` budget leaves the requested detail untouched and
// emits no stderr note.
#[test]
fn max_tokens_keeps_detail_when_it_fits() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--max-tokens", "100000"])
        .assert()
        .success()
        .stdout(predicate::str::contains("### Pets_ListPets"))
        .stderr(predicate::str::is_empty());
}

// Under `--inline-schemas` the recursive expansion still guards against `$ref`
// cycles, breaking the chain with a "cycle detected" row.
#[test]
fn inline_schema_expansion_detects_ref_cycles() {
    vimanam()
        .arg(OAS3_SCHEMA_REFS)
        .args(["--detail", "full", "--include-schemas", "--inline-schemas"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Cycle detected while expanding schema reference",
        ));
}

// #48: a parameter declared as a component `$ref` is resolved instead of
// failing the whole parse (a bare `$ref` param used to crash on `missing field name`).
#[test]
fn ref_parameter_is_resolved() {
    vimanam()
        .arg(REF_PARAMETER)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `limit` | query | No | Max results |",
        ));
}

// #50: a path item declared as a `$ref` yields its operation instead of being
// silently dropped.
#[test]
fn path_item_ref_yields_operation() {
    vimanam()
        .arg(REF_PATH_ITEM)
        .args(["--detail", "basic"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Things_ListThings"))
        .stdout(predicate::str::contains("**Operation:** GET /things"));
}

// #51: OpenAPI 3.1 `type` arrays (e.g. ["string","null"]) parse instead of
// failing on "invalid type: sequence".
#[test]
fn type_array_parameter_parses() {
    vimanam()
        .arg(TYPE_ARRAY)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `q` | query | No | Search term |",
        ));
}

// #56: an operation missing its `responses` block no longer fails the whole
// document; both operations are still rendered.
#[test]
fn operation_missing_responses_still_parses() {
    vimanam()
        .arg(MISSING_RESPONSES)
        .args(["--detail", "basic"])
        .assert()
        .success()
        .stdout(predicate::str::contains("A_NoResponses"))
        .stdout(predicate::str::contains("B_HasResponses"));
}

// #54: an operation-level parameter overrides a path-level one of the same
// (name, in) — it should appear exactly once.
#[test]
fn duplicate_parameter_is_deduplicated() {
    let output = vimanam()
        .arg(OVERRIDE_PARAM)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(output).unwrap();
    let id_rows = text.matches("| `id` | path |").count();
    assert_eq!(id_rows, 1, "expected a single `id` row, got {id_rows}");
    // The operation-level definition wins.
    assert!(text.contains("Operation-level id wins"));
}

// #60: an operation tagged with a value not in the declared `tags` list gets its
// own service section instead of being silently reassigned to the first service.
#[test]
fn unknown_operation_tag_keeps_its_own_service() {
    vimanam()
        .arg(UNKNOWN_TAG)
        .args(["--detail", "basic"])
        .assert()
        .success()
        // The undeclared tag Gamma becomes its own service section (under the
        // bug it would not exist — the endpoint was dumped under Alpha)...
        .stdout(predicate::str::contains("## Gamma"))
        .stdout(predicate::str::contains("W_Get"))
        // ...and the first declared service ends up with no endpoints.
        .stdout(predicate::str::contains(
            "## Alpha {#alpha}\n\nNo endpoints found for this service.",
        ));
}

// Shell completions (#41): `vimanam completions <SHELL>` prints a completion
// script for every shell clap_complete supports, without needing a spec file.
#[test]
fn completions_are_generated_for_each_supported_shell() {
    // Each shell is paired with a marker unique to its script format, so the
    // test fails if every shell were to emit the same (e.g. bash) script.
    let shells = [
        ("bash", "complete -F _vimanam"),
        ("zsh", "#compdef vimanam"),
        ("fish", "complete -c vimanam"),
        ("powershell", "Register-ArgumentCompleter"),
        ("elvish", "edit:completion:arg-completer[vimanam]"),
    ];
    for (shell, marker) in shells {
        vimanam()
            .args(["completions", shell])
            .assert()
            .success()
            .stdout(predicate::str::contains(marker))
            .stderr(predicate::str::is_empty());
    }

    // The script must actually cover the CLI's options.
    vimanam()
        .args(["completions", "bash"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--group-by"));
}

#[test]
fn completions_rejects_unsupported_shell() {
    vimanam()
        .args(["completions", "nushell"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("invalid value 'nushell'"));
}

#[test]
fn completions_requires_a_shell() {
    vimanam()
        .arg("completions")
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("<SHELL>"));
}

// The subcommand must not loosen the normal path: with no subcommand the spec
// file is still required.
#[test]
fn no_arguments_still_requires_input_file() {
    vimanam()
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("<FILE>"));
}

// Conversion flags and the spec file are meaningless alongside a subcommand,
// so mixing them is an error rather than being silently ignored.
#[test]
fn completions_conflicts_with_conversion_arguments() {
    vimanam()
        .args([OAS3, "completions", "bash"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot be used with"));
}

// --- Spec hygiene report (#44) ---

// A spec that trips every hygiene check at least once.
const HYGIENE: &str = "tests/fixtures/hygiene_oas3.json";
// One operation whose undescribed requestBody offers two media types.
const HYGIENE_MULTI_BODY: &str = "tests/fixtures/hygiene_multi_body_oas3.json";

// The report is appended after the body by default, separated by a rule.
#[test]
fn hygiene_report_is_appended_by_default() {
    vimanam()
        .arg(OAS3)
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "\n---\n\n## Spec Hygiene Report\n",
        ))
        .stdout(predicate::str::contains(
            "**4 endpoints** across **2 services**",
        ))
        .stdout(predicate::str::contains("| Deprecated | 1 |"))
        .stdout(predicate::str::contains(
            "### Deprecated (1)\n- `GET /store/orders`\n",
        ));
}

#[test]
fn no_report_suppresses_hygiene_report() {
    vimanam()
        .arg(OAS3)
        .arg("--no-report")
        .assert()
        .success()
        .stdout(predicate::str::contains("# Petstore API"))
        .stdout(predicate::str::contains("Spec Hygiene Report").not())
        .stdout(predicate::str::contains("\n---\n").not());
}

// Every check fires on the hygiene fixture; the whole report is asserted
// byte-for-byte so its shape (table order, list order, list item format) is
// pinned down.
#[test]
fn hygiene_report_lists_every_check() {
    let output = String::from_utf8(
        vimanam()
            .arg(HYGIENE)
            .args(["--detail", "standard"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    // A plain multi-line literal (no `\` continuations) so the two-space
    // indentation of the nested duplicate-operationId items is preserved.
    let expected = "
---

## Spec Hygiene Report

**6 endpoints** across **2 services**

| Check | Count |
|-------|------:|
| Missing description | 1 |
| Missing operationId | 1 |
| No responses documented | 1 |
| Deprecated | 2 |
| Untagged (no service tag) | 1 |
| Duplicate operationIds | 1 |
| Parameters without description | 3 |

### Missing description (1)
- `GET /health`

### Missing operationId (1)
- `GET /health`

### No responses documented (1)
- `POST /users`

### Deprecated (2)
- `GET /ping`
- `DELETE /users/{id}`

### Untagged (no service tag) (1)
- `GET /health`

### Duplicate operationIds (1)
- `getUser`
  - `DELETE /users/{id}`
  - `GET /users/{id}`

### Parameters without description (3)
- `GET /users` — `limit`
- `POST /users` — `requestBody`
- `DELETE /users/{id}` — `id`
";

    assert!(
        output.ends_with(expected),
        "report did not match.\nexpected tail:\n{expected}\nactual output:\n{output}"
    );
    // The body precedes the report.
    assert!(output.starts_with("# Hygiene API\n"), "{output}");
}

// The report analyzes the same endpoint set the body rendered: a service
// filter narrows both the counts and the service total.
#[test]
fn hygiene_report_respects_service_filter() {
    vimanam()
        .arg(HYGIENE)
        .args(["--service-filter", "Health"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "**1 endpoint** across **1 service**",
        ))
        .stdout(predicate::str::contains("| Deprecated | 1 |"))
        .stdout(predicate::str::contains(
            "| Untagged (no service tag) | 0 |",
        ))
        .stdout(predicate::str::contains("| Duplicate operationIds | 0 |"))
        .stdout(predicate::str::contains(
            "### Deprecated (1)\n- `GET /ping`\n",
        ))
        .stdout(predicate::str::contains("GET /health").not());
}

// `--exclude-deprecated` removes the deprecated DELETE, which also dissolves
// the duplicate operationId pair and drops its undescribed parameter; the
// deprecated GET /ping was the only Health endpoint, so one service remains.
#[test]
fn hygiene_report_respects_exclude_deprecated() {
    vimanam()
        .arg(HYGIENE)
        .arg("--exclude-deprecated")
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "**4 endpoints** across **1 service**",
        ))
        .stdout(predicate::str::contains("| Deprecated | 0 |"))
        .stdout(predicate::str::contains("| Duplicate operationIds | 0 |"))
        .stdout(predicate::str::contains(
            "| Parameters without description | 2 |",
        ))
        .stdout(predicate::str::contains("### Deprecated").not())
        .stdout(predicate::str::contains("### Duplicate operationIds").not());
}

// `--max-tokens` budgets the body only; the report is still appended.
#[test]
fn hygiene_report_is_appended_under_max_tokens() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "full", "--max-tokens", "40"])
        .assert()
        .success()
        .stderr(predicate::str::contains("token budget"))
        .stdout(predicate::str::contains("## Spec Hygiene Report"));
}

// The file output path appends the report just like stdout does.
#[test]
fn hygiene_report_is_written_to_output_file() {
    let dir = tempfile::tempdir().unwrap();
    let out_path = dir.path().join("out.md");

    vimanam()
        .arg(HYGIENE)
        .args(["-o", out_path.to_str().unwrap()])
        .assert()
        .success();

    let content = std::fs::read_to_string(&out_path).unwrap();
    assert!(content.starts_with("# Hygiene API\n"), "{content}");
    assert!(
        content.contains("\n---\n\n## Spec Hygiene Report\n"),
        "{content}"
    );
    assert!(
        content.contains("| Duplicate operationIds | 1 |"),
        "{content}"
    );
}

// The report is deterministic even with `--sort none` (spec order), where
// nothing but stable collections keeps the lists in a fixed order.
#[test]
fn hygiene_report_is_deterministic() {
    let run = || {
        vimanam()
            .arg(HYGIENE)
            .args(["--detail", "full", "--sort", "none"])
            .output()
            .unwrap()
            .stdout
    };

    let first = run();
    for _ in 0..4 {
        assert_eq!(first, run(), "report differed between identical runs");
    }
}

// The parser emits one synthetic body parameter per requestBody media type,
// all sharing the request body's description; an undescribed body is reported
// once per endpoint, not once per media type.
#[test]
fn hygiene_report_counts_multi_media_type_body_once() {
    let output = String::from_utf8(
        vimanam()
            .arg(HYGIENE_MULTI_BODY)
            .args(["--detail", "standard"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    // The body still documents both media types...
    assert!(
        output.contains("`requestBody (application/json)` | body |"),
        "{output}"
    );
    assert!(
        output.contains("`requestBody (application/xml)` | body |"),
        "{output}"
    );
    // ...but the report flags the body once.
    assert!(
        output.contains("| Parameters without description | 1 |"),
        "{output}"
    );
    assert!(
        output.ends_with(
            "### Parameters without description (1)\n- `POST /items` — `requestBody (application/json)`\n"
        ),
        "{output}"
    );
    assert_eq!(
        output.matches("- `POST /items` — `requestBody").count(),
        1,
        "{output}"
    );
}

// Exactly one blank line separates the body from the report at every detail
// level, even though the views themselves end with differing trailing
// whitespace (one newline at summary, a blank line otherwise).
#[test]
fn hygiene_report_is_separated_from_body_by_one_blank_line() {
    for detail in ["summary", "basic", "standard", "full"] {
        vimanam()
            .arg(OAS3)
            .args(["--detail", detail])
            .assert()
            .success()
            .stdout(predicate::str::contains(
                "\n\n---\n\n## Spec Hygiene Report",
            ))
            .stdout(predicate::str::contains("\n\n\n---").not());
    }
}

// A multi-tag operation is rendered under each of its services but analyzed
// once; the service count still reflects every service it appears in.
#[test]
fn hygiene_report_counts_multi_tag_endpoint_once() {
    vimanam()
        .arg(MULTI_TAG)
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "**1 endpoint** across **2 services**",
        ));
}

// Filters that leave nothing visible produce an all-zero report with no
// detail sections, and no services (only services with visible endpoints
// are counted).
#[test]
fn hygiene_report_on_empty_filtered_set_is_all_zero() {
    let output = String::from_utf8(
        vimanam()
            .arg(OAS3)
            .args(["--path-filter", "/nope"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    let expected = "\
## Spec Hygiene Report

**0 endpoints** across **0 services**

| Check | Count |
|-------|------:|
| Missing description | 0 |
| Missing operationId | 0 |
| No responses documented | 0 |
| Deprecated | 0 |
| Untagged (no service tag) | 0 |
| Duplicate operationIds | 0 |
| Parameters without description | 0 |
";
    assert!(output.ends_with(expected), "{output}");
    assert!(!output.contains("\n### "), "{output}");
}

// --- --stats token-budget dry-run (#42) ---

fn stats_output(args: &[&str]) -> String {
    let output = vimanam().args(args).output().unwrap();
    assert!(output.status.success(), "{output:?}");
    assert!(
        output.stderr.is_empty(),
        "stats wrote to stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout).unwrap()
}

// Splits a stats table into (service, endpoints, ~tokens) rows, header excluded.
fn stats_rows(table: &str) -> Vec<(String, usize, usize)> {
    let mut lines = table.lines();
    assert_eq!(
        lines
            .next()
            .map(|line| line.split_whitespace().collect::<Vec<_>>()),
        Some(vec!["SERVICE", "ENDPOINTS", "~TOKENS"]),
        "{table}"
    );
    lines
        .map(|line| {
            let mut fields = line.split_whitespace().rev();
            let tokens: usize = fields.next().unwrap().parse().unwrap();
            let endpoints: usize = fields.next().unwrap().parse().unwrap();
            let name: Vec<&str> = fields.rev().collect();
            (name.join(" "), endpoints, tokens)
        })
        .collect()
}

// Petstore declares Pets (GET /pets, POST /pets, GET /pets/{petId}) and Store
// (GET /store/orders): one row each in declared order, then a TOTAL of 4.
#[test]
fn stats_lists_each_service_with_endpoint_counts_and_total() {
    let table = stats_output(&[OAS3, "--stats"]);
    let rows = stats_rows(&table);

    assert_eq!(rows.len(), 3, "{table}");
    assert_eq!((rows[0].0.as_str(), rows[0].1), ("Pets", 3));
    assert_eq!((rows[1].0.as_str(), rows[1].1), ("Store", 1));
    assert_eq!((rows[2].0.as_str(), rows[2].1), ("TOTAL", 4));
    for (name, _, tokens) in &rows {
        assert!(*tokens > 0, "{name} has no token estimate: {table}");
    }

    // Plain text only: no blank lines, no Markdown, one trailing newline.
    assert!(table.ends_with('\n') && !table.ends_with("\n\n"), "{table}");
    assert!(!table.contains("\n\n"), "{table}");
    assert!(!table.contains('#') && !table.contains('|'), "{table}");
}

// The exact layout: SERVICE padded to the widest name (the header here),
// numeric columns right-aligned under their headers, three spaces between.
#[test]
fn stats_columns_are_aligned() {
    let table = stats_output(&[OAS3, "--stats"]);
    let lines: Vec<&str> = table.lines().collect();

    assert_eq!(lines[0], "SERVICE   ENDPOINTS   ~TOKENS");
    assert!(lines[1].starts_with("Pets              3   "), "{table}");
    assert!(lines[2].starts_with("Store             1   "), "{table}");
    assert!(lines[3].starts_with("TOTAL             4   "), "{table}");
    let width = lines[0].len();
    assert!(lines.iter().all(|line| line.len() == width), "{table}");
}

#[test]
fn stats_is_deterministic() {
    let first = stats_output(&[OAS3, "--stats", "--detail", "full", "--include-schemas"]);
    let second = stats_output(&[OAS3, "--stats", "--detail", "full", "--include-schemas"]);
    assert_eq!(first, second);
}

// More detail renders more text, so the estimate for the same service grows.
#[test]
fn stats_tokens_grow_with_detail_level() {
    let summary = stats_rows(&stats_output(&[OAS3, "--stats", "--detail", "summary"]));
    let full = stats_rows(&stats_output(&[
        OAS3,
        "--stats",
        "--detail",
        "full",
        "--include-schemas",
    ]));

    for (row, summary_row) in full.iter().zip(&summary) {
        assert_eq!(row.0, summary_row.0);
        assert!(
            row.2 > summary_row.2,
            "{}: full {} <= summary {}",
            row.0,
            row.2,
            summary_row.2
        );
    }
}

#[test]
fn stats_respects_service_filter() {
    let rows = stats_rows(&stats_output(&[
        OAS3,
        "--stats",
        "--service-filter",
        "store",
    ]));

    assert_eq!(rows.len(), 2);
    assert_eq!((rows[0].0.as_str(), rows[0].1), ("Store", 1));
    assert_eq!((rows[1].0.as_str(), rows[1].1), ("TOTAL", 1));
}

// A multi-tag operation is counted in each of its service rows but once in
// the TOTAL, so the TOTAL is not the sum of the rows.
#[test]
fn stats_counts_multi_tag_endpoint_in_each_service_but_once_in_total() {
    let rows = stats_rows(&stats_output(&[MULTI_TAG, "--stats"]));

    assert_eq!(rows.len(), 3);
    assert_eq!((rows[0].0.as_str(), rows[0].1), ("Pets", 1));
    assert_eq!((rows[1].0.as_str(), rows[1].1), ("Admin", 1));
    assert_eq!((rows[2].0.as_str(), rows[2].1), ("TOTAL", 1));
}

// The hygiene fixture's Users service has 5 endpoints (one deprecated) and
// Health has only a deprecated one; excluding deprecated drops Users to 4 and
// removes the Health row entirely.
#[test]
fn stats_respects_exclude_deprecated() {
    let all = stats_rows(&stats_output(&[HYGIENE, "--stats"]));
    assert_eq!(all.len(), 3);
    assert_eq!((all[0].0.as_str(), all[0].1), ("Users", 5));
    assert_eq!((all[1].0.as_str(), all[1].1), ("Health", 1));
    assert_eq!((all[2].0.as_str(), all[2].1), ("TOTAL", 6));

    let live = stats_rows(&stats_output(&[HYGIENE, "--stats", "--exclude-deprecated"]));
    assert_eq!(live.len(), 2);
    assert_eq!((live[0].0.as_str(), live[0].1), ("Users", 4));
    assert_eq!((live[1].0.as_str(), live[1].1), ("TOTAL", 4));
}

// Filters that leave nothing visible still print the header and a zero TOTAL.
#[test]
fn stats_on_empty_filtered_set_is_header_and_zero_total() {
    let table = stats_output(&[OAS3, "--stats", "--path-filter", "/nope"]);
    assert_eq!(
        table,
        "\
SERVICE   ENDPOINTS   ~TOKENS
TOTAL             0         0
"
    );
}

// The hygiene report is never part of stats output, whatever --no-report says.
#[test]
fn stats_never_includes_hygiene_report() {
    let table = stats_output(&[OAS3, "--stats"]);
    assert!(!table.contains("Spec Hygiene Report"), "{table}");
    assert!(!table.contains("---"), "{table}");

    let with_flag = stats_output(&[OAS3, "--stats", "--no-report"]);
    assert_eq!(table, with_flag);
}

// Renders the document with `args` and returns the chars/4 token estimate of
// the resulting Markdown, exactly as `--max-tokens` and `--stats` compute it.
fn rendered_tokens(args: &[&str]) -> usize {
    let output = vimanam().args(args).arg("--no-report").output().unwrap();
    assert!(output.status.success(), "{output:?}");
    String::from_utf8(output.stdout)
        .unwrap()
        .chars()
        .count()
        .div_ceil(4)
}

// Each row's estimate must equal a real render of that service alone under the
// same flags, and TOTAL a real render of the whole document, so the table can
// be trusted as a menu for `--service-filter`.
fn assert_stats_match_real_render(render_args: &[&str]) {
    let mut stats_args = vec![OAS3, "--stats"];
    stats_args.extend_from_slice(render_args);
    let table = stats_output(&stats_args);
    let rows = stats_rows(&table);
    assert!(rows.len() > 1, "{table}");

    for (name, _, tokens) in &rows {
        let mut args = vec![OAS3];
        args.extend_from_slice(render_args);
        if name != "TOTAL" {
            args.extend_from_slice(&["--service-filter", name]);
        }
        assert_eq!(
            *tokens,
            rendered_tokens(&args),
            "{name} estimate disagrees with a real render: {table}"
        );
    }
}

#[test]
fn stats_row_tokens_match_real_render() {
    assert_stats_match_real_render(&["--detail", "full", "--include-schemas"]);
}

// The flat view renders differently from the service view; the estimate must
// follow the grouping flag rather than always sizing the service view.
#[test]
fn stats_row_tokens_match_real_render_under_flat() {
    assert_stats_match_real_render(&["--flat", "--detail", "standard"]);
}

// A service name wider than the SERVICE header widens the first column: the
// header is padded to the name, and every line still has the same length.
#[test]
fn stats_pads_service_column_to_a_long_name() {
    let table = stats_output(&[STATS_LONG_SERVICE, "--stats"]);
    let lines: Vec<&str> = table.lines().collect();
    let name = "Long Service Name";

    assert_eq!(lines.len(), 3, "{table}");
    assert!(
        lines[0].starts_with(&format!(
            "{:<width$}   ENDPOINTS",
            "SERVICE",
            width = name.len()
        )),
        "{table}"
    );
    assert!(lines[1].starts_with(&format!("{name}   ")), "{table}");
    assert!(
        lines[2].starts_with(&format!("{:<width$}   ", "TOTAL", width = name.len())),
        "{table}"
    );
    let width = lines[0].chars().count();
    assert!(
        lines.iter().all(|line| line.chars().count() == width),
        "{table}"
    );

    let rows = stats_rows(&table);
    assert_eq!((rows[0].0.as_str(), rows[0].1), (name, 2));
    assert_eq!((rows[1].0.as_str(), rows[1].1), ("TOTAL", 2));
}

// Writing a stats table to a file and budgeting a dry run are both
// meaningless; clap rejects the combinations with its usage error.
#[test]
fn stats_conflicts_with_output() {
    vimanam()
        .args([OAS3, "--stats", "-o", "stats.txt"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("cannot be used with"));
}

#[test]
fn stats_conflicts_with_max_tokens() {
    vimanam()
        .args([OAS3, "--stats", "--max-tokens", "100"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("cannot be used with"));
}

// --- diff subcommand (#45) ---

// Two versions of one spec. `new` adds a required `pricing` property to the
// shared `Widget` schema while leaving the `GET /widgets` operation object
// byte-identical, removes the deprecated `GET /legacy`, adds
// `GET /widgets/{id}/history`, makes the `fields` query parameter required and
// drops the 404 response on `GET /widgets/{id}`, renames and deprecates the
// `DELETE /widgets/{id}` operation, changes `WidgetInput.weight` from float
// to double, and rewords descriptions only (the `X-Trace` header, the
// `WidgetInput.name` property).
const DIFF_OLD: &str = "tests/fixtures/diff_old_oas3.json";
const DIFF_NEW: &str = "tests/fixtures/diff_new_oas3.json";

const DIFF_SUMMARY: &str =
    "**Summary:** 1 endpoint added, 1 removed, 4 changed; 4 breaking, 8 non-breaking, 1 to review";

/// Runs `vimanam diff` with `args` and returns `(stdout, exit code)`.
fn diff_run(args: &[&str]) -> (String, i32) {
    let output = vimanam().arg("diff").args(args).output().unwrap();
    (
        String::from_utf8(output.stdout).unwrap(),
        output.status.code().unwrap(),
    )
}

fn load_json(path: &str) -> serde_json::Value {
    serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}

/// Writes `spec` to `<dir>/<name>` so an edited copy of a fixture can be diffed.
fn write_spec(dir: &tempfile::TempDir, name: &str, spec: &serde_json::Value) -> String {
    let path = dir.path().join(name);
    std::fs::write(&path, serde_json::to_string_pretty(spec).unwrap()).unwrap();
    path.to_str().unwrap().to_string()
}

#[test]
fn diff_reports_added_removed_changed() {
    let (stdout, code) = diff_run(&[DIFF_OLD, DIFF_NEW]);
    assert_eq!(code, 0, "{stdout}");

    assert!(
        stdout.starts_with("# API Diff: Widgets API 1.0.0 → 1.1.0\n\n"),
        "{stdout}"
    );
    assert!(stdout.contains(&format!("\n{DIFF_SUMMARY}\n")), "{stdout}");

    let breaking = "\
## Breaking changes (4)

| Change | Endpoint | Detail |
|--------|----------|--------|
| Parameter newly required | `GET /widgets/{id}` | `fields` (query) |
| Response removed | `GET /widgets/{id}` | 404 |
| operationId changed | `DELETE /widgets/{id}` | `Widgets_DeleteWidget` → `Widgets_RemoveWidget` |
| Endpoint removed | `GET /legacy` | was deprecated |
";
    assert!(stdout.contains(breaking), "{stdout}");

    let non_breaking = "\
## Non-breaking changes (8)

| Change | Endpoint | Detail |
|--------|----------|--------|
| Response schema changed | `GET /widgets` | 200 `/properties/pricing` added |
| Response schema changed | `GET /widgets` | 200 `/properties/pricing` added to `required` |
| Response schema changed | `POST /widgets` | 201 `/properties/pricing` added |
| Response schema changed | `POST /widgets` | 201 `/properties/pricing` added to `required` |
| Response schema changed | `GET /widgets/{id}` | 200 `/properties/pricing` added |
| Response schema changed | `GET /widgets/{id}` | 200 `/properties/pricing` added to `required` |
| Marked deprecated | `DELETE /widgets/{id}` | - |
| Endpoint added | `GET /widgets/{id}/history` | - |
";
    assert!(stdout.contains(non_breaking), "{stdout}");

    // Without --report there is no Deltas section.
    assert!(!stdout.contains("## Deltas"), "{stdout}");
}

// nrynss's requirement on #45: a change behind a shared `$ref` must surface on
// every endpoint whose operation object did not change at all.
#[test]
fn diff_detects_schema_drift_behind_shared_ref() {
    let old = load_json(DIFF_OLD);
    let new = load_json(DIFF_NEW);
    assert_eq!(
        old.pointer("/paths/~1widgets/get"),
        new.pointer("/paths/~1widgets/get"),
        "fixture precondition: the GET /widgets operation object must be identical"
    );
    assert_ne!(
        old.pointer("/components/schemas/Widget"),
        new.pointer("/components/schemas/Widget"),
        "fixture precondition: the shared Widget schema must differ"
    );

    let (stdout, _) = diff_run(&[DIFF_OLD, DIFF_NEW]);
    assert!(
        stdout.contains(
            "| Response schema changed | `GET /widgets` | 200 `/properties/pricing` added |"
        ),
        "{stdout}"
    );
    assert!(
        stdout.contains(
            "| Response schema changed | `GET /widgets` | 200 `/properties/pricing` added to `required` |"
        ),
        "{stdout}"
    );
}

#[test]
fn diff_classifies_format_change_as_review() {
    let (stdout, _) = diff_run(&[DIFF_OLD, DIFF_NEW]);
    let review = "\
## Needs review (1)

| Change | Endpoint | Detail |
|--------|----------|--------|
| Request schema changed | `POST /widgets` | `/properties/weight/format` changed `float` → `double` |
";
    assert!(stdout.contains(review), "{stdout}");
}

// Reworded descriptions (on a parameter and inside a schema) are not changes.
#[test]
fn diff_ignores_description_only_changes() {
    let old = load_json(DIFF_OLD);
    let new = load_json(DIFF_NEW);
    assert_ne!(
        old.pointer("/paths/~1widgets/post/parameters/0/description"),
        new.pointer("/paths/~1widgets/post/parameters/0/description"),
        "fixture precondition: X-Trace description differs"
    );

    let (stdout, _) = diff_run(&[DIFF_OLD, DIFF_NEW]);
    assert!(!stdout.contains("X-Trace"), "{stdout}");
    assert!(!stdout.contains("/properties/name"), "{stdout}");
    assert!(!stdout.contains("description"), "{stdout}");
}

#[test]
fn diff_fail_on_breaking_exits_3() {
    // Without the flag, breaking changes are reported but the exit is 0.
    let (_, code) = diff_run(&[DIFF_OLD, DIFF_NEW]);
    assert_eq!(code, 0);

    // With the flag the full report is still written before exiting 3.
    let (stdout, code) = diff_run(&[DIFF_OLD, DIFF_NEW, "--fail-on-breaking"]);
    assert_eq!(code, 3, "{stdout}");
    assert!(stdout.contains("## Breaking changes (4)"), "{stdout}");
    assert!(stdout.contains("## Needs review (1)"), "{stdout}");
}

// Review-level and non-breaking changes never trip --fail-on-breaking.
#[test]
fn diff_fail_on_breaking_passes_without_breaking_changes() {
    let dir = tempfile::tempdir().unwrap();
    let mut edited = load_json(DIFF_OLD);
    // A format change (review) and a new optional parameter (non-breaking).
    *edited
        .pointer_mut("/components/schemas/WidgetInput/properties/weight/format")
        .unwrap() = serde_json::json!("double");
    edited
        .pointer_mut("/paths/~1widgets/get/parameters")
        .unwrap()
        .as_array_mut()
        .unwrap()
        .push(serde_json::json!({
            "name": "offset",
            "in": "query",
            "schema": {"type": "integer"}
        }));
    let edited_path = write_spec(&dir, "edited.json", &edited);

    let (stdout, code) = diff_run(&[DIFF_OLD, &edited_path, "--fail-on-breaking"]);
    assert_eq!(code, 0, "{stdout}");
    assert!(!stdout.contains("## Breaking changes"), "{stdout}");
    assert!(
        stdout.contains("| Parameter added | `GET /widgets` | `offset` (query), optional |"),
        "{stdout}"
    );
    assert!(stdout.contains("## Needs review (1)"), "{stdout}");
}

#[test]
fn diff_no_changes_exits_0_and_says_so() {
    let (stdout, code) = diff_run(&[DIFF_OLD, DIFF_OLD]);
    assert_eq!(code, 0);
    assert_eq!(
        stdout,
        "# API Diff: Widgets API 1.0.0 → 1.0.0\n\n**Summary:** No changes.\n"
    );

    // Self-referential schemas (Node -> Node, Pet -> Pet) must resolve and
    // compare without looping.
    let (stdout, code) = diff_run(&[OAS3_SCHEMA_REFS, OAS3_SCHEMA_REFS, "--fail-on-breaking"]);
    assert_eq!(code, 0);
    assert!(stdout.ends_with("**Summary:** No changes.\n"), "{stdout}");
}

#[test]
fn diff_report_shows_hygiene_and_token_deltas() {
    let (stdout, code) = diff_run(&[DIFF_OLD, DIFF_NEW, "--report"]);
    assert_eq!(code, 0, "{stdout}");

    let deltas_header = "\
## Deltas

| Check | Old | New | Δ |
|-------|----:|----:|--:|
";
    assert!(stdout.contains(deltas_header), "{stdout}");
    // The added history endpoint has no summary; the deprecated count moves
    // from GET /legacy to DELETE /widgets/{id}.
    assert!(
        stdout.contains("| Missing description | 0 | 1 | +1 |"),
        "{stdout}"
    );
    assert!(stdout.contains("| Deprecated | 1 | 1 | 0 |"), "{stdout}");
    assert!(
        stdout.contains("| Parameters without description | 0 | 0 | 0 |"),
        "{stdout}"
    );

    let token_line = stdout
        .lines()
        .find(|line| line.starts_with("Token estimate (--detail full --include-schemas): "))
        .unwrap_or_else(|| panic!("no token estimate line in:\n{stdout}"));
    let numbers: Vec<usize> = token_line
        .split(|c: char| !c.is_ascii_digit())
        .filter(|s| !s.is_empty())
        .map(|s| s.parse().unwrap())
        .collect();
    let (old_tokens, new_tokens) = (numbers[0], numbers[1]);
    assert!(new_tokens > old_tokens, "{token_line}");
    assert!(
        token_line.ends_with(&format!("(+{})", new_tokens - old_tokens)),
        "{token_line}"
    );
    assert!(stdout.ends_with(&format!("{token_line}\n")), "{stdout}");

    // With no changes the Deltas section still follows the summary.
    let (stdout, _) = diff_run(&[DIFF_OLD, DIFF_OLD, "--report"]);
    assert!(
        stdout.contains("**Summary:** No changes.\n\n## Deltas\n"),
        "{stdout}"
    );
}

#[test]
fn diff_output_is_deterministic() {
    let first = diff_run(&[DIFF_OLD, DIFF_NEW, "--report"]);
    for _ in 0..4 {
        assert_eq!(first, diff_run(&[DIFF_OLD, DIFF_NEW, "--report"]));
    }
}

#[test]
fn diff_writes_to_output_file() {
    let dir = tempfile::tempdir().unwrap();
    let out_path = dir.path().join("diff.md");

    vimanam()
        .args(["diff", DIFF_OLD, DIFF_NEW, "-o", out_path.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    let content = std::fs::read_to_string(&out_path).unwrap();
    let (stdout, _) = diff_run(&[DIFF_OLD, DIFF_NEW]);
    assert_eq!(content, stdout);
    assert!(content.starts_with("# API Diff: Widgets API"), "{content}");

    // --fail-on-breaking still exits 3 when writing to a file.
    vimanam()
        .args([
            "diff",
            DIFF_OLD,
            DIFF_NEW,
            "--fail-on-breaking",
            "-o",
            out_path.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .code(3);
}

// The conversion arguments are meaningless alongside the subcommand.
#[test]
fn diff_rejects_conversion_flags() {
    vimanam()
        .args([OAS3, "diff", DIFF_OLD, DIFF_NEW])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("cannot be used with"));

    vimanam()
        .args(["--detail", "full", "diff", DIFF_OLD, DIFF_NEW])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("cannot be used with"));
}

#[test]
fn diff_requires_two_specs() {
    vimanam()
        .args(["diff", DIFF_OLD])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("<NEW>"));
}

// A spec that fails to parse is a runtime error (1), distinct from breaking (3).
#[test]
fn diff_unparseable_spec_exits_1() {
    vimanam()
        .args([
            "diff",
            DIFF_OLD,
            "tests/fixtures/does_not_exist.json",
            "--fail-on-breaking",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("Failed to parse OpenAPI file"));
}

// Swagger 2.0: `#/definitions/` refs resolve, OAS2 `schema` responses are
// compared, and a non-body parameter's inline `type` is compared.
#[test]
fn diff_works_for_oas2() {
    let (stdout, code) = diff_run(&[OAS2, OAS2]);
    assert_eq!(code, 0);
    assert_eq!(
        stdout,
        "# API Diff: Petstore Legacy API 2.0.0 → 2.0.0\n\n**Summary:** No changes.\n"
    );

    let dir = tempfile::tempdir().unwrap();
    let mut old = load_json(OAS2);
    old.pointer_mut("/paths/~1pets/post/parameters")
        .unwrap()
        .as_array_mut()
        .unwrap()
        .push(serde_json::json!({"name": "limit", "in": "query", "type": "integer"}));
    let mut new = old.clone();
    *new.pointer_mut("/paths/~1pets/post/parameters/1/type")
        .unwrap() = serde_json::json!("string");
    *new.pointer_mut("/definitions/Pet").unwrap() = serde_json::json!({
        "type": "object",
        "properties": {"name": {"type": "string"}}
    });
    let old_path = write_spec(&dir, "old.json", &old);
    let new_path = write_spec(&dir, "new.json", &new);

    let (stdout, code) = diff_run(&[&old_path, &new_path, "--fail-on-breaking"]);
    assert_eq!(code, 3, "{stdout}");
    assert!(
        stdout.contains(
            "| Parameter schema changed | `POST /pets` | `limit` (query) `/type` changed `integer` → `string` |"
        ),
        "{stdout}"
    );
    // The body parameter and the 200 response both reference #/definitions/Pet.
    assert!(
        stdout.contains("| Request schema changed | `POST /pets` | `/properties/name` added |"),
        "{stdout}"
    );
    assert!(
        stdout
            .contains("| Response schema changed | `POST /pets` | 200 `/properties/name` added |"),
        "{stdout}"
    );
}