svccat 1.5.0

Detect drift between your declared service catalog and what actually lives in the repo.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
use std::fs;
use std::path::Path;
use tempfile::TempDir;

// ── Test helpers ──────────────────────────────────────────────────────────────

fn touch(root: &Path, rel_path: &str) {
    let full = root.join(rel_path);
    if let Some(parent) = full.parent() {
        fs::create_dir_all(parent).unwrap();
    }
    fs::write(full, "").unwrap();
}

fn write_manifest(root: &Path, content: &str) {
    fs::write(root.join("services.yaml"), content).unwrap();
}

fn load(
    root: &Path,
) -> (
    svccat::manifest::Manifest,
    Vec<svccat::discovery::DiscoveredService>,
) {
    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    let d = svccat::discovery::discover_services(root, &m);
    (m, d)
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[test]
fn no_drift_when_all_services_found() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api-gateway/Cargo.toml");
    touch(root, "services/auth-service/Dockerfile");

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
services:
  - name: api-gateway
    language: Rust
    role: API gateway
    platform: Cloud Run
  - name: auth-service
    language: Python
    role: Authentication
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    assert_eq!(
        report.drifts.len(),
        0,
        "unexpected drift: {:?}",
        report.drifts
    );
}

#[test]
fn detects_declared_service_missing_from_repo() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api-gateway/Cargo.toml");
    // auth-service directory intentionally absent

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
services:
  - name: api-gateway
    language: Rust
    role: API gateway
    platform: Cloud Run
  - name: auth-service
    language: Python
    role: Authentication
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);

    let missing: Vec<_> = report
        .drifts
        .iter()
        .filter(|item| item.kind == svccat::drift::DriftKind::DeclaredMissingFromRepo)
        .collect();
    assert_eq!(missing.len(), 1, "expected exactly one missing service");
    assert_eq!(missing[0].service, "auth-service");
    assert_eq!(missing[0].severity, svccat::drift::Severity::Error);
}

#[test]
fn detects_undeclared_service_in_repo() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api-gateway/Cargo.toml");
    touch(root, "services/auth-service/Dockerfile");
    touch(root, "services/new-feature/go.mod"); // not in manifest

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
services:
  - name: api-gateway
    language: Rust
    role: API gateway
    platform: Cloud Run
  - name: auth-service
    language: Python
    role: Authentication
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);

    let undeclared: Vec<_> = report
        .drifts
        .iter()
        .filter(|item| item.kind == svccat::drift::DriftKind::UndeclaredInRepo)
        .collect();
    assert_eq!(
        undeclared.len(),
        1,
        "expected exactly one undeclared service"
    );
    assert_eq!(undeclared[0].service, "new-feature");
    assert_eq!(undeclared[0].severity, svccat::drift::Severity::Warning);
}

#[test]
fn detects_missing_role_field() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api-gateway/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
services:
  - name: api-gateway
    language: Rust
    platform: Cloud Run
    # role intentionally omitted
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);

    let field_drifts: Vec<_> = report
        .drifts
        .iter()
        .filter(|item| item.kind == svccat::drift::DriftKind::MissingField)
        .collect();
    assert_eq!(field_drifts.len(), 1, "expected one missing-field drift");
    assert_eq!(field_drifts[0].detail.as_deref(), Some("role"));
    assert_eq!(field_drifts[0].severity, svccat::drift::Severity::Error);
}

#[test]
fn detects_missing_referenced_docs_file() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api-gateway/Cargo.toml");
    // docs/api-gateway.md intentionally absent

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
services:
  - name: api-gateway
    language: Rust
    role: API gateway
    platform: Cloud Run
    docs: docs/api-gateway.md
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);

    let ref_drifts: Vec<_> = report
        .drifts
        .iter()
        .filter(|item| item.kind == svccat::drift::DriftKind::MissingReferencedFile)
        .collect();
    assert_eq!(ref_drifts.len(), 1);
    assert!(ref_drifts[0].message.contains("docs"));
}

#[test]
fn explicit_path_overrides_name_matching() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    // Service directory is nested, not top-level services/
    touch(root, "infra/gateway/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
services:
  - name: api-gateway
    language: Rust
    role: API gateway
    platform: Cloud Run
    path: infra/gateway
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);

    // Should be no "missing" drift (explicit path matched), but api-gateway
    // is not in services/* discovery so no undeclared entries either.
    let missing: Vec<_> = report
        .drifts
        .iter()
        .filter(|i| i.kind == svccat::drift::DriftKind::DeclaredMissingFromRepo)
        .collect();
    assert_eq!(missing.len(), 0, "explicit path should resolve correctly");
}

#[test]
fn json_output_is_valid() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api-gateway/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
services:
  - name: api-gateway
    language: Rust
    role: API gateway
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);

    // Serialise to JSON — must not panic and must round-trip cleanly.
    let json_str = serde_json::to_string_pretty(&report).unwrap();
    let _: serde_json::Value = serde_json::from_str(&json_str).unwrap();
}

// ── depends_on graph tests ────────────────────────────────────────────────────

#[test]
fn graph_renders_depends_on_edges() {
    use std::io::Write;

    let dir = TempDir::new().unwrap();
    let root = dir.path();

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
services:
  - name: payment-service
    language: Rust
    role: payments
    platform: Cloud Run
    depends_on:
      - auth-service
      - postgres
  - name: auth-service
    language: Go
    role: authentication
    platform: Cloud Run
  - name: postgres
    language: SQL
    role: database
    platform: Cloud SQL
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();

    // Capture stdout
    let mut output = Vec::new();
    {
        // Render to a string by using the public render function
        // We test the manifest parses depends_on correctly
        assert_eq!(m.services[0].depends_on, vec!["auth-service", "postgres"]);
        assert!(m.services[1].depends_on.is_empty());
    }

    // Verify depends_on survives a YAML round-trip
    let yaml = serde_yaml::to_string(&m).unwrap();
    let m2: svccat::manifest::Manifest = serde_yaml::from_str(&yaml).unwrap();
    assert_eq!(m2.services[0].depends_on, vec!["auth-service", "postgres"]);
    let _ = output.flush();
}

// ── ping tests (unit-level, no real HTTP) ────────────────────────────────────

#[test]
fn ping_result_is_ok_for_reachable() {
    use svccat::ping::{PingResult, PingStatus};

    let r = PingResult {
        service: "api".to_string(),
        url: "https://example.com".to_string(),
        ping: PingStatus::Reachable { code: 200 },
    };
    assert!(r.is_ok());

    let r2 = PingResult {
        service: "api".to_string(),
        url: "https://example.com".to_string(),
        ping: PingStatus::Reachable { code: 404 },
    };
    assert!(r2.is_ok()); // reachable even if 404

    let r3 = PingResult {
        service: "api".to_string(),
        url: "https://example.com".to_string(),
        ping: PingStatus::Unreachable {
            reason: "connection refused".to_string(),
        },
    };
    assert!(!r3.is_ok());
}

#[test]
fn ping_skips_services_without_url() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    write_manifest(
        root,
        r#"
services:
  - name: no-url-service
    language: Rust
    role: api
    platform: Cloud Run
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    // ping_services returns empty because no url is set
    // We test the filter logic: services without url are skipped
    let services_with_url: Vec<_> = m.services.iter().filter(|s| s.url.is_some()).collect();
    assert_eq!(services_with_url.len(), 0);
}

#[test]
fn init_creates_services_yaml_from_discovered_services() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api-gateway/Cargo.toml");
    touch(root, "services/worker/go.mod");

    let output = root.join("services.yaml");
    svccat::init::run(root, output.clone(), false).unwrap();

    assert!(output.exists(), "services.yaml should be created");
    let contents = fs::read_to_string(&output).unwrap();
    assert!(
        contents.contains("api-gateway"),
        "should include api-gateway"
    );
    assert!(contents.contains("worker"), "should include worker");
    assert!(
        contents.contains("Rust"),
        "should infer Rust from Cargo.toml"
    );
    assert!(contents.contains("Go"), "should infer Go from go.mod");
}

#[test]
fn init_infers_platform_from_deploy_descriptor() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/web/Cargo.toml");
    touch(root, "services/web/fly.toml");

    let output = root.join("services.yaml");
    svccat::init::run(root, output.clone(), false).unwrap();

    let contents = fs::read_to_string(&output).unwrap();
    assert!(
        contents.contains("platform: fly.io"),
        "should infer fly.io platform from fly.toml, got:\n{contents}"
    );
}

#[test]
fn init_leaves_platform_placeholder_without_descriptor() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    // Only a Dockerfile: not a platform signal, so platform stays a placeholder.
    touch(root, "services/api/Dockerfile");

    let output = root.join("services.yaml");
    svccat::init::run(root, output.clone(), false).unwrap();

    let contents = fs::read_to_string(&output).unwrap();
    assert!(
        contents.contains("platform: ~"),
        "platform should remain a placeholder, got:\n{contents}"
    );
}

#[test]
fn fix_infers_language_and_platform_for_added_services() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    write_manifest(
        root,
        "version: \"1\"\ndiscovery:\n  paths:\n    - services/*\nservices: []\n",
    );

    touch(root, "services/worker/go.mod");
    fs::create_dir_all(root.join("services/worker/k8s")).unwrap();

    let manifest_path = root.join("services.yaml");
    svccat::fix::run(&manifest_path, root, &[], 1, false, false).unwrap();

    let m = svccat::manifest::Manifest::load(&manifest_path).unwrap();
    let worker = m
        .services
        .iter()
        .find(|s| s.name == "worker")
        .expect("worker should be added by fix");
    assert_eq!(worker.language.as_deref(), Some("Go"));
    assert_eq!(worker.platform.as_deref(), Some("kubernetes"));
}

#[test]
fn init_refuses_to_overwrite_without_force() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();
    let output = root.join("services.yaml");
    fs::write(&output, "existing content").unwrap();

    let result = svccat::init::run(root, output, false);
    assert!(
        result.is_err(),
        "should error when file exists and --force not set"
    );
}

#[test]
fn init_overwrites_with_force() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();
    let output = root.join("services.yaml");
    fs::write(&output, "old content").unwrap();

    touch(root, "services/my-svc/Dockerfile");
    svccat::init::run(root, output.clone(), true).unwrap();

    let contents = fs::read_to_string(&output).unwrap();
    assert!(
        contents.contains("my-svc"),
        "should contain discovered service"
    );
    assert!(
        !contents.contains("old content"),
        "should overwrite old content"
    );
}

#[test]
fn init_empty_repo_writes_skeleton() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();
    let output = root.join("services.yaml");

    svccat::init::run(root, output.clone(), false).unwrap();

    let contents = fs::read_to_string(&output).unwrap();
    assert!(
        contents.contains("version"),
        "skeleton should contain version key"
    );
    assert!(
        contents.contains("services:"),
        "skeleton should contain services key"
    );
}

// ── ignore pattern tests ──────────────────────────────────────────────────────

#[test]
fn ignore_patterns_exclude_matching_directories() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");
    touch(root, "services/examples/Cargo.toml"); // should be ignored
    touch(root, "services/vendor/go.mod"); // should be ignored

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
  ignore:
    - "services/examples"
    - "services/vendor"
services:
  - name: api
    language: Rust
    role: api
    platform: Cloud Run
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    let discovered = svccat::discovery::discover_services(root, &m);

    let names: Vec<&str> = discovered.iter().map(|d| d.name.as_str()).collect();
    assert!(names.contains(&"api"), "api should be discovered");
    assert!(!names.contains(&"examples"), "examples should be ignored");
    assert!(!names.contains(&"vendor"), "vendor should be ignored");
}

#[test]
fn extra_ignore_from_cli_merges_with_manifest() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");
    touch(root, "services/scratch/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
services:
  - name: api
    language: Rust
    role: api
    platform: Cloud Run
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    // Pass "services/scratch" as an extra CLI ignore
    let discovered = svccat::discovery::discover_services_with_ignore(
        root,
        &m,
        &["services/scratch".to_string()],
    );

    let names: Vec<&str> = discovered.iter().map(|d| d.name.as_str()).collect();
    assert!(names.contains(&"api"));
    assert!(
        !names.contains(&"scratch"),
        "scratch should be excluded by CLI ignore"
    );
}

// ── svccat.toml config tests ──────────────────────────────────────────────────

#[test]
fn config_loads_from_svccat_toml() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    fs::write(
        root.join("svccat.toml"),
        r#"
fail_on_drift = true
ignore = ["examples/*", "vendor/*"]
"#,
    )
    .unwrap();

    let cfg = svccat::config::SvccatConfig::load(root).unwrap();
    assert!(cfg.fail_on_drift);
    assert_eq!(cfg.ignore, vec!["examples/*", "vendor/*"]);
}

#[test]
fn config_returns_defaults_when_no_file() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    let cfg = svccat::config::SvccatConfig::load(root).unwrap();
    assert!(!cfg.fail_on_drift);
    assert!(cfg.ignore.is_empty());
}

// ── completions test ──────────────────────────────────────────────────────────

#[test]
fn completions_produces_output_for_bash() {
    use clap::CommandFactory;
    use clap_complete::{generate, Shell};
    use svccat::cli::Cli;

    let mut cmd = Cli::command();
    let mut buf = Vec::new();
    generate(Shell::Bash, &mut cmd, "svccat", &mut buf);
    assert!(!buf.is_empty(), "bash completions should produce output");
    let script = String::from_utf8(buf).unwrap();
    assert!(
        script.contains("svccat"),
        "completions should mention the binary name"
    );
}

// ── policy tests ──────────────────────────────────────────────────────────────

#[test]
fn policy_require_fields_flags_missing_url() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
policy:
  require_fields: [url, language]
services:
  - name: api
    language: Rust
    role: api
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);

    let policy_violations: Vec<_> = report
        .drifts
        .iter()
        .filter(|i| i.kind == svccat::drift::DriftKind::PolicyViolation)
        .collect();

    assert_eq!(
        policy_violations.len(),
        1,
        "url should be flagged by policy"
    );
    assert!(policy_violations[0].message.contains("url"));
}

#[test]
fn policy_no_violations_when_fields_present() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths:
    - "services/*"
policy:
  require_fields: [url, language]
services:
  - name: api
    language: Rust
    role: api
    platform: Cloud Run
    url: https://api.example.com
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);

    let violations: Vec<_> = report
        .drifts
        .iter()
        .filter(|i| i.kind == svccat::drift::DriftKind::PolicyViolation)
        .collect();
    assert!(violations.is_empty(), "no policy violations expected");
}

// ── diff tests ────────────────────────────────────────────────────────────────

#[test]
fn diff_detects_added_and_removed_services() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    let before_json = r#"{
      "version": "1",
      "manifest": "services.yaml",
      "summary": {"declared": 2, "discovered": 2, "drift_count": 0, "errors": 0, "warnings": 0},
      "services": [
        {"name": "api", "language": "Rust", "platform": "Cloud Run", "role": "api", "depends_on": []},
        {"name": "legacy", "language": "Go", "platform": "Fly.io", "role": "worker", "depends_on": []}
      ],
      "drift": []
    }"#;

    let after_json = r#"{
      "version": "1",
      "manifest": "services.yaml",
      "summary": {"declared": 2, "discovered": 2, "drift_count": 0, "errors": 0, "warnings": 0},
      "services": [
        {"name": "api", "language": "Rust", "platform": "Cloud Run", "role": "api", "depends_on": []},
        {"name": "new-worker", "language": "Python", "platform": "Cloud Run", "role": "worker", "depends_on": []}
      ],
      "drift": []
    }"#;

    let before_path = root.join("before.json");
    let after_path = root.join("after.json");
    fs::write(&before_path, before_json).unwrap();
    fs::write(&after_path, after_json).unwrap();

    let report = svccat::diff::diff_snapshots(&before_path, &after_path).unwrap();

    assert!(report.added.contains(&"new-worker".to_string()));
    assert!(report.removed.contains(&"legacy".to_string()));
    assert!(!report.added.contains(&"api".to_string()));
}

#[test]
fn diff_detects_field_changes() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    let before_json = r#"{
      "services": [
        {"name": "api", "language": "Python", "platform": "Cloud Run", "role": "api", "depends_on": []}
      ],
      "drift": []
    }"#;

    let after_json = r#"{
      "services": [
        {"name": "api", "language": "Rust", "platform": "Cloud Run", "role": "api", "depends_on": []}
      ],
      "drift": []
    }"#;

    let before_path = root.join("before.json");
    let after_path = root.join("after.json");
    fs::write(&before_path, before_json).unwrap();
    fs::write(&after_path, after_json).unwrap();

    let report = svccat::diff::diff_snapshots(&before_path, &after_path).unwrap();

    assert_eq!(report.changed.len(), 1);
    assert_eq!(report.changed[0].name, "api");
    let lang_change = report.changed[0]
        .changes
        .iter()
        .find(|c| c.field == "language")
        .expect("language change expected");
    assert_eq!(lang_change.before, "Python");
    assert_eq!(lang_change.after, "Rust");
}

#[test]
fn diff_no_changes_when_snapshots_identical() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    let snapshot = r#"{
      "services": [
        {"name": "api", "language": "Rust", "platform": "Cloud Run", "role": "api", "depends_on": []}
      ],
      "drift": []
    }"#;

    let before_path = root.join("before.json");
    let after_path = root.join("after.json");
    fs::write(&before_path, snapshot).unwrap();
    fs::write(&after_path, snapshot).unwrap();

    let report = svccat::diff::diff_snapshots(&before_path, &after_path).unwrap();
    assert!(
        report.is_empty(),
        "identical snapshots should produce no diff"
    );
}

// ── v0.6.0: Ownership metadata + team filter ──────────────────────────────────

#[test]
fn team_and_oncall_fields_parse() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");
    touch(root, "services/worker/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    team: platform
    oncall: platform-oncall@example.com
  - name: worker
    language: Rust
    role: Worker
    platform: Cloud Run
    team: data
    oncall: data-team@example.com
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    let api = m.services.iter().find(|s| s.name == "api").unwrap();
    let worker = m.services.iter().find(|s| s.name == "worker").unwrap();

    assert_eq!(api.team.as_deref(), Some("platform"));
    assert_eq!(api.oncall.as_deref(), Some("platform-oncall@example.com"));
    assert_eq!(worker.team.as_deref(), Some("data"));
    assert_eq!(worker.oncall.as_deref(), Some("data-team@example.com"));
}

#[test]
fn team_filter_limits_analysis_to_matching_services() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");
    touch(root, "services/worker/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    team: platform
  - name: worker
    language: Rust
    role: Worker
    platform: Cloud Run
    team: data
"#,
    );

    // Simulate --team platform: retain only services owned by "platform".
    let full_m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    let mut m = full_m.clone();
    m.services.retain(|s| {
        s.team
            .as_deref()
            .map(|t| t.eq_ignore_ascii_case("platform"))
            .unwrap_or(false)
    });

    // Discover against the full manifest, then filter out other-team services
    // to avoid false UndeclaredInRepo noise (mirrors main.rs behaviour).
    let in_scope: std::collections::HashSet<&str> =
        m.services.iter().map(|s| s.name.as_str()).collect();
    let other_declared: std::collections::HashSet<&str> = full_m
        .services
        .iter()
        .filter(|s| !in_scope.contains(s.name.as_str()))
        .map(|s| s.name.as_str())
        .collect();
    let discovered_all = svccat::discovery::discover_services(root, &full_m);
    let d: Vec<_> = discovered_all
        .into_iter()
        .filter(|d| !other_declared.contains(d.name.as_str()))
        .collect();

    let report = svccat::drift::analyze(&m, &d, root);

    // Only "api" (team: platform) should be in scope; "worker" should be invisible.
    assert_eq!(m.services.len(), 1);
    assert_eq!(m.services[0].name, "api");
    assert_eq!(
        report.drifts.len(),
        0,
        "no drift expected for team-filtered check: {:?}",
        report.drifts
    );
}

#[test]
fn policy_requires_team_field() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
policy:
  require_fields: ["team", "oncall"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    # team and oncall intentionally omitted to trigger policy violations
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);

    let policy_violations: Vec<_> = report
        .drifts
        .iter()
        .filter(|d| d.kind == svccat::drift::DriftKind::PolicyViolation)
        .collect();

    assert_eq!(
        policy_violations.len(),
        2,
        "expected 2 policy violations (team + oncall), got: {:?}",
        policy_violations
    );
    let fields: Vec<_> = policy_violations
        .iter()
        .filter_map(|v| v.detail.as_deref())
        .collect();
    assert!(fields.contains(&"team"), "expected team violation");
    assert!(fields.contains(&"oncall"), "expected oncall violation");
}

#[test]
fn team_filter_case_insensitive() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    team: Platform
"#,
    );

    let mut m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    // Match "platform" (lowercase) against team value "Platform" (mixed case).
    m.services.retain(|s| {
        s.team
            .as_deref()
            .map(|t| t.eq_ignore_ascii_case("platform"))
            .unwrap_or(false)
    });

    assert_eq!(m.services.len(), 1, "case-insensitive match should succeed");
}

// ── v0.7.0: depends_on validation + cycle detection ───────────────────────────

#[test]
fn no_drift_for_valid_depends_on() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");
    touch(root, "services/auth/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    depends_on: [auth]
  - name: auth
    language: Rust
    role: Auth
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let dependency_drifts: Vec<_> = report
        .drifts
        .iter()
        .filter(|d| {
            d.kind == svccat::drift::DriftKind::DanglingDependency
                || d.kind == svccat::drift::DriftKind::CircularDependency
        })
        .collect();
    assert!(
        dependency_drifts.is_empty(),
        "valid depends_on should produce no drift: {:?}",
        dependency_drifts
    );
}

#[test]
fn detects_dangling_depends_on() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    depends_on: [ghost-service]
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let dangling: Vec<_> = report
        .drifts
        .iter()
        .filter(|d| d.kind == svccat::drift::DriftKind::DanglingDependency)
        .collect();
    assert_eq!(
        dangling.len(),
        1,
        "expected 1 dangling dependency: {:?}",
        dangling
    );
    assert_eq!(dangling[0].detail.as_deref(), Some("ghost-service"));
    assert_eq!(dangling[0].severity, svccat::drift::Severity::Error);
}

#[test]
fn detects_two_node_cycle() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");
    touch(root, "services/auth/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    depends_on: [auth]
  - name: auth
    language: Rust
    role: Auth
    platform: Cloud Run
    depends_on: [api]
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let cycles: Vec<_> = report
        .drifts
        .iter()
        .filter(|d| d.kind == svccat::drift::DriftKind::CircularDependency)
        .collect();
    assert!(
        !cycles.is_empty(),
        "expected cycle to be detected: {:?}",
        report.drifts
    );
    assert_eq!(cycles[0].severity, svccat::drift::Severity::Error);
}

#[test]
fn detects_three_node_cycle() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/a/Cargo.toml");
    touch(root, "services/b/Cargo.toml");
    touch(root, "services/c/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: a
    role: A
    depends_on: [b]
  - name: b
    role: B
    depends_on: [c]
  - name: c
    role: C
    depends_on: [a]
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let cycles: Vec<_> = report
        .drifts
        .iter()
        .filter(|d| d.kind == svccat::drift::DriftKind::CircularDependency)
        .collect();
    assert!(
        !cycles.is_empty(),
        "expected 3-node cycle to be detected: {:?}",
        report.drifts
    );
}

// ── v0.7.0: SARIF output ──────────────────────────────────────────────────────

#[test]
fn sarif_output_is_valid_json_with_rules() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    platform: Cloud Run
    # role intentionally missing to trigger MissingField
"#,
    );

    let (m, d) = load(root);
    let mut report = svccat::drift::analyze(&m, &d, root);
    report.manifest = "services.yaml".to_string();

    // Verify the report has a MissingField drift for role.
    let role_drift = report.drifts.iter().any(|d| {
        d.kind == svccat::drift::DriftKind::MissingField && d.detail.as_deref() == Some("role")
    });
    assert!(
        role_drift,
        "expected MissingField for role: {:?}",
        report.drifts
    );

    // Verify the SARIF schema constant embeds the right version string.
    let sarif_doc = serde_json::json!({
        "version": "2.1.0",
        "runs": [{
            "tool": { "driver": { "name": "svccat" } },
            "results": report.drifts.iter().map(|item| {
                let rule_id = match item.kind {
                    svccat::drift::DriftKind::MissingField => "missing_field",
                    svccat::drift::DriftKind::PolicyViolation => "policy_violation",
                    svccat::drift::DriftKind::DeclaredMissingFromRepo => "declared_missing_from_repo",
                    svccat::drift::DriftKind::UndeclaredInRepo => "undeclared_in_repo",
                    svccat::drift::DriftKind::MissingReferencedFile => "missing_referenced_file",
                    svccat::drift::DriftKind::DanglingDependency => "dangling_dependency",
                    svccat::drift::DriftKind::CircularDependency => "circular_dependency",
                    // DriftKind is #[non_exhaustive]; map any future variant generically.
                    _ => "unknown",
                };
                serde_json::json!({ "ruleId": rule_id, "message": { "text": item.message } })
            }).collect::<Vec<_>>()
        }]
    });

    assert_eq!(sarif_doc["version"], "2.1.0");
    let results = sarif_doc["runs"][0]["results"].as_array().unwrap();
    assert!(!results.is_empty(), "SARIF results should not be empty");
    assert_eq!(results[0]["ruleId"], "missing_field");
}

// ── v0.7.0: graph --team filter ───────────────────────────────────────────────

#[test]
fn graph_team_filter_limits_to_in_scope_services() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");
    touch(root, "services/worker/Cargo.toml");
    touch(root, "services/auth/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    team: platform
    depends_on: [auth]
  - name: auth
    language: Rust
    role: Auth
    platform: Cloud Run
    team: platform
  - name: worker
    language: Rust
    role: Worker
    platform: Cloud Run
    team: data
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();

    // Collect in-scope names for team=platform
    let in_scope: std::collections::HashSet<&str> = m
        .services
        .iter()
        .filter(|s| {
            s.team
                .as_deref()
                .map(|t| t.eq_ignore_ascii_case("platform"))
                .unwrap_or(false)
        })
        .map(|s| s.name.as_str())
        .collect();

    assert!(in_scope.contains("api"), "api should be in platform scope");
    assert!(
        in_scope.contains("auth"),
        "auth should be in platform scope"
    );
    assert!(
        !in_scope.contains("worker"),
        "worker should not be in platform scope"
    );
    assert_eq!(in_scope.len(), 2);
}

// ── v0.8.0: svccat lint ───────────────────────────────────────────────────────

#[test]
fn lint_clean_manifest_has_no_issues() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    write_manifest(
        root,
        r#"
version: "1"
services:
  - name: api
    role: API
    language: Rust
    platform: Cloud Run
    team: platform
    docs: docs/api.md
    depends_on: [auth]
  - name: auth
    role: Auth
    language: Rust
    platform: Cloud Run
    team: platform
    docs: docs/auth.md
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    let result = svccat::lint::run(&m);
    assert!(
        result.issues.is_empty(),
        "clean manifest should have no lint issues: {:?}",
        result.issues
    );
}

#[test]
fn lint_detects_duplicate_service_names() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    write_manifest(
        root,
        r#"
services:
  - name: api
    role: API
  - name: api
    role: Duplicate
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    let result = svccat::lint::run(&m);
    let dups: Vec<_> = result
        .issues
        .iter()
        .filter(|i| i.message.contains("duplicate service name"))
        .collect();
    assert_eq!(
        dups.len(),
        1,
        "expected 1 duplicate-name issue: {:?}",
        result.issues
    );
    assert_eq!(result.error_count(), 1);
}

#[test]
fn lint_detects_self_referential_depends_on() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    write_manifest(
        root,
        r#"
services:
  - name: api
    role: API
    depends_on: [api]
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    let result = svccat::lint::run(&m);
    let self_refs: Vec<_> = result
        .issues
        .iter()
        .filter(|i| i.message.contains("lists itself"))
        .collect();
    assert_eq!(
        self_refs.len(),
        1,
        "expected 1 self-reference issue: {:?}",
        result.issues
    );
    assert_eq!(self_refs[0].severity, svccat::lint::LintSeverity::Error);
}

#[test]
fn lint_detects_duplicate_depends_on_entries() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    write_manifest(
        root,
        r#"
services:
  - name: api
    role: API
    depends_on: [auth, auth]
  - name: auth
    role: Auth
"#,
    );

    let m = svccat::manifest::Manifest::load(&root.join("services.yaml")).unwrap();
    let result = svccat::lint::run(&m);
    let dup_deps: Vec<_> = result
        .issues
        .iter()
        .filter(|i| i.message.contains("more than once"))
        .collect();
    assert_eq!(
        dup_deps.len(),
        1,
        "expected 1 duplicate-depends_on warning: {:?}",
        result.issues
    );
    assert_eq!(dup_deps[0].severity, svccat::lint::LintSeverity::Warning);
}

// ── v0.8.0: svccat report ─────────────────────────────────────────────────────

#[test]
fn report_markdown_contains_service_names_and_summary() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");
    touch(root, "services/worker/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    team: platform
    oncall: oncall@example.com
  - name: worker
    language: Python
    role: Worker
    platform: Fly.io
    team: data
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let md = svccat::report::render_markdown(&m, &report);

    assert!(md.contains("# Service Catalog Report"));
    assert!(md.contains("| Services | 2 |"));
    assert!(md.contains("api"));
    assert!(md.contains("worker"));
    assert!(md.contains("platform"));
    assert!(md.contains("data"));
    assert!(md.contains(""), "expected clean status cells in markdown");
}

#[test]
fn report_html_contains_html_structure() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
    team: platform
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let html = svccat::report::render_html(&m, &report);

    assert!(html.contains("<!DOCTYPE html>"));
    assert!(html.contains("<table>"));
    assert!(html.contains("<th>Service</th>"));
    assert!(html.contains("api"));
    assert!(html.contains("Service Catalog Report"));
}

// ── v0.8.0: --since git-ref ───────────────────────────────────────────────────

#[test]
fn since_load_at_ref_returns_committed_manifest() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    let initial_manifest = r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
"#;
    write_manifest(root, initial_manifest);

    // Initialise a git repo and commit the manifest.
    for args in &[
        vec!["init"],
        vec!["config", "user.email", "test@example.com"],
        vec!["config", "user.name", "Test"],
        vec!["add", "services.yaml"],
        vec!["commit", "-m", "init"],
    ] {
        std::process::Command::new("git")
            .args(
                std::iter::once("-C")
                    .chain(std::iter::once(root.to_str().unwrap()))
                    .chain(args.iter().copied()),
            )
            .output()
            .unwrap();
    }

    let manifest_path = root.join("services.yaml");
    let m = svccat::since::load_at_ref(root, &manifest_path, "HEAD").unwrap();

    assert_eq!(m.services.len(), 1);
    assert_eq!(m.services[0].name, "api");
}

// ── v0.9.0: --format markdown ─────────────────────────────────────────────────

#[test]
fn check_markdown_no_drift() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let md = svccat::output::markdown::render_check_markdown(&report, &[]);

    assert!(md.contains("## 🔍 svccat drift check"));
    assert!(md.contains("✅ **No drift detected**"));
    assert!(!md.contains("❌ **DRIFT DETECTED**"));
}

#[test]
fn check_markdown_with_drift_contains_table() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    // declared but not present on disk → MISSING drift
    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: ghost-service
    language: Rust
    role: API
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let md = svccat::output::markdown::render_check_markdown(&report, &[]);

    assert!(md.contains("❌ **DRIFT DETECTED**"));
    assert!(md.contains("| Severity | Kind | Service | Message |"));
    assert!(md.contains("MISSING"));
    assert!(md.contains("ghost-service"));
}

// ── v0.9.0: --fail-on-new-drift ───────────────────────────────────────────────

#[test]
fn since_diff_markdown_no_change() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let old_report = svccat::drift::analyze(&m, &d, root);
    let new_report = svccat::drift::analyze(&m, &d, root);

    let md =
        svccat::output::markdown::render_since_diff_markdown(&old_report, &new_report, "HEAD~1");
    assert!(md.contains("✅ **No change in drift since"));
}

#[test]
fn since_diff_markdown_new_drift() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    let clean_manifest = r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
"#;
    let drifty_manifest = r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
  - name: ghost-service
    language: Go
    role: Worker
    platform: Cloud Run
"#;

    write_manifest(root, clean_manifest);
    let (m_clean, d) = load(root);
    let old_report = svccat::drift::analyze(&m_clean, &d, root);

    write_manifest(root, drifty_manifest);
    let (m_drifty, _) = load(root);
    let new_report = svccat::drift::analyze(&m_drifty, &d, root);

    let md =
        svccat::output::markdown::render_since_diff_markdown(&old_report, &new_report, "HEAD~1");
    assert!(md.contains("### ❌ New drift since"));
    assert!(md.contains("ghost-service"));
}

// ── v0.9.0: svccat report --history ──────────────────────────────────────────

#[test]
fn report_history_markdown_with_git_repo() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    let manifest_content = r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
"#;
    write_manifest(root, manifest_content);

    // Initialise a git repo with two commits.
    for args in &[
        vec!["init"],
        vec!["config", "user.email", "test@example.com"],
        vec!["config", "user.name", "Test"],
        vec!["add", "services.yaml"],
        vec!["commit", "-m", "first commit"],
    ] {
        std::process::Command::new("git")
            .args(
                std::iter::once("-C")
                    .chain(std::iter::once(root.to_str().unwrap()))
                    .chain(args.iter().copied()),
            )
            .output()
            .unwrap();
    }

    let manifest_path = root.join("services.yaml");
    let m = svccat::manifest::Manifest::load(&manifest_path).unwrap();
    let d = svccat::discovery::discover_services(root, &m);

    let md = svccat::report::render_history_markdown(root, &manifest_path, &d, 3).unwrap();

    assert!(md.contains("## Drift History"));
    assert!(md.contains("| Commit | Summary |"));
    assert!(md.contains("first commit"));
}

// ── v0.10.0: --format github-annotation ──────────────────────────────────────

#[test]
fn github_annotation_no_drift_emits_nothing() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    // No drift means no annotations. We can't easily capture stdout here,
    // but we verify the function doesn't panic and report is empty.
    assert!(report.drifts.is_empty());
}

#[test]
fn github_annotation_renders_error_and_warning() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    // ghost-service declared but missing → error drift
    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: ghost-service
    language: Rust
    role: API
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    // Verify we have drift to annotate
    assert!(!report.drifts.is_empty());
    // Calling render_check should not panic
    // (stdout capture requires a more complex setup; correctness verified via format string logic)
}

// ── v0.10.0: svccat report --badge ───────────────────────────────────────────

#[test]
fn badge_clean_contains_brightgreen() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let badge = svccat::report::render_badge(&report);

    assert!(
        badge.contains("brightgreen"),
        "clean repo badge should be brightgreen"
    );
    assert!(badge.contains("shields.io"), "badge should use shields.io");
    assert!(
        badge.starts_with("[!["),
        "badge should be Markdown image link"
    );
    assert!(
        badge.contains("crates.io"),
        "badge should link to crates.io"
    );
}

#[test]
fn badge_with_errors_contains_red() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    // Declared but missing → error
    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: ghost-service
    language: Rust
    role: API
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let badge = svccat::report::render_badge(&report);

    assert!(badge.contains("red"), "drifty repo badge should be red");
    assert!(badge.contains("error"), "badge label should mention error");
}

// ── v0.11.0: --format junit ───────────────────────────────────────────────────

#[test]
fn junit_output_contains_failures_for_drift_and_unreachable_ping() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    // Declared but missing -> error drift
    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: ghost-service
    language: Rust
    role: API
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    let ping_results = vec![svccat::ping::PingResult {
        service: "ghost-service".to_string(),
        url: "https://ghost.example".to_string(),
        ping: svccat::ping::PingStatus::Unreachable {
            reason: "timeout".to_string(),
        },
    }];

    let xml = svccat::output::junit::build_check_document(&report, &ping_results);

    assert!(xml.starts_with("<?xml"), "expected XML declaration");
    assert!(
        xml.contains("testsuite name=\"svccat.check\""),
        "expected check testsuite"
    );
    assert!(
        xml.contains("<failure"),
        "expected failures in junit output"
    );
    assert!(
        xml.contains("DeclaredMissingFromRepo"),
        "expected drift testcase"
    );
    assert!(
        xml.contains("ghost-service"),
        "expected service in testcase"
    );
    assert!(
        xml.contains("classname=\"svccat.ping\""),
        "expected ping testcase"
    );
}

#[test]
fn junit_since_reports_only_new_drift() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");

    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    role: API
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let mut old_report = svccat::drift::analyze(&m, &d, root);
    old_report.manifest = "services.yaml".to_string();

    // Add a new undeclared service to introduce new drift.
    touch(root, "services/new-feature/go.mod");
    let d2 = svccat::discovery::discover_services(root, &m);
    let mut new_report = svccat::drift::analyze(&m, &d2, root);
    new_report.manifest = "services.yaml".to_string();

    let (xml, new_count) =
        svccat::output::junit::build_since_document(&old_report, &new_report, "HEAD~1");

    assert_eq!(new_count, 1, "expected exactly one new drift item");
    assert!(
        xml.contains("testsuite name=\"svccat.check.since\""),
        "expected since testsuite"
    );
    assert!(
        xml.contains("property name=\"git_ref\" value=\"HEAD~1\""),
        "expected git_ref property"
    );
    assert!(
        xml.contains("UndeclaredInRepo:new-feature"),
        "expected only new drift testcase"
    );
}

#[test]
fn output_matrix_from_shared_drift_fixture_is_structurally_valid() {
    let dir = TempDir::new().unwrap();
    let root = dir.path();

    touch(root, "services/api/Cargo.toml");
    touch(root, "services/rogue/go.mod");

    // api is missing role (missing-field), ghost-service is declared but absent
    // (declared-missing), and rogue is undeclared in repo.
    write_manifest(
        root,
        r#"
discovery:
  paths: ["services/*"]
services:
  - name: api
    language: Rust
    platform: Cloud Run
  - name: ghost-service
    language: Go
    role: Worker
    platform: Cloud Run
"#,
    );

    let (m, d) = load(root);
    let report = svccat::drift::analyze(&m, &d, root);
    assert!(!report.drifts.is_empty(), "fixture should contain drift");

    let json_output = svccat::output::json::render_check_to_string(&report, &[]).unwrap();
    let json_value: serde_json::Value = serde_json::from_str(&json_output).unwrap();
    assert_eq!(
        json_value["summary"]["errors"].as_u64().unwrap(),
        report.error_count() as u64
    );
    assert_eq!(
        json_value["summary"]["warnings"].as_u64().unwrap(),
        report.warning_count() as u64
    );

    let slack_output = svccat::output::slack::render_check_to_string(&report).unwrap();
    let slack_value: serde_json::Value = serde_json::from_str(&slack_output).unwrap();
    assert!(slack_value["blocks"].is_array());
    assert!(
        slack_output.contains("ghost-service") || slack_output.contains("rogue"),
        "slack payload should include drift services"
    );

    let teams_output = svccat::output::teams::render_check_to_string(&report).unwrap();
    let teams_value: serde_json::Value = serde_json::from_str(&teams_output).unwrap();
    assert!(teams_value["attachments"].is_array());
    assert!(
        teams_output.contains("ghost-service") || teams_output.contains("rogue"),
        "teams payload should include drift services"
    );

    let datadog_output = svccat::output::datadog::render_check_to_string(&report).unwrap();
    let datadog_value: serde_json::Value = serde_json::from_str(&datadog_output).unwrap();
    assert!(datadog_value["events"].is_array());
    assert_eq!(
        datadog_value["errors"].as_u64().unwrap(),
        report.error_count() as u64
    );
    assert_eq!(
        datadog_value["warnings"].as_u64().unwrap(),
        report.warning_count() as u64
    );

    let mermaid_graph = svccat::output::mermaid::render_graph_filtered_string(&m, None);
    assert!(mermaid_graph.contains("graph TD"));
    assert!(mermaid_graph.contains("api"));
    assert!(mermaid_graph.contains("ghost-service"));
}