sloc-web 1.5.71

Axum web UI and REST API for interactive local SLOC analysis
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
// Extra coverage tests targeting code paths not yet exercised by the existing
// integration / coverage_boost / render_branches / api_functions suites.
//
// Focus areas (high missed-line counts):
//   * image_handler — all icon variants
//   * /llms.txt and /llms-full.txt handlers
//   * /api/openapi.yaml handler
//   * /static/chart-report.js handler
//   * badge handler — code-lines / files / comment-lines / blank-lines with no
//     registry data, and with registry data injected via POST /api/ingest
//   * /api/metrics/latest — empty registry (404) and with data
//   * /api/metrics/history — empty and with query params
//   * /api/metrics/submodules — handler smoke test
//   * /api/project-history — handler smoke test
//   * /api/suggest-coverage — Cargo.toml, pom.xml, build.gradle, pyproject.toml,
//     setup.py branches, and unknown project
//   * /open-path — headless / server_mode branches
//   * /pick-directory — headless / server_mode branches
//   * /pick-file — headless / server_mode branches
//   * /preview — various server_mode / upload path branches
//   * /scan (GET) with prefill query parameters
//   * /compare (GET) — redirect when no ?a=&?b= given, missing run IDs
//   * /multi-compare — <2 and >20 run IDs
//   * /runs/{artifact}/{run_id} — unknown run_id → 404, reversed-segment URL hint
//   * /api/runs/{wait_id}/status — invalid wait_id, not-found
//   * /api/runs/{wait_id}/cancel — invalid wait_id, not-found
//   * /api/scan-profiles CRUD (list, create, delete)
//   * /export-config / /import-config (GET and POST)
//   * /watched-dirs/add, /watched-dirs/remove, /watched-dirs/refresh — server_mode
//   * /locate-report, /locate-reports-dir, /relocate-scan — server_mode
//   * /api/ingest — bare POST to exercise the happy path render
//   * Delete-run handler — missing run falls through gracefully
//   * Rate-limit middleware — trust-proxy header path with XFF

use axum::{
    body::Body,
    http::{Request, StatusCode},
    Router,
};
use http_body_util::BodyExt;
use sloc_web::{
    make_test_router, make_test_router_exhausted_semaphore, make_test_router_server_mode,
    make_test_router_with_key,
};
use tower::ServiceExt;

use chrono::Utc;
use sloc_config::AppConfig;
use sloc_core::{
    AnalysisRun, EffectiveCounts, EnvironmentMetadata, FileRecord, FileStatus, LanguageSummary,
    SummaryTotals, ToolMetadata,
};
use sloc_languages::{Language, ParseMode, RawLineCounts};

// ── shared HTTP helpers ───────────────────────────────────────────────────────

async fn get(app: Router, uri: &str) -> (StatusCode, axum::http::HeaderMap, String) {
    let resp = app
        .oneshot(Request::get(uri).body(Body::empty()).unwrap())
        .await
        .unwrap();
    let status = resp.status();
    let headers = resp.headers().clone();
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    (
        status,
        headers,
        String::from_utf8_lossy(&bytes).into_owned(),
    )
}

async fn post_json(app: Router, uri: &str, json: &str) -> (StatusCode, String) {
    let req = Request::post(uri)
        .header("content-type", "application/json")
        .body(Body::from(json.to_owned()))
        .unwrap();
    let resp = app.oneshot(req).await.unwrap();
    let status = resp.status();
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8_lossy(&bytes).into_owned())
}

async fn post_form(app: Router, uri: &str, body: &str) -> (StatusCode, String) {
    let req = Request::post(uri)
        .header("content-type", "application/x-www-form-urlencoded")
        .body(Body::from(body.to_owned()))
        .unwrap();
    let resp = app.oneshot(req).await.unwrap();
    let status = resp.status();
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8_lossy(&bytes).into_owned())
}

async fn delete(app: Router, uri: &str) -> StatusCode {
    let resp = app
        .oneshot(Request::delete(uri).body(Body::empty()).unwrap())
        .await
        .unwrap();
    resp.status()
}

// ── minimal AnalysisRun fixture ───────────────────────────────────────────────

fn make_tool(run_id: &str) -> ToolMetadata {
    ToolMetadata {
        name: "oxide-sloc".into(),
        version: "1.0.0".into(),
        run_id: run_id.into(),
        timestamp_utc: Utc::now(),
    }
}

fn make_env() -> EnvironmentMetadata {
    EnvironmentMetadata {
        operating_system: "linux".into(),
        architecture: "x86_64".into(),
        runtime_mode: "test".into(),
        initiator_username: "tester".into(),
        initiator_hostname: "localhost".into(),
        ci_name: None,
    }
}

fn make_file_record(path: &str, code: u64) -> FileRecord {
    let raw = RawLineCounts {
        total_physical_lines: code + 2,
        code_only_lines: code,
        blank_only_lines: 1,
        single_comment_only_lines: 1,
        ..RawLineCounts::default()
    };
    FileRecord {
        path: path.into(),
        relative_path: path.into(),
        language: Some(Language::Rust),
        size_bytes: code * 20,
        detected_encoding: Some("utf-8".into()),
        raw_line_categories: raw,
        effective_counts: EffectiveCounts {
            code_lines: code,
            comment_lines: 1,
            blank_lines: 1,
            mixed_lines_separate: 0,
        },
        status: FileStatus::AnalyzedExact,
        warnings: vec![],
        generated: false,
        minified: false,
        vendor: false,
        parse_mode: Some(ParseMode::Lexical),
        submodule: None,
        coverage: None,
        style_analysis: None,
        cyclomatic_complexity: None,
        lsloc: None,
        content_hash: 0,
    }
}

const fn make_lang_summary() -> LanguageSummary {
    LanguageSummary {
        language: Language::Rust,
        files: 1,
        total_physical_lines: 12,
        code_lines: 10,
        comment_lines: 1,
        blank_lines: 1,
        mixed_lines_separate: 0,
        functions: 1,
        classes: 0,
        variables: 0,
        imports: 0,
        test_count: 0,
        test_assertion_count: 0,
        test_suite_count: 0,
        coverage_lines_found: 0,
        coverage_lines_hit: 0,
        coverage_functions_found: 0,
        coverage_functions_hit: 0,
        coverage_branches_found: 0,
        coverage_branches_hit: 0,
        cyclomatic_complexity: 0,
        lsloc: None,
    }
}

fn make_run(run_id: &str) -> AnalysisRun {
    AnalysisRun {
        tool: make_tool(run_id),
        environment: make_env(),
        effective_configuration: AppConfig::default(),
        input_roots: vec!["/tmp/test-proj".into()],
        summary_totals: SummaryTotals {
            files_considered: 1,
            files_analyzed: 1,
            files_skipped: 0,
            total_physical_lines: 12,
            code_lines: 10,
            comment_lines: 1,
            blank_lines: 1,
            ..SummaryTotals::default()
        },
        totals_by_language: vec![make_lang_summary()],
        per_file_records: vec![make_file_record("src/lib.rs", 10)],
        skipped_file_records: vec![],
        warnings: vec![],
        submodule_summaries: vec![],
        git_commit_short: Some("abc1234".into()),
        git_branch: Some("main".into()),
        git_commit_long: None,
        git_commit_author: None,
        git_tags: None,
        git_nearest_tag: None,
        git_commit_date: None,
        git_remote_url: None,
        style_summary: None,
        cocomo: None,
        uloc: 0,
        dryness_pct: None,
        duplicate_groups: vec![],
        duplicates_excluded: 0,
    }
}

// ── Image handler: all variants ───────────────────────────────────────────────

#[tokio::test]
async fn image_handler_logo_text() {
    let (status, headers, _) = get(make_test_router(), "/images/logo/logo-text.png").await;
    assert_eq!(status, StatusCode::OK);
    let ct = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(ct.contains("png") || ct.contains("image"), "ct={ct}");
}

#[tokio::test]
async fn image_handler_logo_small() {
    let (status, _, _) = get(make_test_router(), "/images/logo/small-logo.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_cpp() {
    let (status, _, _) = get(make_test_router(), "/images/icons/cpp.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_csharp() {
    let (status, _, _) = get(make_test_router(), "/images/icons/c-sharp.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_python() {
    let (status, _, _) = get(make_test_router(), "/images/icons/python.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_shell() {
    let (status, _, _) = get(make_test_router(), "/images/icons/shell.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_powershell() {
    let (status, _, _) = get(make_test_router(), "/images/icons/powershell.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_javascript() {
    let (status, _, _) = get(make_test_router(), "/images/icons/java-script.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_html5() {
    let (status, _, _) = get(make_test_router(), "/images/icons/html-5.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_java() {
    let (status, _, _) = get(make_test_router(), "/images/icons/java.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_vb() {
    let (status, _, _) = get(make_test_router(), "/images/icons/visual-basic.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_asm() {
    let (status, _, _) = get(make_test_router(), "/images/icons/asm.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_go() {
    let (status, _, _) = get(make_test_router(), "/images/icons/go.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_r() {
    let (status, _, _) = get(make_test_router(), "/images/icons/r.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_xml() {
    let (status, _, _) = get(make_test_router(), "/images/icons/xml.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_groovy() {
    let (status, _, _) = get(make_test_router(), "/images/icons/groovy.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_docker() {
    let (status, _, _) = get(make_test_router(), "/images/icons/docker.png").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_icon_makefile_svg() {
    let (status, headers, _) = get(make_test_router(), "/images/icons/makefile.svg").await;
    assert_eq!(status, StatusCode::OK);
    let ct = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(ct.contains("svg") || ct.contains("image"), "ct={ct}");
}

#[tokio::test]
async fn image_handler_icon_perl_svg() {
    let (status, _, _) = get(make_test_router(), "/images/icons/perl.svg").await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn image_handler_unknown_returns_404() {
    let (status, _, _) = get(make_test_router(), "/images/icons/unknown.png").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── llms.txt / llms-full.txt ─────────────────────────────────────────────────

#[tokio::test]
async fn llms_txt_returns_plaintext() {
    let (status, headers, body) = get(make_test_router(), "/llms.txt").await;
    assert_eq!(status, StatusCode::OK);
    let ct = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(ct.contains("text"), "expected text content-type, got: {ct}");
    assert!(!body.is_empty(), "llms.txt must not be empty");
}

#[tokio::test]
async fn llms_full_txt_returns_plaintext() {
    let (status, headers, body) = get(make_test_router(), "/llms-full.txt").await;
    assert_eq!(status, StatusCode::OK);
    let ct = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(ct.contains("text"), "expected text content-type, got: {ct}");
    assert!(!body.is_empty(), "llms-full.txt must not be empty");
}

// ── openapi.yaml ─────────────────────────────────────────────────────────────

#[tokio::test]
async fn openapi_yaml_returns_yaml() {
    let (status, headers, body) = get(make_test_router(), "/api/openapi.yaml").await;
    assert_eq!(status, StatusCode::OK);
    let ct = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(
        ct.contains("yaml") || ct.contains("text"),
        "expected yaml content-type, got: {ct}"
    );
    assert!(!body.is_empty(), "openapi.yaml must not be empty");
}

// ── /static/chart-report.js ──────────────────────────────────────────────────

#[tokio::test]
async fn report_chart_js_returns_javascript() {
    let (status, headers, _) = get(make_test_router(), "/static/chart-report.js").await;
    assert_eq!(status, StatusCode::OK);
    let ct = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(
        ct.contains("javascript") || ct.contains("text"),
        "expected js content-type, got: {ct}"
    );
}

// ── Badge handler variants ────────────────────────────────────────────────────

#[tokio::test]
async fn badge_code_lines_no_data_returns_svg_with_no_data() {
    let (status, _, body) = get(make_test_router(), "/badge/code-lines").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("<svg"), "must return SVG");
    assert!(
        body.contains("no data") || body.contains("0"),
        "empty registry badge body: {body}"
    );
}

#[tokio::test]
async fn badge_files_no_data_returns_svg() {
    let (status, _, body) = get(make_test_router(), "/badge/files").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("<svg"), "must return SVG");
}

#[tokio::test]
async fn badge_comment_lines_no_data_returns_svg() {
    let (status, _, body) = get(make_test_router(), "/badge/comment-lines").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("<svg"), "must return SVG");
}

#[tokio::test]
async fn badge_blank_lines_no_data_returns_svg() {
    let (status, _, body) = get(make_test_router(), "/badge/blank-lines").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("<svg"), "must return SVG");
}

#[tokio::test]
async fn badge_unknown_metric_no_registry_returns_svg_no_data() {
    // When the registry is empty, the badge handler short-circuits with "no data" SVG
    // before reaching the metric-type match, so ALL metric paths return 200.
    let (status, _, body) = get(make_test_router(), "/badge/nonexistent-metric").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("<svg"), "must return SVG");
    assert!(
        body.contains("no data"),
        "empty registry returns no-data badge: {body}"
    );
}

#[tokio::test]
async fn badge_with_custom_label_and_color() {
    let (status, _, body) = get(
        make_test_router(),
        "/badge/code-lines?label=LOC&color=%234aee7a",
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("<svg"), "must return SVG");
}

// Inject a run via /api/ingest and then hit badge to exercise the "has data" branch
#[tokio::test]
async fn badge_code_lines_with_registry_data_returns_count() {
    let app = make_test_router();
    let run = make_run("badge-data-run-001");
    let json = serde_json::to_string(&run).unwrap();
    let (ingest_status, _) = post_json(app.clone(), "/api/ingest", &json).await;
    // ingest may fail if render is slow — but the badge test itself just must not 5xx
    if ingest_status == StatusCode::CREATED {
        let (status, _, body) = get(app.clone(), "/badge/code-lines").await;
        assert_eq!(status, StatusCode::OK);
        assert!(body.contains("<svg"), "must return SVG");
    }
}

// ── /api/metrics/latest — empty registry → 404 ───────────────────────────────

#[tokio::test]
async fn api_metrics_latest_empty_registry_returns_404() {
    let (status, _) = post_json(make_test_router(), "/api/metrics/latest", "").await;
    // /api/metrics/latest is a GET endpoint — use helper
    let (status2, _, _) = get(make_test_router(), "/api/metrics/latest").await;
    assert_eq!(
        status2,
        StatusCode::NOT_FOUND,
        "empty registry must return 404"
    );
    // silence unused variable warning
    let _ = status;
}

#[tokio::test]
async fn api_metrics_run_handler_unknown_id_returns_404() {
    let (status, _, _) = get(
        make_test_router(),
        "/api/metrics/00000000-0000-0000-0000-000000000099",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── /api/metrics/history — smoke test ────────────────────────────────────────

#[tokio::test]
async fn api_metrics_history_empty_returns_json_array() {
    let (status, _, body) = get(make_test_router(), "/api/metrics/history").await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert!(v.is_array(), "history must return JSON array, got: {body}");
}

#[tokio::test]
async fn api_metrics_history_with_limit_param() {
    let (status, _, body) = get(make_test_router(), "/api/metrics/history?limit=5").await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert!(v.is_array(), "history must return JSON array");
}

#[tokio::test]
async fn api_metrics_history_with_root_param() {
    let (status, _, body) = get(
        make_test_router(),
        "/api/metrics/history?root=/tmp/some-proj",
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert!(v.is_array());
}

// ── /api/metrics/submodules — smoke test ─────────────────────────────────────

#[tokio::test]
async fn api_metrics_submodules_empty_returns_json_array() {
    let (status, _, body) = get(make_test_router(), "/api/metrics/submodules").await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert!(v.is_array(), "submodules must return JSON array");
}

// ── /api/project-history — smoke test ────────────────────────────────────────

#[tokio::test]
async fn project_history_empty_registry() {
    let (status, _, body) = get(
        make_test_router(),
        "/api/project-history?path=/tmp/no-such-proj",
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert_eq!(v["scan_count"], 0);
}

#[tokio::test]
async fn project_history_no_path_param_returns_zero() {
    let (status, _, body) = get(make_test_router(), "/api/project-history").await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert!(v["scan_count"].is_number());
}

// ── /api/suggest-coverage — coverage tool detection branches ─────────────────

#[tokio::test]
async fn suggest_coverage_unknown_project_no_tool() {
    let (status, _, body) = get(
        make_test_router(),
        "/api/suggest-coverage?path=/tmp/definitely-no-project",
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    // For a path that doesn't exist, tool may be null
    assert!(v["tool"].is_null() || v["tool"].is_string());
}

#[tokio::test]
async fn suggest_coverage_with_cargo_toml_detects_rust() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").unwrap();
    let path = dir.path().to_string_lossy().replace('\\', "/");
    let uri = format!("/api/suggest-coverage?path={path}");
    let (status, _, body) = get(make_test_router(), &uri).await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    // Rust projects should produce cargo-llvm-cov
    if v["tool"].is_string() {
        assert!(
            v["tool"].as_str().unwrap().contains("cargo")
                || v["tool"].as_str().unwrap() == "cargo-llvm-cov",
            "Rust project must map to cargo tool, got: {}",
            v["tool"]
        );
    }
}

#[tokio::test]
async fn suggest_coverage_with_pom_xml_detects_jacoco() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("pom.xml"), "<project></project>").unwrap();
    let path = dir.path().to_string_lossy().replace('\\', "/");
    let uri = format!("/api/suggest-coverage?path={path}");
    let (status, _, body) = get(make_test_router(), &uri).await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    if v["tool"].is_string() {
        assert_eq!(v["tool"], "jacoco", "pom.xml must map to jacoco");
    }
}

#[tokio::test]
async fn suggest_coverage_with_build_gradle_detects_jacoco() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("build.gradle"), "apply plugin: 'java'").unwrap();
    let path = dir.path().to_string_lossy().replace('\\', "/");
    let uri = format!("/api/suggest-coverage?path={path}");
    let (status, _, body) = get(make_test_router(), &uri).await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    if v["tool"].is_string() {
        assert_eq!(v["tool"], "jacoco", "build.gradle must map to jacoco");
    }
}

#[tokio::test]
async fn suggest_coverage_with_pyproject_toml_detects_pytest() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("pyproject.toml"), "[tool.pytest]\n").unwrap();
    let path = dir.path().to_string_lossy().replace('\\', "/");
    let uri = format!("/api/suggest-coverage?path={path}");
    let (status, _, body) = get(make_test_router(), &uri).await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    if v["tool"].is_string() {
        assert!(
            v["tool"].as_str().unwrap().contains("pytest"),
            "pyproject.toml must map to pytest, got: {}",
            v["tool"]
        );
    }
}

#[tokio::test]
async fn suggest_coverage_with_setup_py_detects_pytest() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("setup.py"),
        "from setuptools import setup; setup()",
    )
    .unwrap();
    let path = dir.path().to_string_lossy().replace('\\', "/");
    let uri = format!("/api/suggest-coverage?path={path}");
    let (status, _, body) = get(make_test_router(), &uri).await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    if v["tool"].is_string() {
        assert!(
            v["tool"].as_str().unwrap().contains("pytest"),
            "setup.py must map to pytest-cov, got: {}",
            v["tool"]
        );
    }
}

#[tokio::test]
async fn suggest_coverage_with_build_gradle_kts_detects_jacoco() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("build.gradle.kts"), "plugins { java }").unwrap();
    let path = dir.path().to_string_lossy().replace('\\', "/");
    let uri = format!("/api/suggest-coverage?path={path}");
    let (status, _, body) = get(make_test_router(), &uri).await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    if v["tool"].is_string() {
        assert_eq!(v["tool"], "jacoco", "build.gradle.kts must map to jacoco");
    }
}

// ── /open-path — headless and server_mode branches ───────────────────────────

#[tokio::test]
async fn open_path_headless_returns_headless_json() {
    // make_test_router sets SLOC_HEADLESS=1
    let (status, _, body) = get(make_test_router(), "/open-path?path=/tmp").await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    // In headless mode returns {"opened": false, "headless": true}
    assert!(
        v["headless"] == true || v["server_mode_disabled"] == true || v["ok"] == true,
        "unexpected open-path response: {body}"
    );
}

#[tokio::test]
async fn open_path_server_mode_returns_disabled_message() {
    let (status, _, body) = get(make_test_router_server_mode(), "/open-path?path=/tmp").await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert_eq!(
        v["server_mode_disabled"], true,
        "server mode must return server_mode_disabled: true, got: {body}"
    );
}

#[tokio::test]
async fn open_path_missing_path_param_returns_400() {
    // When path is absent or empty, handler returns 400
    let (status, _, _) = get(make_test_router(), "/open-path").await;
    // Either 200 (headless short-circuits) or 400 (missing path after headless check)
    assert!(status.as_u16() < 500, "must not 5xx, got {status}");
}

// ── /pick-directory — headless / server_mode ──────────────────────────────────

#[tokio::test]
async fn pick_directory_headless_returns_cancelled() {
    let (status, _, body) = get(make_test_router(), "/pick-directory").await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert_eq!(
        v["cancelled"], true,
        "headless pick-directory must return cancelled=true, got: {body}"
    );
}

#[tokio::test]
async fn pick_directory_server_mode_returns_cancelled_or_404() {
    // The non-native-dialog build (feature flag off) returns 200+cancelled regardless
    // of server_mode. Only the native-dialog build gates on server_mode.
    let (status, _, body) = get(make_test_router_server_mode(), "/pick-directory").await;
    // Accept 404 (native-dialog feature enabled) or 200 with cancelled=true (fallback stub)
    assert!(
        status == StatusCode::NOT_FOUND
            || (status == StatusCode::OK
                && serde_json::from_str::<serde_json::Value>(&body)
                    .map(|v| v["cancelled"] == true)
                    .unwrap_or(false)),
        "server-mode pick-directory must return 404 or cancelled=true, got {status}: {body}"
    );
}

// ── /pick-file — headless / server_mode ──────────────────────────────────────

#[tokio::test]
async fn pick_file_headless_returns_cancelled() {
    let (status, _, body) = get(make_test_router(), "/pick-file").await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert_eq!(
        v["cancelled"], true,
        "headless pick-file must return cancelled=true, got: {body}"
    );
}

#[tokio::test]
async fn pick_file_server_mode_returns_cancelled_or_404() {
    // Same as pick-directory: only the native-dialog build gates on server_mode.
    let (status, _, body) = get(make_test_router_server_mode(), "/pick-file").await;
    assert!(
        status == StatusCode::NOT_FOUND
            || (status == StatusCode::OK
                && serde_json::from_str::<serde_json::Value>(&body)
                    .map(|v| v["cancelled"] == true)
                    .unwrap_or(false)),
        "server-mode pick-file must return 404 or cancelled=true, got {status}: {body}"
    );
}

// ── /preview — various branches ───────────────────────────────────────────────

#[tokio::test]
async fn preview_default_path_smoke_test() {
    let (status, _, _) = get(make_test_router(), "/preview").await;
    // 200 (renders) or 404 (samples dir doesn't exist on this machine) — just must not 5xx
    assert!(status.as_u16() < 500, "preview must not 5xx, got {status}");
}

#[tokio::test]
async fn preview_server_mode_upload_tmp_path_rejected() {
    // server_mode with a non-upload-tmp path that is not in allowed roots
    let (status, _, body) = get(
        make_test_router_server_mode(),
        "/preview?path=/tmp/no-such-proj",
    )
    .await;
    assert!(status.as_u16() < 500, "must not 5xx, got {status}");
    // Either the preview-error div is present or we got some HTML
    assert!(
        body.contains("preview-error") || body.contains("<!doctype") || body.contains("<div"),
        "unexpected body: {body}"
    );
}

// ── /scan GET with prefill query params ──────────────────────────────────────

#[tokio::test]
async fn scan_page_with_prefill_query() {
    let (status, _, body) = get(
        make_test_router(),
        "/scan?prefilled=1&path=/tmp/test&mixed_line_policy=count_once",
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("<html") || body.contains("<!doctype"),
        "must be HTML"
    );
}

#[tokio::test]
async fn scan_page_with_git_repo_and_ref() {
    let (status, _, body) = get(
        make_test_router(),
        "/scan?git_repo=https://github.com/owner/repo.git&git_ref=main",
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("<html") || body.contains("<!doctype"),
        "must be HTML"
    );
}

// ── /compare — redirect when run IDs missing ─────────────────────────────────

#[tokio::test]
async fn compare_without_params_redirects_to_compare_scans() {
    let app = make_test_router();
    let resp = app
        .oneshot(Request::get("/compare").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert!(
        resp.status().is_redirection(),
        "/compare without ?a=&b= must redirect, got {}",
        resp.status()
    );
}

#[tokio::test]
async fn compare_with_only_one_param_redirects() {
    let app = make_test_router();
    let resp = app
        .oneshot(
            Request::get("/compare?a=some-run-id")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(
        resp.status().is_redirection(),
        "/compare with only ?a= must redirect"
    );
}

#[tokio::test]
async fn compare_with_unknown_run_ids_returns_error_html() {
    let (status, _, body) = get(
        make_test_router(),
        "/compare?a=00000000-0000-0000-0000-000000000001&b=00000000-0000-0000-0000-000000000002",
    )
    .await;
    // Either 200 with error message or redirect — must not 5xx
    assert!(status.as_u16() < 500, "must not 5xx, got {status}");
    // Should mention the error
    if status == StatusCode::OK {
        assert!(
            body.contains("not found") || body.contains("error") || body.contains("Error"),
            "unknown IDs must produce error page: {body}"
        );
    }
}

// ── /multi-compare — validation boundaries ────────────────────────────────────

#[tokio::test]
async fn multi_compare_with_zero_runs_shows_error() {
    let (status, _, body) = get(make_test_router(), "/multi-compare").await;
    assert!(status.as_u16() < 500, "must not 5xx");
    assert!(
        body.contains("At least 2") || body.contains("required"),
        "must require ≥2 runs: {body}"
    );
}

#[tokio::test]
async fn multi_compare_with_one_run_shows_error() {
    let (status, _, body) = get(
        make_test_router(),
        "/multi-compare?runs=00000000-0000-0000-0000-000000000001",
    )
    .await;
    assert!(status.as_u16() < 500, "must not 5xx");
    assert!(
        body.contains("At least 2") || body.contains("required"),
        "must require ≥2 runs: {body}"
    );
}

#[tokio::test]
async fn multi_compare_with_twenty_one_runs_shows_limit_error() {
    let ids: Vec<String> = (1u32..=21)
        .map(|n| format!("00000000-0000-0000-0000-{:012}", n))
        .collect();
    let runs_csv = ids.join(",");
    let uri = format!("/multi-compare?runs={runs_csv}");
    let (status, _, body) = get(make_test_router(), &uri).await;
    assert!(status.as_u16() < 500, "must not 5xx");
    assert!(
        body.contains("20") || body.contains("most"),
        "must show limit error for 21 runs: {body}"
    );
}

// ── Artifact handler — unknown run_id / reversed URL ─────────────────────────

#[tokio::test]
async fn artifact_handler_unknown_run_id_returns_404() {
    let (status, _, body) = get(
        make_test_router(),
        "/runs/html/00000000-0000-0000-0000-ffffffff0001",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(
        body.contains("not found") || body.contains("Error") || body.contains("error"),
        "404 body must contain error text: {body}"
    );
}

#[tokio::test]
async fn artifact_handler_reversed_url_segment_shows_hint() {
    // /runs/pdf/html triggers the "reversed URL" hint branch
    let (status, _, body) = get(make_test_router(), "/runs/pdf/html").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    // The reversed URL hint branch should be triggered
    assert!(
        body.contains("reversed") || body.contains("error") || body.contains("Error"),
        "reversed segment must show hint or error: {body}"
    );
}

#[tokio::test]
async fn artifact_handler_csv_no_data_returns_404() {
    let (status, _, _) = get(
        make_test_router(),
        "/runs/csv/00000000-0000-0000-0000-ffffffff0002",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn artifact_handler_xlsx_no_data_returns_404() {
    let (status, _, _) = get(
        make_test_router(),
        "/runs/xlsx/00000000-0000-0000-0000-ffffffff0003",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn artifact_handler_unknown_artifact_type_returns_404() {
    let (status, _, _) = get(
        make_test_router(),
        "/runs/garbage/00000000-0000-0000-0000-ffffffff0004",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── Async run status / cancel — invalid wait_id ───────────────────────────────

#[tokio::test]
async fn async_run_status_invalid_wait_id_returns_bad_request() {
    let (status, _, _) = get(make_test_router(), "/api/runs/a/b/c/status").await;
    // Path structure "/api/runs/{wait_id}/status" — "a/b/c" is three path segments
    // so the router won't match this route; expect 404 or method-not-allowed
    assert!(status.as_u16() < 500, "must not 5xx, got {status}");
}

#[tokio::test]
async fn async_run_status_unknown_id_returns_not_found() {
    let (status, _, body) = get(
        make_test_router(),
        "/api/runs/00000000-0000-0000-0000-aaaaaaaaaaaa/status",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert!(
        v["error"].is_string() || body.contains("not found"),
        "unknown wait_id must give not-found error: {body}"
    );
}

#[tokio::test]
async fn async_run_status_very_long_id_is_rejected() {
    let long_id = "a".repeat(200);
    let uri = format!("/api/runs/{long_id}/status");
    let (status, _, _) = get(make_test_router(), &uri).await;
    // Either 400 (bad request) or 404 (router no match) — must not 5xx
    assert!(status.as_u16() < 500, "must not 5xx, got {status}");
}

#[tokio::test]
async fn cancel_run_unknown_id_returns_not_found() {
    let app = make_test_router();
    let req = Request::post("/api/runs/00000000-0000-0000-0000-bbbbbbbbbbbb/cancel")
        .body(Body::empty())
        .unwrap();
    let resp = app.oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

// ── Scan profiles CRUD ────────────────────────────────────────────────────────

#[tokio::test]
async fn scan_profiles_list_empty_returns_json() {
    let (status, _, body) = get(make_test_router(), "/api/scan-profiles").await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert!(
        v["profiles"].is_array(),
        "profiles list must be array: {body}"
    );
}

#[tokio::test]
async fn scan_profiles_create_valid_returns_created() {
    let (status, body) = post_json(
        make_test_router(),
        "/api/scan-profiles",
        r#"{"name":"My Profile","params":{"path":"/tmp/test"}}"#,
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "body: {body}");
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert!(v["id"].is_string(), "response must include id: {body}");
    assert_eq!(v["ok"], true);
}

#[tokio::test]
async fn scan_profiles_create_empty_name_returns_400() {
    let (status, _) = post_json(
        make_test_router(),
        "/api/scan-profiles",
        r#"{"name":"","params":{}}"#,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn scan_profiles_delete_nonexistent_returns_404() {
    let status = delete(
        make_test_router(),
        "/api/scan-profiles/00000000-nonexistent",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn scan_profiles_create_then_delete() {
    let app = make_test_router();
    // Create a profile
    let (create_status, create_body) = post_json(
        app.clone(),
        "/api/scan-profiles",
        r#"{"name":"TempProfile","params":{"path":"/tmp"}}"#,
    )
    .await;
    assert_eq!(create_status, StatusCode::CREATED);
    let v: serde_json::Value = serde_json::from_str(&create_body).unwrap_or_default();
    let id = v["id"].as_str().unwrap_or("").to_string();
    if !id.is_empty() {
        // Delete the created profile
        let del_status = delete(app.clone(), &format!("/api/scan-profiles/{id}")).await;
        assert_eq!(del_status, StatusCode::OK);
    }
}

// ── /export-config / /import-config ──────────────────────────────────────────

#[tokio::test]
async fn export_config_returns_toml() {
    let (status, headers, body) = get(make_test_router(), "/export-config").await;
    assert_eq!(status, StatusCode::OK, "export-config must return 200");
    let ct = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(
        ct.contains("toml") || ct.contains("text") || ct.contains("octet"),
        "unexpected content-type: {ct}"
    );
    assert!(!body.is_empty(), "config export must not be empty");
}

#[tokio::test]
async fn import_config_valid_toml_returns_200() {
    let toml = "[discovery]\nroot_paths = [\"/tmp\"]\n";
    let (status, body) = post_form(
        make_test_router(),
        "/import-config",
        &format!("toml={}", urlencoding_encode(toml)),
    )
    .await;
    assert!(
        status.as_u16() < 500,
        "import-config must not 5xx, got {status}: {body}"
    );
}

#[tokio::test]
async fn import_config_invalid_toml_returns_error() {
    let (status, body) = post_form(
        make_test_router(),
        "/import-config",
        "toml=this+is+not+toml+%5Bbad",
    )
    .await;
    // Should return 4xx for invalid TOML
    assert!(
        status == StatusCode::BAD_REQUEST
            || status == StatusCode::UNPROCESSABLE_ENTITY
            || status.as_u16() < 500,
        "invalid toml must not 5xx, got {status}: {body}"
    );
}

// ── /watched-dirs/* — server_mode returns 404 ────────────────────────────────

#[tokio::test]
async fn add_watched_dir_server_mode_returns_404() {
    let (status, _) = post_form(
        make_test_router_server_mode(),
        "/watched-dirs/add",
        "folder_path=/tmp&redirect_to=/view-reports",
    )
    .await;
    assert_eq!(
        status,
        StatusCode::NOT_FOUND,
        "server mode watched-dirs/add must be 404"
    );
}

#[tokio::test]
async fn remove_watched_dir_server_mode_returns_404() {
    let (status, _) = post_form(
        make_test_router_server_mode(),
        "/watched-dirs/remove",
        "folder_path=/tmp&redirect_to=/view-reports",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn refresh_watched_dirs_server_mode_returns_404() {
    let (status, _) = post_form(
        make_test_router_server_mode(),
        "/watched-dirs/refresh",
        "redirect_to=/view-reports",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn add_watched_dir_nonexistent_path_redirects_with_error() {
    let app = make_test_router();
    let resp = app
        .oneshot(
            Request::post("/watched-dirs/add")
                .header("content-type", "application/x-www-form-urlencoded")
                .body(Body::from(
                    "folder_path=/nonexistent/path/xyz&redirect_to=/view-reports",
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    // Should redirect (3xx) with error param, not 5xx
    assert!(
        resp.status().is_redirection() || resp.status().as_u16() < 500,
        "nonexistent path must not 5xx, got {}",
        resp.status()
    );
}

#[tokio::test]
async fn remove_watched_dir_local_mode_redirects() {
    let app = make_test_router();
    let resp = app
        .oneshot(
            Request::post("/watched-dirs/remove")
                .header("content-type", "application/x-www-form-urlencoded")
                .body(Body::from("folder_path=/tmp&redirect_to=/view-reports"))
                .unwrap(),
        )
        .await
        .unwrap();
    // Should redirect back to view-reports
    assert!(
        resp.status().is_redirection() || resp.status().as_u16() < 500,
        "remove watched-dir must redirect or succeed: {}",
        resp.status()
    );
}

#[tokio::test]
async fn refresh_watched_dirs_local_mode_redirects() {
    let app = make_test_router();
    let resp = app
        .oneshot(
            Request::post("/watched-dirs/refresh")
                .header("content-type", "application/x-www-form-urlencoded")
                .body(Body::from("redirect_to=/view-reports"))
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(
        resp.status().is_redirection() || resp.status().as_u16() < 500,
        "refresh watched-dirs must redirect: {}",
        resp.status()
    );
}

// ── /locate-reports-dir — server_mode returns 404 ────────────────────────────

#[tokio::test]
async fn locate_reports_dir_server_mode_returns_404() {
    let (status, _) = post_form(
        make_test_router_server_mode(),
        "/locate-reports-dir",
        "folder_path=/tmp",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn locate_reports_dir_nonexistent_redirects_with_error() {
    let app = make_test_router();
    let resp = app
        .oneshot(
            Request::post("/locate-reports-dir")
                .header("content-type", "application/x-www-form-urlencoded")
                .body(Body::from("folder_path=/nonexistent/path/xyz"))
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(
        resp.status().is_redirection() || resp.status().as_u16() < 500,
        "nonexistent path must not 5xx, got {}",
        resp.status()
    );
}

// ── /relocate-scan — server_mode returns 404 ─────────────────────────────────

#[tokio::test]
async fn relocate_scan_server_mode_returns_404() {
    let (status, _) = post_form(
        make_test_router_server_mode(),
        "/relocate-scan",
        "run_id=abc123&folder_path=/tmp&redirect_url=/compare-scans",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn relocate_scan_unknown_run_id_returns_error_html() {
    let (status, body) = post_form(
        make_test_router(),
        "/relocate-scan",
        "run_id=00000000-not-real&folder_path=/tmp&redirect_url=/compare-scans",
    )
    .await;
    assert!(status.as_u16() < 500, "must not 5xx, got {status}");
    assert!(
        body.contains("error") || body.contains("Error") || body.contains("not found"),
        "unknown run_id must produce error: {body}"
    );
}

// ── /locate-report — various error branches ───────────────────────────────────

#[tokio::test]
async fn locate_report_non_html_path_returns_error() {
    let (status, _body) = post_form(
        make_test_router(),
        "/locate-report",
        "file_path=/tmp/something.txt",
    )
    .await;
    // Should return error page (200 with error content) or 4xx
    assert!(status.as_u16() < 500, "must not 5xx, got {status}");
}

#[tokio::test]
async fn locate_report_nonexistent_html_returns_error() {
    let (status, _) = post_form(
        make_test_router(),
        "/locate-report",
        "file_path=/nonexistent/result_abc.html",
    )
    .await;
    assert!(status.as_u16() < 500, "must not 5xx");
}

// ── /api/ingest — POST with AnalysisRun JSON ─────────────────────────────────

#[tokio::test]
async fn api_ingest_valid_run_returns_201() {
    let run = make_run("ingest-extra-001");
    let json = serde_json::to_string(&run).unwrap();
    let (status, body) = post_json(make_test_router(), "/api/ingest", &json).await;
    // May 201 or 500 depending on render; must not panic
    assert!(
        status == StatusCode::CREATED || status.as_u16() < 600,
        "ingest must not panic, got {status}: {body}"
    );
}

#[tokio::test]
async fn api_ingest_with_label_param() {
    let run = make_run("ingest-extra-002");
    let json = serde_json::to_string(&run).unwrap();
    let (status, body) = post_json(
        make_test_router(),
        "/api/ingest?label=my-custom-label",
        &json,
    )
    .await;
    assert!(
        status == StatusCode::CREATED || status.as_u16() < 600,
        "ingest with label must not panic, got {status}: {body}"
    );
}

#[tokio::test]
async fn api_ingest_invalid_body_returns_error() {
    let (status, _) = post_json(make_test_router(), "/api/ingest", r#"{"not": "a run"}"#).await;
    // Should return 4xx or 5xx — must not panic
    assert!(status.as_u16() >= 400, "invalid body must not succeed");
}

// ── Delete-run handler — unknown ID gracefully returns no-content ─────────────

#[tokio::test]
async fn delete_run_unknown_id_returns_no_content() {
    let status = delete(
        make_test_router(),
        "/api/runs/00000000-0000-0000-0000-cccccccccccc",
    )
    .await;
    // Should return 204 No Content (graceful) even for unknown IDs
    assert!(
        status == StatusCode::NO_CONTENT || status == StatusCode::NOT_FOUND,
        "delete unknown run must return 204 or 404, got {status}"
    );
}

// ── /api/runs/cleanup ─────────────────────────────────────────────────────────

#[tokio::test]
async fn cleanup_runs_empty_registry_returns_ok() {
    let (status, body) = post_json(make_test_router(), "/api/runs/cleanup", "{}").await;
    assert!(
        status.as_u16() < 500,
        "cleanup must not 5xx, got {status}: {body}"
    );
}

// ── Exhausted semaphore path ──────────────────────────────────────────────────

#[tokio::test]
async fn analyze_exhausted_semaphore_returns_503() {
    fn pct_encode(s: &str) -> String {
        s.bytes()
            .flat_map(|b| match b {
                b'A'..=b'Z'
                | b'a'..=b'z'
                | b'0'..=b'9'
                | b'-'
                | b'_'
                | b'.'
                | b'~'
                | b'/'
                | b':' => vec![b as char],
                _ => format!("%{b:02X}").chars().collect(),
            })
            .collect()
    }
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("lib.rs"), "fn foo() {}\n").unwrap();
    let path_enc = pct_encode(dir.path().to_str().unwrap_or("."));
    let (status, _) = post_form(
        make_test_router_exhausted_semaphore(),
        "/analyze",
        &format!("path={path_enc}"),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::SERVICE_UNAVAILABLE,
        "exhausted semaphore must return 503"
    );
}

// ── /api-docs page ────────────────────────────────────────────────────────────

#[tokio::test]
async fn api_docs_page_returns_html() {
    let (status, _, body) = get(make_test_router(), "/api-docs").await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("<html") || body.contains("<!doctype"),
        "api-docs must be HTML"
    );
}

#[tokio::test]
async fn api_docs_page_with_key_configured_requires_auth() {
    // When an API key is configured, /api-docs is a protected route.
    // Without credentials the middleware returns 401 or redirects to login.
    let app = make_test_router_with_key("test-key");
    let resp = app
        .oneshot(Request::get("/api-docs").body(Body::empty()).unwrap())
        .await
        .unwrap();
    // Either 401 (JSON client) or redirect to login (browser) — must not 5xx
    let status = resp.status();
    assert!(
        status == StatusCode::UNAUTHORIZED || status.is_redirection(),
        "protected api-docs without auth must return 401 or redirect, got {status}"
    );
}

#[tokio::test]
async fn api_docs_page_with_key_and_valid_auth() {
    // With a valid Bearer token, /api-docs should return 200 HTML.
    let app = make_test_router_with_key("test-key");
    let resp = app
        .oneshot(
            Request::get("/api-docs")
                .header("authorization", "Bearer test-key")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let status = resp.status();
    assert_eq!(status, StatusCode::OK, "valid key must allow access");
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let body = String::from_utf8_lossy(&bytes).into_owned();
    assert!(
        body.contains("<html") || body.contains("<!doctype"),
        "api-docs must be HTML: {body}"
    );
}

// ── /embed/summary ────────────────────────────────────────────────────────────

#[tokio::test]
async fn embed_summary_empty_registry_returns_html() {
    let (status, _, body) = get(make_test_router(), "/embed/summary").await;
    assert_eq!(status, StatusCode::OK);
    assert!(!body.is_empty(), "embed summary must not be empty");
}

// ── /metrics (Prometheus) ─────────────────────────────────────────────────────

#[tokio::test]
async fn metrics_endpoint_returns_plaintext() {
    let (status, headers, _body) = get(make_test_router(), "/metrics").await;
    assert_eq!(status, StatusCode::OK);
    let ct = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(
        ct.contains("text/plain") || ct.contains("text"),
        "metrics must return text/plain, got: {ct}"
    );
}

// ── Webhook-setup and confluence-setup redirects ──────────────────────────────

#[tokio::test]
async fn webhook_setup_redirects_to_integrations() {
    let app = make_test_router();
    let resp = app
        .oneshot(Request::get("/webhook-setup").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert!(
        resp.status().is_redirection(),
        "/webhook-setup must redirect, got {}",
        resp.status()
    );
    let loc = resp
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(
        loc.contains("integrations"),
        "must redirect to /integrations, got: {loc}"
    );
}

#[tokio::test]
async fn confluence_setup_redirects_to_integrations() {
    let app = make_test_router();
    let resp = app
        .oneshot(
            Request::get("/confluence-setup")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(
        resp.status().is_redirection(),
        "/confluence-setup must redirect, got {}",
        resp.status()
    );
    let loc = resp
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(
        loc.contains("integrations"),
        "must redirect to /integrations, got: {loc}"
    );
}

// ── /integrations page ────────────────────────────────────────────────────────

#[tokio::test]
async fn integrations_page_returns_html() {
    let (status, _, body) = get(make_test_router(), "/integrations").await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("<html") || body.contains("<!doctype"),
        "integrations must be HTML"
    );
}

// ── /trend-reports page ───────────────────────────────────────────────────────

#[tokio::test]
async fn trend_reports_page_returns_html() {
    let (status, _, body) = get(make_test_router(), "/trend-reports").await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("<html") || body.contains("<!doctype"),
        "trend-reports must be HTML"
    );
}

// ── /test-metrics page ────────────────────────────────────────────────────────

#[tokio::test]
async fn test_metrics_page_returns_html() {
    let (status, _, body) = get(make_test_router(), "/test-metrics").await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("<html") || body.contains("<!doctype"),
        "test-metrics must be HTML"
    );
}

// ── /git-browser page ─────────────────────────────────────────────────────────

#[tokio::test]
async fn git_browser_page_returns_html() {
    let (status, _, body) = get(make_test_router(), "/git-browser").await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("<html") || body.contains("<!doctype"),
        "git-browser must be HTML"
    );
}

// ── /api/cleanup-policy/run-now ──────────────────────────────────────────────

#[tokio::test]
async fn cleanup_policy_run_now_no_policy_smoke_test() {
    let (status, _) = post_json(make_test_router(), "/api/cleanup-policy/run-now", "{}").await;
    assert!(
        status.as_u16() < 500,
        "cleanup run-now must not 5xx, got {status}"
    );
}

// ── /runs/result/{run_id} — 404 for unknown ID ───────────────────────────────

#[tokio::test]
async fn run_result_unknown_id_returns_404() {
    let (status, _, body) = get(
        make_test_router(),
        "/runs/result/00000000-0000-0000-0000-eeeeeeeeeeee",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(
        body.contains("not found") || body.contains("Error"),
        "must show error: {body}"
    );
}

// ── Security headers are present on all pages ─────────────────────────────────

#[tokio::test]
async fn security_headers_present_on_scan_page() {
    let (_, headers, _) = get(make_test_router(), "/scan").await;
    let frame_opts = headers
        .get("x-frame-options")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert_eq!(frame_opts, "DENY", "X-Frame-Options must be DENY");

    let cto = headers
        .get("x-content-type-options")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert_eq!(cto, "nosniff", "X-Content-Type-Options must be nosniff");
}

// ── /api/runs/{run_id}/pdf-status — no PDF on disk ───────────────────────────

#[tokio::test]
async fn pdf_status_no_pdf_returns_not_ready() {
    let (status, _, body) = get(
        make_test_router(),
        "/api/runs/00000000-0000-0000-0000-dddddddddddd/pdf-status",
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
    assert_eq!(v["ready"], false, "no-PDF run must return ready=false");
}

// ── download bundle — unknown run ─────────────────────────────────────────────

#[tokio::test]
async fn download_bundle_unknown_run_returns_404() {
    let (status, _, _) = get(
        make_test_router(),
        "/api/runs/00000000-0000-0000-0000-ffffffffff01/bundle",
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── /api/confluence/post smoke test ──────────────────────────────────────────

#[tokio::test]
async fn api_confluence_post_no_config_returns_error() {
    let (status, _body) = post_json(
        make_test_router(),
        "/api/confluence/post",
        r#"{"run_id":"some-run-id"}"#,
    )
    .await;
    // With no Confluence config, should return 4xx — definitely not 5xx
    assert!(
        status.as_u16() < 500,
        "confluence post without config must not 5xx, got {status}"
    );
}

// ── /api/confluence/test smoke test ──────────────────────────────────────────

#[tokio::test]
async fn api_confluence_test_no_config_returns_error() {
    let (status, _) = post_json(make_test_router(), "/api/confluence/test", r#"{}"#).await;
    assert!(
        status.as_u16() < 500,
        "confluence test without config must not 5xx, got {status}"
    );
}

// ── Helper function: URL-encode a string for form bodies ─────────────────────

fn urlencoding_encode(s: &str) -> String {
    s.bytes()
        .flat_map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                vec![b as char]
            }
            b' ' => vec!['+'],
            _ => format!("%{b:02X}").chars().collect(),
        })
        .collect()
}