//! HTML report renderer for the conformance self-test.
//!
//! Issue #79 round 17.6 — Srikanth's (17.6) ask: a human-readable
//! report grouped by category, severity, and OWASP class. The JSON
//! reports from rounds 17.x are precise but hard to skim under a
//! deadline; this module renders a self-contained HTML file that
//! drops into a browser without any external assets.
//!
//! Sections:
//! 1. Header: target URL, timestamp, headline counts.
//! 2. Self-test summary cards: positives, negatives caught / missed
//!    per category.
//! 3. Negative detail table (rolled up by category + label) so a
//!    user can drill from "owasp had 12 misses" → which routes.
//! 4. Optional spec-audit section (if a round-17.4 audit JSON is
//!    passed in alongside).
//!
//! Output is one self-contained HTML string: inline CSS, no external
//! fonts or scripts, safe to email or commit to a CI artefact bucket.

use super::self_test::{CaseOutcome, OperationResult, SelfTestReport};
use std::collections::BTreeMap;

/// Render a complete HTML report for the given self-test report.
/// `audit` is an optional `SpecAuditReport`-shaped JSON value — when
/// present, an audit section is appended. We accept `&serde_json::Value`
/// rather than the strongly-typed `SpecAuditReport` to keep this
/// module decoupled from `spec_audit` (which lives on a separate
/// in-flight branch).
pub fn render_html(report: &SelfTestReport, audit: Option<&serde_json::Value>) -> String {
    render_html_with_options(report, audit, &RenderOptions::default())
}

/// Round 21.1 — render options surfaced via CLI flags. Currently:
/// - `missed_cap`: max rows in the missed-negative drill-down table.
///   `Some(N)` caps at N (default 200); `None` shows all rows. Set
///   via `--report-missed-cap` (with `--report-missed-cap 0` mapping
///   to None for "no cap").
#[derive(Debug, Clone)]
pub struct RenderOptions {
    pub missed_cap: Option<usize>,
}

impl Default for RenderOptions {
    fn default() -> Self {
        Self {
            missed_cap: Some(200),
        }
    }
}

/// Round 21.1 — like `render_html` but lets the caller override the
/// drill-down cap. Used by the CLI when `--report-missed-cap` is set.
pub fn render_html_with_options(
    report: &SelfTestReport,
    audit: Option<&serde_json::Value>,
    opts: &RenderOptions,
) -> String {
    let mut html = String::new();
    html.push_str(HEAD);
    push_header(&mut html, report);
    push_summary_cards(&mut html, report);
    // Round 24 (e) — pre-compute the set of categories and operation
    // slugs that will actually appear in the truncated drill-down
    // table, so the count-cells in the upper tables only link when
    // the target anchor exists. Without this, a count linking to a
    // row that got cropped by `--report-missed-cap` dead-ends.
    let anchors = compute_anchor_set(report, opts);
    // Round 26 — Srikanth on 0.3.169: the standalone `Negatives by
    // category` table duplicated what the family table already shows.
    // Now there's a single `Negatives by category` table with a Family
    // column prepended; one row per category, grouped under its family.
    // No separate family rollup section.
    push_grouped_category_table(&mut html, report, &anchors);
    push_operations_table(&mut html, report, opts, &anchors);
    if let Some(a) = audit {
        push_spec_audit(&mut html, a);
    }
    html.push_str(FOOT);
    html
}

/// Round 24 (e) — for each (category, op_slug) that gets at least one
/// row in the drill-down table under the current cap, record it here.
/// The category and per-operation tables consult this set so a count
/// only becomes a clickable link when the target row is actually
/// rendered. Without this, capping at 200 rows on a 1000-violation
/// run left every link past row 200 pointing into the void.
fn compute_anchor_set(report: &SelfTestReport, opts: &RenderOptions) -> AnchorSet {
    let mut missed: Vec<(&OperationResult, &CaseOutcome)> = Vec::new();
    for op in &report.operations {
        for neg in &op.negatives {
            if !neg.passed {
                missed.push((op, neg));
            }
        }
    }
    let take = opts.missed_cap.unwrap_or(usize::MAX);
    let mut cats: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut ops: std::collections::HashSet<String> = std::collections::HashSet::new();
    for (op, neg) in missed.iter().take(take) {
        let cat = neg.label.split(':').next().unwrap_or("other").to_string();
        cats.insert(cat);
        ops.insert(op_anchor_slug(&op.method, &op.path));
    }
    AnchorSet { cats, ops }
}

/// Round 24 (e) — set of category names and operation slugs that have
/// at least one anchored row in the drill-down table after the cap.
#[derive(Default)]
struct AnchorSet {
    cats: std::collections::HashSet<String>,
    ops: std::collections::HashSet<String>,
}

/// Inline-CSS opening — no external assets, prints fine.
const HEAD: &str = r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MockForge Conformance Report</title>
<style>
  body { font-family: -apple-system, system-ui, sans-serif; max-width: 1100px;
         margin: 2rem auto; padding: 0 1rem; color: #1f2933; line-height: 1.5; }
  h1 { font-size: 1.8rem; margin: 0 0 0.5rem; }
  h2 { font-size: 1.3rem; margin: 2rem 0 0.5rem; border-bottom: 1px solid #d1d5db; padding-bottom: 0.3rem; }
  .meta { color: #6b7280; font-size: 0.9rem; }
  .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 0.75rem; margin: 1rem 0; }
  .card { padding: 0.75rem 1rem; border-radius: 6px; background: #f3f4f6; }
  .card .label { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; }
  .card .value { font-size: 1.6rem; font-weight: 600; color: #1f2933; }
  .card.ok { background: #ecfdf5; } .card.ok .value { color: #047857; }
  .card.warn { background: #fffbeb; } .card.warn .value { color: #b45309; }
  .card.err { background: #fef2f2; } .card.err .value { color: #b91c1c; }
  table { width: 100%; border-collapse: collapse; margin: 0.5rem 0 1.5rem; font-size: 0.9rem; }
  th, td { text-align: left; padding: 0.5rem 0.75rem; border-bottom: 1px solid #e5e7eb; }
  th { background: #f9fafb; font-weight: 600; color: #374151; }
  tr:hover { background: #f9fafb; }
  .badge { display: inline-block; padding: 0.1rem 0.5rem; border-radius: 999px; font-size: 0.75rem; font-weight: 500; }
  .badge.pass { background: #d1fae5; color: #047857; }
  .badge.fail { background: #fee2e2; color: #b91c1c; }
  .badge.info { background: #dbeafe; color: #1d4ed8; }
  .badge.warn { background: #fef3c7; color: #92400e; }
  .badge.err  { background: #fee2e2; color: #b91c1c; }
  .small { color: #6b7280; font-size: 0.85rem; }
  code { background: #f3f4f6; padding: 0.05rem 0.3rem; border-radius: 3px; font-size: 0.9em; }
</style>
</head>
<body>
"#;

const FOOT: &str = "\n</body>\n</html>\n";

fn push_header(out: &mut String, _report: &SelfTestReport) {
    out.push_str("<h1>MockForge Conformance Report</h1>\n");
    // Round 22.6 — link the probe-label reference next to the
    // generator credit so users can decode labels like
    // `request-body:type-mismatch:user.email` without leaving
    // the report. The book is generated separately, so we link
    // to the canonical hosted location.
    out.push_str(
        "<p class=\"meta\">Generated by <code>mockforge bench --conformance-self-test</code>. \
         Probe-label reference: \
         <a href=\"https://docs.mockforge.dev/reference/conformance-self-test-probes.html\">\
         docs.mockforge.dev/reference/conformance-self-test-probes</a>.</p>\n",
    );
}

fn push_summary_cards(out: &mut String, report: &SelfTestReport) {
    let positives = report.positive_pass + report.positive_fail;
    let neg_caught: usize = report.negative_caught.values().sum();
    let neg_missed: usize = report.negative_missed.values().sum();
    let pos_class = if report.positive_fail == 0 {
        "ok"
    } else {
        "err"
    };
    let miss_class = if neg_missed == 0 { "ok" } else { "warn" };
    out.push_str("<div class=\"cards\">\n");
    push_card(out, "Positive cases", positives, pos_class);
    push_card(out, "Positive failures", report.positive_fail, pos_class);
    push_card(out, "Negatives matched (4xx)", neg_caught, "ok");
    push_card(out, "Negatives mismatched (non-4xx)", neg_missed, miss_class);
    push_card(out, "Operations", report.operations.len(), "");
    out.push_str("</div>\n");
}

fn push_card(out: &mut String, label: &str, value: usize, class: &str) {
    let class_attr = if class.is_empty() {
        String::new()
    } else {
        format!(" {}", class)
    };
    out.push_str(&format!(
        "  <div class=\"card{class_attr}\"><div class=\"label\">{}</div><div class=\"value\">{}</div></div>\n",
        html_escape(label),
        value
    ));
}

/// Round 26 — single category table with a Family column prepended.
/// Each row is still one category with its own Matched/Mismatched
/// counts, PASS/FAIL badge, and clickable mismatch count anchor; the
/// new Family column groups categories under a family name so the
/// reader sees both the per-category resolution Srikanth wanted to
/// keep AND the family rollup in one glance. Categories with no
/// family fall back to `<code>other</code>` in the Family column.
/// Rows are sorted by family first then category, so all members of a
/// family render contiguously.
fn push_grouped_category_table(out: &mut String, report: &SelfTestReport, anchors: &AnchorSet) {
    out.push_str("<h2>Negatives by category</h2>\n");
    let mut keys: Vec<&String> =
        report.negative_caught.keys().chain(report.negative_missed.keys()).collect();
    keys.sort();
    keys.dedup();
    if keys.is_empty() {
        out.push_str("<p class=\"small\">No negative probes ran — typically means no operations had any injectable surface.</p>\n");
        return;
    }
    // (family, category) tuples so we can sort by family first.
    let mut rows: Vec<(&'static str, &String)> =
        keys.into_iter().map(|c| (family_for_category(c), c)).collect();
    rows.sort_by(|a, b| a.0.cmp(b.0).then_with(|| a.1.cmp(b.1)));
    out.push_str("<table>\n<thead><tr><th>Family</th><th>Category</th><th>Matched (4xx)</th><th>Mismatched (non-4xx)</th><th>Status</th></tr></thead>\n<tbody>\n");
    for (family, cat) in rows {
        let caught = report.negative_caught.get(cat).copied().unwrap_or(0);
        let missed = report.negative_missed.get(cat).copied().unwrap_or(0);
        let (badge_class, badge_text) = if missed == 0 {
            ("pass", "PASS")
        } else {
            ("fail", "FAIL")
        };
        // Same clickable-count + cap-aware logic as rounds 23/24.
        let missed_cell = if missed > 0 && anchors.cats.contains(cat) {
            format!("<a href=\"#miss-cat-{}\">{}</a>", html_escape(cat), missed)
        } else {
            missed.to_string()
        };
        out.push_str(&format!(
            "<tr><td>{}</td><td><code>{}</code></td><td>{}</td><td>{}</td><td><span class=\"badge {}\">{}</span></td></tr>\n",
            html_escape(family),
            html_escape(cat),
            caught,
            missed_cell,
            badge_class,
            badge_text
        ));
    }
    out.push_str("</tbody></table>\n");
}

/// Round 26 — map a category label prefix to its display family name.
/// Mirrors the membership in the deleted `push_family_table`. Keeping
/// the map in one place so future probes (e.g. round-25's
/// content-type-mismatch) are easy to slot into the right family.
fn family_for_category(cat: &str) -> &'static str {
    match cat {
        "request-body" => "Request body",
        "parameters" => "Parameters",
        "security" | "owasp" => "Security",
        _ => "other",
    }
}

fn push_operations_table(
    out: &mut String,
    report: &SelfTestReport,
    opts: &RenderOptions,
    anchors: &AnchorSet,
) {
    out.push_str("<h2>Per-operation results</h2>\n");
    if report.operations.is_empty() {
        out.push_str("<p class=\"small\">No operations.</p>\n");
        return;
    }
    // Round 25 — added a `By category` column showing which categories
    // each operation's mismatches came from. Comma-joined `cat:N` pairs
    // make it scannable from the upper table without expanding the
    // drill-down. Empty cell when the operation has zero mismatches.
    out.push_str("<table>\n<thead><tr><th>Method</th><th>Path</th><th>Positive</th><th>Matched / Mismatched</th><th>By category</th></tr></thead>\n<tbody>\n");
    for op in &report.operations {
        let pos_badge = match &op.positive {
            Some(p) if p.passed => "<span class=\"badge pass\">2xx ✓</span>".to_string(),
            Some(p) => format!("<span class=\"badge fail\">{} ✗</span>", p.actual_status),
            None => "<span class=\"badge info\">none</span>".into(),
        };
        let (caught, missed) = op.negatives.iter().partition::<Vec<&CaseOutcome>, _>(|n| n.passed);
        // Round 23 (d) — clickable count: link the Mismatched count to
        // the operation's anchor in the drill-down table below.
        // Round 24 (e) — only link when the operation's first
        // mismatched row survived the cap, otherwise the link is a
        // dead anchor.
        let op_slug = op_anchor_slug(&op.method, &op.path);
        let missed_cell = if missed.is_empty() {
            "0".to_string()
        } else if anchors.ops.contains(&op_slug) {
            format!("<a href=\"#miss-op-{}\">{}</a>", op_slug, missed.len())
        } else {
            missed.len().to_string()
        };
        // Round 25 — per-operation category breakdown: count
        // mismatches grouped by their label's first segment. Sorted
        // alphabetically for stable rendering.
        let mut by_cat: BTreeMap<&str, usize> = BTreeMap::new();
        for m in &missed {
            let cat = m.label.split(':').next().unwrap_or("other");
            *by_cat.entry(cat).or_insert(0) += 1;
        }
        // Round 28 — Srikanth's 0.3.171 ask: each `cat:N` here should
        // be clickable like the upper Mismatched count, so the reader
        // can jump straight to the category's drill-down rows. Same
        // cap-aware rule as the per-row links above: only emit `<a>`
        // when the category has at least one anchored row in the
        // drill-down table.
        let by_cat_cell = if by_cat.is_empty() {
            String::new()
        } else {
            by_cat
                .iter()
                .map(|(cat, n)| {
                    if anchors.cats.contains(*cat) {
                        format!(
                            "<code><a href=\"#miss-cat-{}\">{}:{}</a></code>",
                            html_escape(cat),
                            html_escape(cat),
                            n
                        )
                    } else {
                        format!("<code>{}:{}</code>", html_escape(cat), n)
                    }
                })
                .collect::<Vec<_>>()
                .join(" ")
        };
        out.push_str(&format!(
            "<tr><td><code>{}</code></td><td><code>{}</code></td><td>{}</td><td>{} / {}</td><td>{}</td></tr>\n",
            html_escape(&op.method),
            html_escape(&op.path),
            pos_badge,
            caught.len(),
            missed_cell,
            by_cat_cell
        ));
    }
    out.push_str("</tbody></table>\n");
    push_missed_detail(out, report, opts);
}

/// Round 23 (d) — stable slug for the per-operation anchor in the
/// missed-negative drill-down table. Lowercase, [a-z0-9_] only so the
/// resulting `id` is HTML-valid and the `#miss-op-...` link from the
/// Per-operation table resolves predictably. Collisions across very
/// similar paths are acceptable: clicking lands on the first matching
/// row and the table is short enough to scan from there.
fn op_anchor_slug(method: &str, path: &str) -> String {
    let mut s = format!("{method}_{path}");
    s = s.to_ascii_lowercase();
    s = s.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
    s
}

/// Round 21.1 — human-readable expected status range derived from the
/// probe's `expected_4xx` flag, so the missed-negative table tells you
/// what status it WAS expecting alongside what it ACTUALLY saw.
fn expected_status_label(case: &CaseOutcome) -> &'static str {
    if case.expected_4xx {
        "4xx (reject)"
    } else {
        "2xx-3xx (accept)"
    }
}

fn push_missed_detail(out: &mut String, report: &SelfTestReport, opts: &RenderOptions) {
    // List every individual missed negative for drill-down. By default
    // capped at 200 rows to keep the HTML file under a reasonable size
    // on huge specs; raise or remove via `--report-missed-cap`. The
    // JSON report always has the full set.
    let mut missed: Vec<(&OperationResult, &CaseOutcome)> = Vec::new();
    for op in &report.operations {
        for neg in &op.negatives {
            if !neg.passed {
                missed.push((op, neg));
            }
        }
    }
    if missed.is_empty() {
        return;
    }
    out.push_str(
        "<h2>Mismatched negatives (server returned non-4xx to a probe expecting 4xx)</h2>\n",
    );
    // Cap message: surface the cap explicitly so the user knows
    // whether the table is truncated or complete.
    let total = missed.len();
    let cap_msg = match opts.missed_cap {
        Some(cap) if total > cap => format!(
            "{} mismatched negative(s). Showing first {} (raise with <code>--report-missed-cap N</code>, or <code>0</code> for no cap); full set in <code>conformance-self-test.json</code>.",
            total, cap
        ),
        Some(_) => format!("{} mismatched negative(s). All shown.", total),
        None => format!("{} mismatched negative(s). All shown (no cap).", total),
    };
    out.push_str(&format!("<p class=\"small\">{cap_msg}</p>\n"));
    out.push_str("<table>\n<thead><tr><th>Method</th><th>Path</th><th>Label</th><th>Expected</th><th>Actual</th></tr></thead>\n<tbody>\n");
    let take = opts.missed_cap.unwrap_or(usize::MAX);
    // Round 23 (d) — emit anchor ids so the count-cells in the
    // Negatives-by-category and Per-operation tables can link straight
    // to the first matching drill-down row:
    //   `miss-cat-<category>` on the <tr>
    //   `miss-op-<slug>`      on a zero-size <span> in the first cell
    // (a <tr> can only carry one `id`, so the per-op anchor rides on
    // the span; HTML treats both as valid jump targets). First-seen
    // wins to avoid duplicate IDs across the truncated table.
    let mut seen_cat: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut seen_op: std::collections::HashSet<String> = std::collections::HashSet::new();
    for (op, neg) in missed.iter().take(take) {
        let cat = neg.label.split(':').next().unwrap_or("other").to_string();
        let op_slug = op_anchor_slug(&op.method, &op.path);
        let tr_id = if seen_cat.insert(cat.clone()) {
            format!(" id=\"miss-cat-{}\"", html_escape(&cat))
        } else {
            String::new()
        };
        let op_anchor = if seen_op.insert(op_slug.clone()) {
            format!("<span id=\"miss-op-{op_slug}\"></span>")
        } else {
            String::new()
        };
        out.push_str(&format!(
            "<tr{}><td>{}<code>{}</code></td><td><code>{}</code></td><td><code>{}</code></td><td><span class=\"badge info\">{}</span></td><td>{}</td></tr>\n",
            tr_id,
            op_anchor,
            html_escape(&op.method),
            html_escape(&op.path),
            html_escape(&neg.label),
            expected_status_label(neg),
            neg.actual_status
        ));
    }
    out.push_str("</tbody></table>\n");
}

fn push_spec_audit(out: &mut String, audit: &serde_json::Value) {
    out.push_str("<h2>Spec audit</h2>\n");
    let findings = audit.get("findings").and_then(|v| v.as_array());
    let coverage = audit.get("datatype_coverage").and_then(|v| v.as_object());
    let ops = audit.get("operations_audited").and_then(|v| v.as_u64()).unwrap_or(0);
    out.push_str(&format!(
        "<p class=\"small\">Audited {ops} operation(s). Coverage map: {} datatype kind(s).</p>\n",
        coverage.map(|c| c.len()).unwrap_or(0)
    ));
    if let Some(findings) = findings {
        if findings.is_empty() {
            out.push_str("<p class=\"small\">No findings.</p>\n");
        } else {
            // Group findings by severity for an easy scan.
            let mut by_sev: BTreeMap<String, Vec<&serde_json::Value>> = BTreeMap::new();
            for f in findings {
                let sev = f.get("severity").and_then(|v| v.as_str()).unwrap_or("info").to_string();
                by_sev.entry(sev).or_default().push(f);
            }
            out.push_str("<table>\n<thead><tr><th>Severity</th><th>Category</th><th>Location</th><th>Message</th></tr></thead>\n<tbody>\n");
            for (sev, items) in by_sev {
                let badge_class = match sev.as_str() {
                    "error" => "err",
                    "warning" => "warn",
                    _ => "info",
                };
                for item in items {
                    let cat = item.get("category").and_then(|v| v.as_str()).unwrap_or("");
                    let loc = item.get("location").and_then(|v| v.as_str()).unwrap_or("");
                    let msg = item.get("message").and_then(|v| v.as_str()).unwrap_or("");
                    out.push_str(&format!(
                        "<tr><td><span class=\"badge {}\">{}</span></td><td><code>{}</code></td><td><code>{}</code></td><td>{}</td></tr>\n",
                        badge_class,
                        html_escape(&sev),
                        html_escape(cat),
                        html_escape(loc),
                        html_escape(msg)
                    ));
                }
            }
            out.push_str("</tbody></table>\n");
        }
    }
    if let Some(coverage) = coverage {
        let mut entries: Vec<(&String, u64)> =
            coverage.iter().filter_map(|(k, v)| v.as_u64().map(|c| (k, c))).collect();
        entries.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
        if !entries.is_empty() {
            out.push_str("<h2>Datatype coverage</h2>\n");
            out.push_str("<table>\n<thead><tr><th>Type</th><th>Count</th></tr></thead>\n<tbody>\n");
            for (kind, count) in entries.iter().take(40) {
                out.push_str(&format!(
                    "<tr><td><code>{}</code></td><td>{}</td></tr>\n",
                    html_escape(kind),
                    count
                ));
            }
            out.push_str("</tbody></table>\n");
        }
    }
}

fn html_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            _ => out.push(c),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::conformance::self_test::{CaseOutcome, OperationResult, SelfTestReport};

    fn sample_report() -> SelfTestReport {
        SelfTestReport {
            positive_pass: 3,
            positive_fail: 1,
            negative_caught: BTreeMap::from([("request-body".into(), 4), ("parameters".into(), 2)]),
            negative_missed: BTreeMap::from([("owasp".into(), 1)]),
            operations: vec![OperationResult {
                method: "POST".into(),
                path: "/users".into(),
                positive: Some(CaseOutcome {
                    label: "positive".into(),
                    expected_4xx: false,
                    actual_status: 201,
                    passed: true,
                }),
                negatives: vec![CaseOutcome {
                    label: "owasp:sqli".into(),
                    expected_4xx: true,
                    actual_status: 200,
                    passed: false,
                }],
            }],
        }
    }

    #[test]
    fn html_contains_expected_sections() {
        let html = render_html(&sample_report(), None);
        assert!(html.contains("<title>MockForge Conformance Report</title>"));
        assert!(html.contains("Positive cases"));
        assert!(html.contains("Negatives by category"));
        assert!(html.contains("Per-operation results"));
        // Round 23 wording polish: "Missed negatives" → "Mismatched negatives".
        assert!(html.contains("Mismatched negatives"));
        // Specific data points from the sample report:
        assert!(html.contains("request-body"));
        assert!(html.contains("owasp:sqli"));
        assert!(html.contains("/users"));
        // Round 26 — single grouped category table, no separate family
        // section, but a Family column inside the per-category table.
        assert!(!html.contains("Negatives by category family"));
        assert!(html.contains("<th>Family</th>"));
    }

    /// Round 26 — every probe category in the report shows up under
    /// its mapped family in the per-category table. Catches the case
    /// where a new probe family (e.g. round 25's content-type-mismatch)
    /// silently slips through with "other" instead of "Request body".
    #[test]
    fn html_category_table_assigns_each_category_to_a_family() {
        let mut report = SelfTestReport::default();
        report.negative_caught.insert("request-body".into(), 3);
        report.negative_missed.insert("parameters".into(), 1);
        report.negative_missed.insert("security".into(), 2);
        report.negative_caught.insert("owasp".into(), 4);
        let html = render_html(&report, None);
        assert!(html.contains(">Request body</td>"));
        assert!(html.contains(">Parameters</td>"));
        // Both `security` and `owasp` get the same family label.
        assert_eq!(html.matches(">Security</td>").count(), 2);
        // No category should fall through to the "other" bucket here.
        assert!(!html.contains(">other</td>"));
    }

    #[test]
    fn html_renders_audit_section_when_present() {
        let audit = serde_json::json!({
            "findings": [
                {"category": "servers", "severity": "warning",
                 "location": "#/servers", "message": "no servers declared"}
            ],
            "datatype_coverage": {"string": 5, "integer": 3},
            "operations_audited": 7
        });
        let html = render_html(&sample_report(), Some(&audit));
        assert!(html.contains("Spec audit"));
        assert!(html.contains("no servers declared"));
        assert!(html.contains("Datatype coverage"));
        assert!(html.contains("string"));
        assert!(html.contains("Audited 7 operation"));
    }

    #[test]
    fn html_escapes_special_chars_in_labels() {
        let mut report = sample_report();
        report.operations[0].path = "/items/<script>".into();
        report.operations[0].negatives[0].label = "owasp:xss:<>\"&".into();
        let html = render_html(&report, None);
        // The literal special chars should be escaped, not rendered raw.
        assert!(!html.contains("/items/<script>"));
        assert!(html.contains("&lt;script&gt;"));
        assert!(html.contains("&quot;"));
    }

    #[test]
    fn html_handles_empty_report() {
        let html = render_html(&SelfTestReport::default(), None);
        assert!(html.contains("No negative probes ran"));
        assert!(html.contains("No operations."));
    }

    #[test]
    fn html_caps_missed_detail_at_default_200_rows() {
        let mut report = SelfTestReport::default();
        for i in 0..250 {
            report.operations.push(OperationResult {
                method: "GET".into(),
                path: format!("/r/{i}"),
                positive: None,
                negatives: vec![CaseOutcome {
                    label: "parameters:missing-query".into(),
                    expected_4xx: true,
                    actual_status: 200,
                    passed: false,
                }],
            });
        }
        report.negative_missed.insert("parameters".into(), 250);
        let html = render_html(&report, None);
        // Cap message visible and references the new flag (round 23: "missed" → "mismatched"):
        assert!(html.contains("250 mismatched negative"));
        assert!(html.contains("Showing first 200"));
        assert!(html.contains("--report-missed-cap"));
    }

    /// Round 21.1 — when `missed_cap` is `None` (set via
    /// `--report-missed-cap 0`), all rows are shown and the message
    /// says so explicitly.
    #[test]
    fn html_no_cap_shows_all_rows() {
        let mut report = SelfTestReport::default();
        for i in 0..50 {
            report.operations.push(OperationResult {
                method: "GET".into(),
                path: format!("/r/{i}"),
                positive: None,
                negatives: vec![CaseOutcome {
                    label: "parameters:missing-query".into(),
                    expected_4xx: true,
                    actual_status: 200,
                    passed: false,
                }],
            });
        }
        let opts = RenderOptions { missed_cap: None };
        let html = render_html_with_options(&report, None, &opts);
        assert!(html.contains("50 mismatched negative"));
        assert!(html.contains("All shown (no cap)"));
        assert!(!html.contains("Showing first"));
    }

    /// Round 21.1 — the missed-negative table now has an Expected
    /// column derived from the probe's `expected_4xx` flag.
    #[test]
    fn html_missed_table_has_expected_column() {
        let mut report = sample_report();
        // The sample's single missed negative is `owasp:sqli` with
        // expected_4xx: true.
        report.operations[0].negatives = vec![CaseOutcome {
            label: "security:bad-bearer".into(),
            expected_4xx: true,
            actual_status: 200,
            passed: false,
        }];
        let html = render_html(&report, None);
        assert!(html.contains("Expected"), "Expected column header missing");
        assert!(
            html.contains("4xx (reject)"),
            "expected-status badge for negative probe missing"
        );
    }

    /// Round 24 (e) — when `--report-missed-cap` truncates the drill-
    /// down to N rows, the count-cells in the upper tables must only
    /// link to a `#miss-cat-*` or `#miss-op-*` anchor that's actually
    /// rendered. Srikanth's report: clicking a count past the cap
    /// dead-ended because the anchor was cropped out.
    #[test]
    fn html_count_links_only_emit_for_visible_anchors() {
        let mut report = SelfTestReport::default();
        // 4 operations, each contributes one mismatched negative.
        // Categories alternate `cat-a` and `cat-b` so we have two
        // distinct categories. With cap=1 only the first row survives
        // the truncation, so its category/operation should be the
        // only ones linked from the upper tables.
        let cats = ["cat-a", "cat-b", "cat-a", "cat-b"];
        for (i, c) in cats.iter().enumerate() {
            report.operations.push(OperationResult {
                method: "GET".into(),
                path: format!("/r/{i}"),
                positive: None,
                negatives: vec![CaseOutcome {
                    label: format!("{c}:fail-{i}"),
                    expected_4xx: true,
                    actual_status: 200,
                    passed: false,
                }],
            });
            *report.negative_missed.entry((*c).to_string()).or_insert(0) += 1;
        }
        let opts = RenderOptions {
            missed_cap: Some(1),
        };
        let html = render_html_with_options(&report, None, &opts);
        // The drill-down only renders one row; its category is
        // `cat-a` and its operation slug is `get__r_0`.
        assert!(html.contains("id=\"miss-cat-cat-a\""));
        assert!(!html.contains("id=\"miss-cat-cat-b\""));
        // cat-a's count cell is a link; cat-b's count cell is just
        // the number with no `<a href="#miss-cat-cat-b">`.
        assert!(html.contains("<a href=\"#miss-cat-cat-a\">"));
        assert!(!html.contains("<a href=\"#miss-cat-cat-b\">"));
        // Per-op: only `/r/0` has an anchor in the drill-down, so
        // only its count is a link.
        assert!(html.contains("<a href=\"#miss-op-get__r_0\">"));
        assert!(!html.contains("<a href=\"#miss-op-get__r_2\">"));
    }
}
