reptr 0.8.0

Local-first pentest report generator: Markdown findings -> HTML/JSON/DOCX/PDF.
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
use std::fs;
use std::path::PathBuf;

use reptr::commands::{add, build, library as library_cmd, new, retest, stats};
use reptr::library;
use reptr::model::{validate_engagement, Engagement, Severity};
use reptr::parse::{load_engagement_config, load_findings};

fn fixture_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/sample-engagement")
}

fn build_engagement(root: &std::path::Path) -> Engagement {
    let (cfg, client) = load_engagement_config(root).expect("config");
    let findings = load_findings(&root.join("findings")).expect("findings");
    let mut eng = Engagement {
        meta: cfg.engagement,
        client,
        findings,
        appendices: vec![],
        output: cfg.output,
        template: cfg.template,
        severity_thresholds: cfg.severity_thresholds,
        library: cfg.library,
    };
    eng.sort_findings();
    eng
}

#[test]
fn parses_sample_engagement() {
    let eng = build_engagement(&fixture_root());
    assert_eq!(eng.findings.len(), 2);
    // sorted highest-severity first
    assert_eq!(eng.findings[0].severity, Severity::Critical);
    assert_eq!(eng.findings[0].id, "F-001");
    assert_eq!(eng.findings[1].id, "F-002");
    assert!(eng.findings[0].body_html.contains("<h2>"));
    assert!(eng.findings[0].body_html.contains("Description"));
}

#[test]
fn sample_engagement_validates_clean() {
    let eng = build_engagement(&fixture_root());
    let errors = validate_engagement(&eng);
    assert!(errors.is_empty(), "expected no errors, got: {errors:?}");
}

#[test]
fn build_renders_html_and_json_into_tempdir() {
    // Copy fixture into a tempdir so we don't pollute the repo with output/.
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();

    build::run(dst).expect("build succeeds");

    let html = dst.join("output/acme-webapp-2026.html");
    let json = dst.join("output/acme-webapp-2026.json");
    assert!(html.exists(), "html not produced");
    assert!(json.exists(), "json not produced");

    let html_body = fs::read_to_string(&html).unwrap();
    assert!(html_body.contains("Acme Web Application Assessment"));
    assert!(html_body.contains("SQL Injection"));
    assert!(html_body.contains("sev-critical"));

    let json_body = fs::read_to_string(&json).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json_body).unwrap();
    assert_eq!(parsed["meta"]["slug"], "acme-webapp-2026");
    assert_eq!(parsed["findings"][0]["id"], "F-001");
}

#[test]
fn build_renders_pdf_when_typst_available() {
    // Skip if typst isn't installed — keeps CI / first-time devs unblocked.
    if std::process::Command::new("typst")
        .arg("--version")
        .output()
        .map(|o| !o.status.success())
        .unwrap_or(true)
    {
        eprintln!("skipping: typst CLI not on PATH");
        return;
    }

    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();

    let cfg_path = dst.join("reptr.toml");
    let cfg = fs::read_to_string(&cfg_path).unwrap();
    let cfg = cfg.replace(
        r#"formats = ["html", "json"]"#,
        r#"formats = ["html", "json", "pdf"]"#,
    );
    fs::write(&cfg_path, cfg).unwrap();

    build::run(dst).expect("build succeeds");

    let pdf_path = dst.join("output/acme-webapp-2026.pdf");
    assert!(pdf_path.exists(), "pdf not produced");
    let bytes = fs::read(&pdf_path).unwrap();
    assert!(bytes.starts_with(b"%PDF-"), "pdf magic missing");
    assert!(
        bytes.len() > 1000,
        "pdf suspiciously small: {} bytes",
        bytes.len()
    );
}

#[test]
fn build_renders_docx_when_format_enabled() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();

    // Add docx to the formats list.
    let cfg_path = dst.join("reptr.toml");
    let cfg = fs::read_to_string(&cfg_path).unwrap();
    let cfg = cfg.replace(
        r#"formats = ["html", "json"]"#,
        r#"formats = ["html", "json", "docx"]"#,
    );
    fs::write(&cfg_path, cfg).unwrap();

    build::run(dst).expect("build succeeds");

    let docx_path = dst.join("output/acme-webapp-2026.docx");
    assert!(docx_path.exists(), "docx not produced");
    let bytes = fs::read(&docx_path).unwrap();
    assert!(
        bytes.len() > 1000,
        "docx suspiciously small: {} bytes",
        bytes.len()
    );
    // Word .docx files are zip archives; verify the local-file-header magic.
    assert_eq!(&bytes[..2], b"PK", "docx is not a valid zip archive");
}

#[test]
fn finding_image_refs_are_parsed_and_resolved() {
    let eng = build_engagement(&fixture_root());
    let sqli = eng
        .findings
        .iter()
        .find(|f| f.id == "F-001")
        .expect("sqli finding");
    assert_eq!(sqli.images.len(), 1, "expected exactly one image ref");
    let img = &sqli.images[0];
    assert_eq!(img.markdown_src, "../assets/screenshots/sqli-bypass.png");
    let resolved = img.resolved_path.as_ref().expect("resolved path");
    assert!(resolved.exists(), "{} should exist", resolved.display());
    assert!(resolved.ends_with("assets/screenshots/sqli-bypass.png"));
}

#[test]
fn docx_embeds_referenced_image() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    let cfg_path = dst.join("reptr.toml");
    let cfg = fs::read_to_string(&cfg_path).unwrap();
    fs::write(
        &cfg_path,
        cfg.replace(
            r#"formats = ["html", "json"]"#,
            r#"formats = ["html", "json", "docx"]"#,
        ),
    )
    .unwrap();

    build::run(dst).expect("build succeeds");

    let docx = dst.join("output/acme-webapp-2026.docx");
    let bytes = fs::read(&docx).unwrap();
    // OOXML places embedded images under word/media/. Searching the raw zip
    // bytes is enough — we don't need to unzip in the test.
    assert!(
        bytes.windows(11).any(|w| w == b"word/media/"),
        "expected an entry under word/media/ inside the DOCX zip"
    );
}

#[test]
fn pdf_typst_source_references_image() {
    if std::process::Command::new("typst")
        .arg("--version")
        .output()
        .map(|o| !o.status.success())
        .unwrap_or(true)
    {
        eprintln!("skipping: typst CLI not on PATH");
        return;
    }

    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    let cfg_path = dst.join("reptr.toml");
    let cfg = fs::read_to_string(&cfg_path).unwrap();
    fs::write(
        &cfg_path,
        cfg.replace(
            r#"formats = ["html", "json"]"#,
            r#"formats = ["html", "json", "pdf"]"#,
        ),
    )
    .unwrap();

    build::run(dst).expect("build succeeds");

    let typ_src = fs::read_to_string(dst.join("output/acme-webapp-2026.typ")).unwrap();
    assert!(
        typ_src.contains("#image("),
        "expected typst source to embed the screenshot. got:\n{typ_src}"
    );
    let pdf = dst.join("output/acme-webapp-2026.pdf");
    let bytes = fs::read(&pdf).unwrap();
    assert!(bytes.starts_with(b"%PDF-"));
    assert!(bytes.len() > 1000);
}

#[test]
fn custom_html_template_overrides_default() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();

    // Write a minimal custom template with a sentinel marker we can grep for.
    let custom = r#"<!DOCTYPE html>
<html><head><title>{{ engagement.meta.name }}</title></head>
<body data-reptr-test="custom-template-v1">
<h1>{{ engagement.meta.name }}</h1>
<p>{{ engagement.findings | length }} findings</p>
<ul>
{% for f in engagement.findings %}
  <li data-id="{{ f.id }}" data-sev="{{ f.severity }}">{{ f.title }}</li>
{% endfor %}
</ul>
</body></html>
"#;
    fs::create_dir_all(dst.join("templates")).unwrap();
    fs::write(dst.join("templates/report.html"), custom).unwrap();

    // Point [template].html at it.
    let cfg_path = dst.join("reptr.toml");
    let mut cfg = fs::read_to_string(&cfg_path).unwrap();
    cfg.push_str("\n[template]\nhtml = \"templates/report.html\"\n");
    fs::write(&cfg_path, cfg).unwrap();

    build::run(dst).expect("build succeeds");

    let html = fs::read_to_string(dst.join("output/acme-webapp-2026.html")).unwrap();
    assert!(
        html.contains(r#"data-reptr-test="custom-template-v1""#),
        "expected sentinel from custom template, got:\n{html}"
    );
    assert!(html.contains("2 findings"));
    assert!(html.contains(r#"data-sev="critical""#));
    assert!(
        !html.contains("Findings Overview"),
        "default template should not have been used"
    );
}

#[test]
fn missing_custom_template_errors_clearly() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();

    let cfg_path = dst.join("reptr.toml");
    let mut cfg = fs::read_to_string(&cfg_path).unwrap();
    cfg.push_str("\n[template]\nhtml = \"templates/does-not-exist.html\"\n");
    fs::write(&cfg_path, cfg).unwrap();

    let err = build::run(dst).expect_err("expected build to fail");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("does-not-exist.html") && msg.to_lowercase().contains("reading"),
        "error should name the missing file. got: {msg}"
    );
}

#[test]
fn stats_aggregates_across_engagements() {
    let tmp = tempfile::tempdir().unwrap();
    let parent = tmp.path();

    // Two engagement dirs cloned from the fixture, with one extra finding in
    // the second so totals differ between them.
    copy_dir(&fixture_root(), &parent.join("eng-a")).unwrap();
    copy_dir(&fixture_root(), &parent.join("eng-b")).unwrap();

    // Make eng-b's slug unique so the rows are distinguishable.
    let b_cfg = parent.join("eng-b/reptr.toml");
    let cfg = fs::read_to_string(&b_cfg).unwrap();
    fs::write(
        &b_cfg,
        cfg.replace(
            r#"slug = "acme-webapp-2026""#,
            r#"slug = "contoso-mobile-2026""#,
        ),
    )
    .unwrap();

    // Add an extra HIGH finding to eng-b.
    fs::write(
        parent.join("eng-b/findings/003-extra.md"),
        "---\nid: F-003\ntitle: Extra finding for eng-b\nseverity: high\nstatus: resolved\n---\n\n## Description\n\nbody.\n",
    )
    .unwrap();

    let (rows, totals) = stats::collect_stats(parent).expect("stats ok");
    assert_eq!(rows.len(), 2, "expected 2 engagements");
    let slugs: Vec<&str> = rows.iter().map(|r| r.slug.as_str()).collect();
    assert!(slugs.contains(&"acme-webapp-2026"));
    assert!(slugs.contains(&"contoso-mobile-2026"));

    // Each fixture has 1 critical + 1 low; eng-b adds 1 high (resolved).
    assert_eq!(totals.counts.critical, 2);
    assert_eq!(totals.counts.high, 1);
    assert_eq!(totals.counts.low, 2);
    assert_eq!(totals.total, 5);
    assert_eq!(totals.resolved, 1);
    assert_eq!(totals.open, 4);

    // JSON serializes cleanly.
    let json = serde_json::to_value(&rows).unwrap();
    assert!(json[0].get("counts").is_some());
}

#[test]
fn stats_works_inside_a_single_engagement_dir() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();

    let (rows, totals) = stats::collect_stats(dst).expect("stats ok");
    assert_eq!(rows.len(), 1);
    assert_eq!(totals.engagements, 1);
    assert_eq!(totals.total, 2);
    assert_eq!(totals.counts.critical, 1);
    assert_eq!(totals.counts.low, 1);
}

#[test]
fn stats_errors_when_no_engagement_found() {
    let tmp = tempfile::tempdir().unwrap();
    let err = stats::collect_stats(tmp.path()).expect_err("should fail on empty dir");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("no engagements found"),
        "expected helpful error, got: {msg}"
    );
}

fn library_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/findings-library")
}

#[test]
fn library_lists_every_template() {
    let templates = library::list_templates(&library_root()).unwrap();
    let names: Vec<_> = templates.iter().map(|t| t.name.as_str()).collect();
    assert!(names.contains(&"web/xss-stored"));
    assert!(names.contains(&"web/sql-injection"));
    assert!(names.contains(&"api/idor"));
    // Sorted alphabetically
    let mut sorted = names.clone();
    sorted.sort();
    assert_eq!(names, sorted);

    let xss = templates
        .iter()
        .find(|t| t.name == "web/xss-stored")
        .unwrap();
    assert_eq!(xss.title, "Stored Cross-Site Scripting");
    assert_eq!(xss.severity, "high");
}

#[test]
fn library_load_missing_template_errors_clearly() {
    let err = library::load_template(&library_root(), "does-not-exist").expect_err("should fail");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("does-not-exist") && msg.contains("not found"),
        "expected helpful error, got: {msg}"
    );
}

#[test]
fn add_from_library_imports_and_assigns_id() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();

    // Point [library].path at the test fixture library (absolute path so it
    // works regardless of the temp dir's location).
    let mut cfg = fs::read_to_string(dst.join("reptr.toml")).unwrap();
    cfg.push_str(&format!(
        "\n[library]\npath = \"{}\"\n",
        library_root().display()
    ));
    fs::write(dst.join("reptr.toml"), cfg).unwrap();

    // Import with no title override — should use the template's title.
    add::run(
        dst,
        None,
        reptr::model::Severity::Medium,
        Some("web/xss-stored"),
    )
    .expect("add --from succeeds");

    // The fixture already has 002 (high-severity-ish finding); next id is F-003.
    let imported_path = dst.join("findings/003-stored-cross-site-scripting.md");
    assert!(imported_path.exists(), "import file not created");

    let body = fs::read_to_string(&imported_path).unwrap();
    assert!(body.contains("id: F-003"));
    assert!(body.contains("title: Stored Cross-Site Scripting"));
    assert!(
        body.contains("severity: high"),
        "template severity must survive import"
    );
    // Body markdown should come through intact.
    assert!(body.contains("Apply context-aware output encoding"));
}

#[test]
fn add_from_library_with_title_override() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    let mut cfg = fs::read_to_string(dst.join("reptr.toml")).unwrap();
    cfg.push_str(&format!(
        "\n[library]\npath = \"{}\"\n",
        library_root().display()
    ));
    fs::write(dst.join("reptr.toml"), cfg).unwrap();

    add::run(
        dst,
        Some("XSS in Profile Bio"),
        reptr::model::Severity::Medium,
        Some("web/xss-stored"),
    )
    .expect("add --from with title succeeds");

    let body = fs::read_to_string(dst.join("findings/003-xss-in-profile-bio.md")).unwrap();
    assert!(body.contains("title: XSS in Profile Bio"));
    // Template severity preserved
    assert!(body.contains("severity: high"));
}

#[test]
fn imported_finding_passes_validation_and_builds() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    let mut cfg = fs::read_to_string(dst.join("reptr.toml")).unwrap();
    cfg.push_str(&format!(
        "\n[library]\npath = \"{}\"\n",
        library_root().display()
    ));
    fs::write(dst.join("reptr.toml"), cfg).unwrap();

    add::run(
        dst,
        None,
        reptr::model::Severity::Medium,
        Some("web/sql-injection"),
    )
    .unwrap();
    add::run(dst, None, reptr::model::Severity::Medium, Some("api/idor")).unwrap();

    // Should build cleanly with the imported findings present.
    build::run(dst).expect("build with imported findings succeeds");

    let html = fs::read_to_string(dst.join("output/acme-webapp-2026.html")).unwrap();
    assert!(html.contains("Insecure Direct Object Reference"));
    assert!(html.contains("SQL Injection"));
}

#[test]
fn library_list_runs_without_panicking() {
    // Smoke-test the library list subcommand against the fixture library.
    // We can't easily capture stdout here, but ensuring it returns Ok is enough.
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    let mut cfg = fs::read_to_string(dst.join("reptr.toml")).unwrap();
    cfg.push_str(&format!(
        "\n[library]\npath = \"{}\"\n",
        library_root().display()
    ));
    fs::write(dst.join("reptr.toml"), cfg).unwrap();

    library_cmd::list(dst).expect("library list ok");
}

#[test]
fn detects_duplicate_finding_ids() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();

    // Duplicate F-001 by copying it under a new filename.
    let extra = dst.join("findings/003-duplicate.md");
    let raw = fs::read_to_string(dst.join("findings/001-sql-injection-in-login-form.md")).unwrap();
    fs::write(&extra, raw).unwrap();

    let err = build::run(dst).expect_err("expected validation failure");
    let msg = format!("{err:#}");
    assert!(msg.to_lowercase().contains("validation"), "msg: {msg}");
}

#[test]
fn new_command_scaffolds_directory() {
    let tmp = tempfile::tempdir().unwrap();
    let cwd_guard = ChangeDir::to(tmp.path());
    new::run("scratch-engagement").expect("new succeeds");
    drop(cwd_guard);

    let root = tmp.path().join("scratch-engagement");
    assert!(root.join("reptr.toml").exists());
    assert!(root.join("client.toml").exists());
    assert!(root.join("findings/001-example-finding.md").exists());
    assert!(root.join("templates").is_dir());
    assert!(root.join("assets/screenshots").is_dir());
    assert!(root.join("output").is_dir());
}

// --- retest tests --------------------------------------------------------

/// Helper: copy fixture to a tempdir and return the path.
fn setup_engagement() -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path().to_path_buf();
    copy_dir(&fixture_root(), &dst).unwrap();
    (tmp, dst)
}

/// Helper: set a finding's `status:` field in its frontmatter via plain string
/// replacement. The fixture files use a single-line `status: <value>` so this
/// is reliable without a full TOML parser.
fn set_finding_status(path: &std::path::Path, new_status: &str) {
    let content = fs::read_to_string(path).unwrap();
    let updated = regex::Regex::new(r"(?m)^status: \w+$")
        .unwrap()
        .replace(&content, format!("status: {new_status}"))
        .to_string();
    fs::write(path, updated).unwrap();
}

/// Helper: change a finding's `severity:` field.
fn set_finding_severity(path: &std::path::Path, new_severity: &str) {
    let content = fs::read_to_string(path).unwrap();
    let updated = regex::Regex::new(r"(?m)^severity: \w+$")
        .unwrap()
        .replace(&content, format!("severity: {new_severity}"))
        .to_string();
    fs::write(path, updated).unwrap();
}

/// Helper: read `output/<slug>-retest.json` and return it as a Value.
fn read_retest_json(dst: &std::path::Path, slug: &str) -> serde_json::Value {
    let path = dst.join(format!("output/{slug}-retest.json"));
    let data =
        fs::read_to_string(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
    serde_json::from_str(&data).unwrap()
}

/// Helper: read `output/<slug>-retest.html` as a string.
fn read_retest_html(dst: &std::path::Path, slug: &str) -> String {
    let path = dst.join(format!("output/{slug}-retest.html"));
    fs::read_to_string(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()))
}

const SLUG: &str = "acme-webapp-2026";

#[test]
fn retest_first_run_establishes_baseline_no_retest_files() {
    let (_tmp, dst) = setup_engagement();

    // No prior JSON at all — this should behave like a plain build and return Ok.
    assert!(
        !dst.join(format!("output/{SLUG}.json")).exists(),
        "precondition: no prior JSON"
    );

    retest::run(&dst).expect("first retest run succeeds");

    // Regular build outputs are created.
    assert!(
        dst.join(format!("output/{SLUG}.html")).exists(),
        "baseline HTML not created"
    );
    assert!(
        dst.join(format!("output/{SLUG}.json")).exists(),
        "baseline JSON not created"
    );

    // Retest-specific delta files should NOT exist on a first (baseline) run.
    assert!(
        !dst.join(format!("output/{SLUG}-retest.json")).exists(),
        "retest JSON should not exist on first run"
    );
    assert!(
        !dst.join(format!("output/{SLUG}-retest.html")).exists(),
        "retest HTML should not exist on first run"
    );
}

#[test]
fn retest_no_changes_all_unchanged() {
    let (_tmp, dst) = setup_engagement();

    // Baseline.
    retest::run(&dst).expect("baseline ok");

    // Diff run — nothing changed.
    retest::run(&dst).expect("second retest ok");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(
        json["unchanged_count"], 2,
        "both fixture findings should be unchanged"
    );
    assert_eq!(json["new_count"], 0);
    assert_eq!(json["resolved_count"], 0);
    assert_eq!(json["regressed_count"], 0);
    assert_eq!(json["changed_count"], 0);
    assert_eq!(json["removed_count"], 0);
}

#[test]
fn retest_detects_resolved_finding() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");

    // Resolve F-002 (the Low finding).
    let f002 = dst.join("findings/002-missing-security-headers.md");
    set_finding_status(&f002, "resolved");

    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(json["resolved_count"], 1, "expected one resolved finding");
    assert_eq!(json["unchanged_count"], 1);
    assert_eq!(json["regressed_count"], 0);

    let deltas = json["deltas"].as_array().unwrap();
    let resolved_delta = deltas
        .iter()
        .find(|d| d["id"] == "F-002")
        .expect("F-002 delta missing");
    assert_eq!(resolved_delta["change_type"], "resolved");
    assert_eq!(resolved_delta["label"], "open → resolved");
}

#[test]
fn retest_detects_regressed_finding() {
    let (_tmp, dst) = setup_engagement();

    // Make F-001 resolved in the baseline.
    let f001 = dst.join("findings/001-sql-injection-in-login-form.md");
    set_finding_status(&f001, "resolved");
    retest::run(&dst).expect("baseline ok");

    // Regress it back to open.
    set_finding_status(&f001, "open");
    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(json["regressed_count"], 1, "expected one regressed finding");
    assert_eq!(json["resolved_count"], 0);

    let deltas = json["deltas"].as_array().unwrap();
    let d = deltas.iter().find(|d| d["id"] == "F-001").unwrap();
    assert_eq!(d["change_type"], "regressed");
    assert_eq!(d["label"], "resolved → open");
}

#[test]
fn retest_detects_new_finding() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");

    // Add a third finding.
    fs::write(
        dst.join("findings/003-csrf-missing-token.md"),
        "---\nid: F-003\ntitle: CSRF Missing Token\nseverity: high\nstatus: open\n---\n\n## Description\n\nCSRF token absent.\n",
    )
    .unwrap();

    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(json["new_count"], 1, "expected one new finding");
    assert_eq!(json["unchanged_count"], 2);

    let deltas = json["deltas"].as_array().unwrap();
    let new_delta = deltas.iter().find(|d| d["id"] == "F-003").unwrap();
    assert_eq!(new_delta["change_type"], "new");
    assert_eq!(new_delta["severity"], "high");
    assert_eq!(new_delta["label"], "New");
}

#[test]
fn retest_detects_removed_finding() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");

    // Remove F-002.
    fs::remove_file(dst.join("findings/002-missing-security-headers.md")).unwrap();

    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(json["removed_count"], 1, "expected one removed finding");
    assert_eq!(json["unchanged_count"], 1);

    let deltas = json["deltas"].as_array().unwrap();
    let removed = deltas.iter().find(|d| d["id"] == "F-002").unwrap();
    assert_eq!(removed["change_type"], "removed");
    assert_eq!(removed["label"], "Removed");
}

#[test]
fn retest_detects_severity_downgrade() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");

    // Downgrade F-001 from critical to high.
    let f001 = dst.join("findings/001-sql-injection-in-login-form.md");
    set_finding_severity(&f001, "high");

    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(json["changed_count"], 1, "expected one changed finding");
    assert_eq!(json["resolved_count"], 0);

    let deltas = json["deltas"].as_array().unwrap();
    let d = deltas.iter().find(|d| d["id"] == "F-001").unwrap();
    assert_eq!(d["change_type"], "changed");
    assert!(
        d["label"].as_str().unwrap().contains("critical → high"),
        "label should show severity change: {}",
        d["label"]
    );
}

#[test]
fn retest_detects_multiple_simultaneous_changes() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");

    // Resolve F-002 + add a new F-003.
    set_finding_status(
        &dst.join("findings/002-missing-security-headers.md"),
        "resolved",
    );
    fs::write(
        dst.join("findings/003-new.md"),
        "---\nid: F-003\ntitle: New Finding\nseverity: medium\nstatus: open\n---\n\nbody.\n",
    )
    .unwrap();

    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(json["new_count"], 1);
    assert_eq!(json["resolved_count"], 1);
    assert_eq!(json["unchanged_count"], 1);
    assert_eq!(json["regressed_count"], 0);
    assert_eq!(json["removed_count"], 0);
}

#[test]
fn retest_accepted_status_to_resolved_counts_as_resolved() {
    let (_tmp, dst) = setup_engagement();

    // Mark F-002 as accepted in the baseline.
    set_finding_status(
        &dst.join("findings/002-missing-security-headers.md"),
        "accepted",
    );
    retest::run(&dst).expect("baseline ok");

    // Then resolve it.
    set_finding_status(
        &dst.join("findings/002-missing-security-headers.md"),
        "resolved",
    );
    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(
        json["resolved_count"], 1,
        "accepted → resolved should count as resolved"
    );
    assert_eq!(json["changed_count"], 0);
}

#[test]
fn retest_open_to_false_positive_counts_as_changed_not_resolved() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");

    set_finding_status(
        &dst.join("findings/002-missing-security-headers.md"),
        "false_positive",
    );
    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(json["changed_count"], 1);
    assert_eq!(json["resolved_count"], 0);

    let deltas = json["deltas"].as_array().unwrap();
    let d = deltas.iter().find(|d| d["id"] == "F-002").unwrap();
    assert_eq!(d["change_type"], "changed");
    assert!(d["label"].as_str().unwrap().contains("false_positive"));
}

#[test]
fn retest_html_output_is_written_and_well_formed() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");
    retest::run(&dst).expect("diff run ok");

    let html = read_retest_html(&dst, SLUG);
    assert!(html.trim().starts_with("<!doctype html>"));
    assert!(html.contains("</html>"));
    assert!(html.contains("Acme Web Application Assessment"));
}

#[test]
fn retest_html_unchanged_findings_get_tag_unchanged_class() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");
    retest::run(&dst).expect("diff run ok");

    let html = read_retest_html(&dst, SLUG);
    assert!(
        html.contains("tag-unchanged"),
        "unchanged findings should carry tag-unchanged CSS class"
    );
}

#[test]
fn retest_html_resolved_finding_gets_correct_classes() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");

    set_finding_status(
        &dst.join("findings/001-sql-injection-in-login-form.md"),
        "resolved",
    );
    retest::run(&dst).expect("diff run ok");

    let html = read_retest_html(&dst, SLUG);
    assert!(
        html.contains("tag-resolved"),
        "resolved badge class missing"
    );
    assert!(
        html.contains("sev-critical"),
        "critical severity badge missing"
    );
}

#[test]
fn retest_html_regressed_finding_gets_regressed_class() {
    let (_tmp, dst) = setup_engagement();

    // Baseline with F-001 resolved.
    set_finding_status(
        &dst.join("findings/001-sql-injection-in-login-form.md"),
        "resolved",
    );
    retest::run(&dst).expect("baseline ok");

    // Regress it.
    set_finding_status(
        &dst.join("findings/001-sql-injection-in-login-form.md"),
        "open",
    );
    retest::run(&dst).expect("diff run ok");

    let html = read_retest_html(&dst, SLUG);
    assert!(
        html.contains("tag-regressed"),
        "regressed badge class missing"
    );
}

#[test]
fn retest_html_new_finding_gets_tag_new_class() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");

    fs::write(
        dst.join("findings/003-new.md"),
        "---\nid: F-003\ntitle: New XSS\nseverity: medium\nstatus: open\n---\n\nbody.\n",
    )
    .unwrap();
    retest::run(&dst).expect("diff run ok");

    let html = read_retest_html(&dst, SLUG);
    assert!(html.contains("tag-new"), "new badge class missing");
    assert!(
        html.contains("New XSS"),
        "new finding title missing from HTML"
    );
}

#[test]
fn retest_json_delta_array_contains_all_findings() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");
    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    let deltas = json["deltas"].as_array().unwrap();
    // Fixture has 2 findings; both should appear in the delta array.
    assert_eq!(
        deltas.len(),
        2,
        "delta array should contain all 2 fixture findings"
    );
}

#[test]
fn retest_json_delta_has_required_fields() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");
    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    let deltas = json["deltas"].as_array().unwrap();
    for d in deltas {
        assert!(d["id"].is_string(), "delta missing `id` field");
        assert!(d["title"].is_string(), "delta missing `title` field");
        assert!(d["severity"].is_string(), "delta missing `severity` field");
        assert!(
            d["change_type"].is_string(),
            "delta missing `change_type` field"
        );
        assert!(d["label"].is_string(), "delta missing `label` field");
    }
}

#[test]
fn retest_json_top_level_has_all_count_fields() {
    let (_tmp, dst) = setup_engagement();
    retest::run(&dst).expect("baseline ok");
    retest::run(&dst).expect("diff run ok");

    let json = read_retest_json(&dst, SLUG);
    for field in &[
        "new_count",
        "removed_count",
        "resolved_count",
        "regressed_count",
        "changed_count",
        "unchanged_count",
        "engagement_name",
        "generated_at",
        "deltas",
    ] {
        assert!(
            !json[field].is_null(),
            "retest JSON missing field `{field}`"
        );
    }
}

#[test]
fn retest_reruns_correctly_accumulate_delta() {
    // Three runs: baseline → resolve → regress → verify each step.
    let (_tmp, dst) = setup_engagement();
    let f002 = dst.join("findings/002-missing-security-headers.md");

    // Run 1: baseline.
    retest::run(&dst).expect("baseline ok");

    // Run 2: resolve F-002.
    set_finding_status(&f002, "resolved");
    retest::run(&dst).expect("second run ok");
    let json2 = read_retest_json(&dst, SLUG);
    assert_eq!(json2["resolved_count"], 1, "run2: F-002 should be resolved");
    assert_eq!(json2["regressed_count"], 0);

    // Run 3: regress F-002 back to open.
    set_finding_status(&f002, "open");
    retest::run(&dst).expect("third run ok");
    let json3 = read_retest_json(&dst, SLUG);
    assert_eq!(
        json3["regressed_count"], 1,
        "run3: F-002 should now be regressed (resolved → open)"
    );
    assert_eq!(json3["resolved_count"], 0);
}

#[test]
fn retest_does_not_fail_on_empty_findings_dir() {
    let (_tmp, dst) = setup_engagement();

    // Baseline with normal findings.
    retest::run(&dst).expect("baseline ok");

    // Remove ALL findings.
    fs::remove_file(dst.join("findings/001-sql-injection-in-login-form.md")).unwrap();
    fs::remove_file(dst.join("findings/002-missing-security-headers.md")).unwrap();

    retest::run(&dst).expect("retest with empty findings dir should not panic");

    let json = read_retest_json(&dst, SLUG);
    assert_eq!(json["removed_count"], 2);
    assert_eq!(json["new_count"], 0);
    assert_eq!(json["unchanged_count"], 0);
}

// --- CVSS integration tests ----------------------------------------------

// Verified computed scores:
//   CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H  → 9.8  (fixture F-001)
//   CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N  → 7.5

const CVSS_VECTOR_9_8: &str = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H";
const CVSS_VECTOR_7_5: &str = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N";

/// Write a minimal finding to `findings/003-<slug>.md` with the given CVSS fields.
fn write_cvss_finding(
    dst: &std::path::Path,
    id: &str,
    title: &str,
    cvss: Option<&str>,
    cvss_vector: Option<&str>,
) {
    let mut fm = format!("---\nid: {id}\ntitle: {title}\nseverity: medium\nstatus: open\n");
    if let Some(s) = cvss {
        fm.push_str(&format!("cvss: \"{s}\"\n"));
    }
    if let Some(v) = cvss_vector {
        fm.push_str(&format!("cvss_vector: \"{v}\"\n"));
    }
    fm.push_str("---\n\n## Description\n\nbody.\n");
    let slug: String = title
        .chars()
        .map(|c| {
            if c.is_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect();
    fs::write(dst.join(format!("findings/003-{slug}.md")), fm).unwrap();
}

/// Read `output/<slug>.json` and return the finding with the given `id`.
fn get_finding_from_json(dst: &std::path::Path, id: &str) -> serde_json::Value {
    let body = fs::read_to_string(dst.join(format!("output/{SLUG}.json"))).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
    parsed["findings"]
        .as_array()
        .unwrap()
        .iter()
        .find(|f| f["id"] == id)
        .unwrap_or_else(|| panic!("finding {id} not found in JSON output"))
        .clone()
}

#[test]
fn cvss_vector_only_auto_derives_score_in_json() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(&dst, "F-003", "SSRF", None, Some(CVSS_VECTOR_7_5));

    build::run(&dst).expect("build with vector-only finding should succeed");

    let f003 = get_finding_from_json(&dst, "F-003");
    assert_eq!(
        f003["cvss"].as_str().unwrap_or(""),
        "7.5",
        "score should be auto-derived from vector. got: {}",
        f003["cvss"]
    );
}

#[test]
fn cvss_derived_score_is_formatted_to_one_decimal_place() {
    // Verifies the format!("{:.1}", ...) rounding, not just the numeric value.
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(&dst, "F-003", "SSRF", None, Some(CVSS_VECTOR_7_5));

    build::run(&dst).expect("build succeeds");

    let f003 = get_finding_from_json(&dst, "F-003");
    let score = f003["cvss"].as_str().unwrap();
    assert_eq!(
        score, "7.5",
        "derived score must be exactly '7.5', not '7.50' or '7'"
    );
}

#[test]
fn cvss_derived_score_appears_in_html_output() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(&dst, "F-003", "SSRF Finding", None, Some(CVSS_VECTOR_7_5));

    build::run(&dst).expect("build succeeds");

    let html = fs::read_to_string(dst.join(format!("output/{SLUG}.html"))).unwrap();
    assert!(
        html.contains("7.5"),
        "derived CVSS score should appear somewhere in HTML output"
    );
}

#[test]
fn cvss_vector_field_is_preserved_in_json_output() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(&dst, "F-003", "SSRF", Some("7.5"), Some(CVSS_VECTOR_7_5));

    build::run(&dst).expect("build succeeds");

    let f003 = get_finding_from_json(&dst, "F-003");
    assert_eq!(
        f003["cvss_vector"].as_str().unwrap_or(""),
        CVSS_VECTOR_7_5,
        "cvss_vector should be round-tripped into JSON output"
    );
}

#[test]
fn cvss_absent_score_absent_from_json() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(&dst, "F-003", "Info Disclosure", None, None);

    build::run(&dst).expect("build without any CVSS fields should succeed");

    let f003 = get_finding_from_json(&dst, "F-003");
    assert!(
        f003["cvss"].is_null(),
        "cvss key should be absent from JSON when no score/vector provided"
    );
    assert!(
        f003["cvss_vector"].is_null(),
        "cvss_vector key should be absent from JSON when not provided"
    );
}

#[test]
fn cvss_score_zero_is_valid() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(&dst, "F-003", "Info Only", Some("0.0"), None);

    build::run(&dst).expect("CVSS score 0.0 is the minimum valid value and should pass");
}

#[test]
fn cvss_score_ten_is_valid() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(&dst, "F-003", "Max Score", Some("10.0"), None);

    build::run(&dst).expect("CVSS score 10.0 is the maximum valid value and should pass");
}

#[test]
fn cvss_matching_score_and_vector_passes_build() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(
        &dst,
        "F-003",
        "SSRF High",
        Some("7.5"),
        Some(CVSS_VECTOR_7_5),
    );

    build::run(&dst).expect("matching explicit score and vector should pass validation");
}

#[test]
fn cvss_invalid_vector_fails_build() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(
        &dst,
        "F-003",
        "Bad Vector",
        None,
        Some("CVSS:3.1/INVALID/VECTOR"),
    );

    let err = build::run(&dst).expect_err("invalid CVSS vector should cause build failure");
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "error should mention validation. got: {msg}"
    );
}

#[test]
fn cvss_completely_malformed_vector_fails_build() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(
        &dst,
        "F-003",
        "Malformed Vector",
        None,
        Some("not-a-cvss-vector"),
    );

    let err = build::run(&dst).expect_err("completely malformed vector should fail");
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "error should mention validation. got: {msg}"
    );
}

#[test]
fn cvss_score_mismatch_fails_build() {
    let (_tmp, dst) = setup_engagement();
    // Score says 5.0 but the vector computes 9.8.
    write_cvss_finding(
        &dst,
        "F-003",
        "Mismatch Finding",
        Some("5.0"),
        Some(CVSS_VECTOR_9_8),
    );

    let err = build::run(&dst).expect_err("mismatched score/vector should fail validation");
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "error should mention validation. got: {msg}"
    );
}

#[test]
fn cvss_score_out_of_range_fails_build() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(&dst, "F-003", "Bad Score Range", Some("15.0"), None);

    let err = build::run(&dst).expect_err("out-of-range CVSS score should fail validation");
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "error should mention validation. got: {msg}"
    );
}

#[test]
fn cvss_negative_score_fails_build() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(&dst, "F-003", "Negative Score", Some("-1.0"), None);

    let err = build::run(&dst).expect_err("negative CVSS score should fail validation");
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "error should mention validation. got: {msg}"
    );
}

#[test]
fn cvss_non_numeric_score_fails_build() {
    let (_tmp, dst) = setup_engagement();
    write_cvss_finding(
        &dst,
        "F-003",
        "Non Numeric Score",
        Some("not-a-number"),
        None,
    );

    let err = build::run(&dst).expect_err("non-numeric CVSS score should fail validation");
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "error should mention validation. got: {msg}"
    );
}

#[test]
fn cvss_multiple_invalid_findings_both_reported() {
    let (_tmp, dst) = setup_engagement();
    // Two bad findings: one with an out-of-range score, one with an invalid vector.
    fs::write(
        dst.join("findings/003-bad-score.md"),
        "---\nid: F-003\ntitle: Bad Score\nseverity: medium\nstatus: open\ncvss: \"20.0\"\n---\n\nbody.\n",
    )
    .unwrap();
    fs::write(
        dst.join("findings/004-bad-vector.md"),
        "---\nid: F-004\ntitle: Bad Vector\nseverity: medium\nstatus: open\ncvss_vector: \"CVSS:3.1/JUNK\"\n---\n\nbody.\n",
    )
    .unwrap();

    let err = build::run(&dst).expect_err("multiple CVSS errors should fail build");
    let msg = format!("{err:#}");
    // The bail message counts errors: "2 validation error(s)"
    assert!(
        msg.contains('2') || msg.to_lowercase().contains("validation"),
        "error should report multiple failures. got: {msg}"
    );
}

#[test]
fn cvss_valid_finding_among_invalid_does_not_suppress_error() {
    let (_tmp, dst) = setup_engagement();
    // F-003 is valid (9.8 with matching vector from fixture F-001 is already
    // clean); add F-004 with a bad vector. Build must still fail.
    write_cvss_finding(
        &dst,
        "F-003",
        "Valid Finding",
        Some("9.8"),
        Some(CVSS_VECTOR_9_8),
    );
    fs::write(
        dst.join("findings/004-bad.md"),
        "---\nid: F-004\ntitle: Bad Vector\nseverity: medium\nstatus: open\ncvss_vector: \"CVSS:3.1/GARBAGE\"\n---\n\nbody.\n",
    )
    .unwrap();

    let err = build::run(&dst).expect_err("one invalid finding among valid ones must still fail");
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "error should mention validation. got: {msg}"
    );
}

#[test]
fn cvss_fixture_findings_have_matching_score_and_vector() {
    // Regression guard: verifies that F-001 in the fixture continues to have a
    // matching cvss score and vector so other tests using the fixture stay clean.
    let eng = build_engagement(&fixture_root());
    let f001 = eng
        .findings
        .iter()
        .find(|f| f.id == "F-001")
        .expect("F-001 in fixture");
    assert_eq!(f001.cvss.as_deref(), Some("9.8"));
    assert_eq!(f001.cvss_vector.as_deref(), Some(CVSS_VECTOR_9_8));
}

// --- Severity threshold integration tests --------------------------------

/// Write `[severity_thresholds]` into the engagement's reptr.toml.
fn set_thresholds(dst: &std::path::Path, toml_snippet: &str) {
    let cfg_path = dst.join("reptr.toml");
    let mut cfg = fs::read_to_string(&cfg_path).unwrap();
    cfg.push_str(&format!("\n[severity_thresholds]\n{toml_snippet}\n"));
    fs::write(&cfg_path, cfg).unwrap();
}

#[test]
fn threshold_not_set_build_always_passes() {
    // Fixture has an open Critical (F-001) — without a threshold it should pass.
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    build::run(dst).expect("build without thresholds should succeed regardless of open findings");
}

#[test]
fn threshold_zero_critical_fails_when_critical_open() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    set_thresholds(dst, "critical = 0");

    let err = build::run(dst).expect_err("open critical finding should fail threshold");
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "error should mention validation. got: {msg}"
    );
}

#[test]
fn threshold_zero_critical_passes_when_no_open_criticals() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    set_thresholds(dst, "critical = 0");

    // Resolve the critical finding so nothing is open at that level.
    set_finding_status(
        &dst.join("findings/001-sql-injection-in-login-form.md"),
        "resolved",
    );

    build::run(dst).expect("no open criticals → threshold of 0 should pass");
}

#[test]
fn threshold_passes_when_count_exactly_at_limit() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    // Fixture has 1 open critical. Setting limit = 1 should pass (1 ≤ 1 is ok? no — limit means
    // "more than N fails", so limit = 1 means allow up to 1).
    // Actually the logic is: count > limit → fail. So count=1, limit=1 → 1 > 1 is false → passes.
    set_thresholds(dst, "critical = 1");

    build::run(dst).expect("1 open critical with limit 1 should pass");
}

#[test]
fn threshold_fails_when_count_exceeds_limit() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    // Add a second critical finding.
    fs::write(
        dst.join("findings/003-extra-critical.md"),
        "---\nid: F-003\ntitle: Extra Critical\nseverity: critical\nstatus: open\n---\n\nbody.\n",
    )
    .unwrap();
    set_thresholds(dst, "critical = 1");

    let err = build::run(dst).expect_err("2 open criticals with limit 1 should fail");
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "error should mention validation. got: {msg}"
    );
}

#[test]
fn threshold_resolved_findings_do_not_trigger_gate() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    set_thresholds(dst, "critical = 0");

    // Resolve F-001 so there are 0 open criticals.
    set_finding_status(
        &dst.join("findings/001-sql-injection-in-login-form.md"),
        "resolved",
    );

    build::run(dst).expect("resolved critical should not count against threshold");
}

#[test]
fn threshold_accepted_findings_do_not_trigger_gate() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    set_thresholds(dst, "critical = 0");

    // Mark F-001 as accepted (risk acknowledged).
    set_finding_status(
        &dst.join("findings/001-sql-injection-in-login-form.md"),
        "accepted",
    );

    build::run(dst).expect("accepted critical should not count against threshold");
}

#[test]
fn threshold_only_applies_to_matching_severity() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    // Gate on high findings — fixture has none open at High, only Critical and Low.
    set_thresholds(dst, "high = 0");

    build::run(dst).expect("no open high findings → high threshold of 0 should pass");
}

#[test]
fn threshold_error_message_is_actionable() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    set_thresholds(dst, "critical = 0");

    let err = build::run(dst).expect_err("expected validation failure");
    // The individual error messages are printed to stderr; the bail message
    // reports a count — just confirm it's a validation failure.
    let msg = format!("{err:#}");
    assert!(
        msg.to_lowercase().contains("validation"),
        "expected validation message. got: {msg}"
    );
}

#[test]
fn multiple_thresholds_exceeded_fails_build() {
    let tmp = tempfile::tempdir().unwrap();
    let dst = tmp.path();
    copy_dir(&fixture_root(), dst).unwrap();
    // Fixture: 1 open critical + 1 open low. Gate both.
    set_thresholds(dst, "critical = 0\nlow = 0");

    let err = build::run(dst).expect_err("both thresholds exceeded should fail build");
    let msg = format!("{err:#}");
    // bail message: "2 validation error(s)" (or more if other errors)
    assert!(
        msg.contains('2') || msg.to_lowercase().contains("validation"),
        "expected 2 threshold errors. got: {msg}"
    );
}

// --- watch integration tests ---------------------------------------------

#[test]
fn watch_startup_build_creates_output_files() {
    use reptr::commands::watch;
    use std::time::{Duration, Instant};

    let (_tmp, dst) = setup_engagement();
    let dst_clone = dst.clone();

    std::thread::spawn(move || {
        let _ = watch::run(&dst_clone);
    });

    // Poll up to 5 s for the startup build to produce output.
    let html = dst.join(format!("output/{SLUG}.html"));
    let deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < deadline {
        if html.exists() {
            return;
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    panic!("watch startup build did not produce HTML within 5 seconds");
}

#[test]
fn watch_startup_produces_json_with_correct_slug() {
    use reptr::commands::watch;
    use std::time::{Duration, Instant};

    let (_tmp, dst) = setup_engagement();
    let dst_clone = dst.clone();

    std::thread::spawn(move || {
        let _ = watch::run(&dst_clone);
    });

    let json_path = dst.join(format!("output/{SLUG}.json"));
    let deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < deadline {
        if json_path.exists() {
            let body = fs::read_to_string(&json_path).unwrap();
            let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
            assert_eq!(parsed["meta"]["slug"], SLUG);
            return;
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    panic!("watch startup build did not produce JSON within 5 seconds");
}

#[test]
fn watch_rebuilds_after_finding_added() {
    use reptr::commands::watch;
    use std::time::{Duration, Instant};

    let (_tmp, dst) = setup_engagement();
    let dst_clone = dst.clone();

    std::thread::spawn(move || {
        let _ = watch::run(&dst_clone);
    });

    // Wait for startup build.
    let json_path = dst.join(format!("output/{SLUG}.json"));
    let deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < deadline && !json_path.exists() {
        std::thread::sleep(Duration::from_millis(100));
    }
    assert!(json_path.exists(), "startup build must complete first");

    let mtime_before = fs::metadata(&json_path).unwrap().modified().unwrap();

    // Add a new finding to trigger a rebuild.
    fs::write(
        dst.join("findings/003-watch-test.md"),
        "---\nid: F-003\ntitle: Watch Trigger Finding\nseverity: medium\nstatus: open\n---\n\nbody.\n",
    )
    .unwrap();

    // Wait up to 4 s for the rebuild (250 ms debounce + build time).
    let deadline = Instant::now() + Duration::from_secs(4);
    loop {
        std::thread::sleep(Duration::from_millis(150));
        if let Ok(meta) = fs::metadata(&json_path) {
            if meta.modified().unwrap() > mtime_before {
                let body = fs::read_to_string(&json_path).unwrap();
                let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
                let count = parsed["findings"].as_array().unwrap().len();
                assert_eq!(count, 3, "rebuilt JSON should contain all 3 findings");
                return;
            }
        }
        if Instant::now() >= deadline {
            panic!("watch did not rebuild within 4 s after adding a new finding");
        }
    }
}

// --- helpers -------------------------------------------------------------

fn copy_dir(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
    for entry in walkdir::WalkDir::new(src) {
        let entry = entry?;
        let rel = entry.path().strip_prefix(src).unwrap();
        let out = dst.join(rel);
        if entry.file_type().is_dir() {
            fs::create_dir_all(&out)?;
        } else if entry.file_type().is_file() {
            if let Some(p) = out.parent() {
                fs::create_dir_all(p)?;
            }
            fs::copy(entry.path(), &out)?;
        }
    }
    Ok(())
}

struct ChangeDir {
    previous: PathBuf,
}

impl ChangeDir {
    fn to(p: &std::path::Path) -> Self {
        let previous = std::env::current_dir().unwrap();
        std::env::set_current_dir(p).unwrap();
        Self { previous }
    }
}

impl Drop for ChangeDir {
    fn drop(&mut self) {
        let _ = std::env::set_current_dir(&self.previous);
    }
}