#!/usr/bin/env python3
"""Render summary.json from kalora-benchmark.py into Markdown tables."""
import json
import sys


def short(r):
    return (
        r.replace("registry.kaloracloud.eu/kalora/", "kalora/")
        .replace("registry.access.redhat.com/", "")
    )


def mb(b):
    return f"{b / 1e6:.1f}"


def pct(k, u):
    return "n/a" if k is None or u is None or u == 0 else f"{(u - k) / u * 100:.1f}%"


def ch(d, t):
    s_ = d[t]["by_severity"]
    return s_["critical"] + s_["high"]


def yn(v):
    return ", ".join(f"`{x.rsplit('/', 1)[-1]}`" for x in v) if v else "none"


def render_markdown(s):
    I = s["images"]
    lines = []

    lines.append("### Vulnerabilities\n")
    lines.append("| Kalora image | Upstream | Trivy CVEs (Kalora / VEX / upstream) | Trivy reduction (raw / VEX) | Grype CVEs (Kalora / upstream) | Grype reduction | Critical + High, Trivy (Kalora / VEX / upstream) |")
    lines.append("|---|---|---|---|---|---|---|")
    for c in s["comparisons"]:
        k, u = I[c["kalora"]], I[c["upstream"]]
        if "error" in k or "error" in u:
            lines.append(f"| `{short(c['kalora']).removeprefix('kalora/')}` | `{short(c['upstream'])}` | n/a | n/a | n/a | n/a | n/a |")
            continue
        kv = k.get("trivy_vex") or k["trivy"]
        trivy_col = f"{k['trivy']['total']} / {kv['total']} / {u['trivy']['total']}"
        red_col = f"{pct(k['trivy']['total'], u['trivy']['total'])} / {pct(kv['total'], u['trivy']['total'])}"
        grype_col = f"{k['grype']['total']} / {u['grype']['total']}"
        gred_col = pct(k["grype"]["total"], u["grype"]["total"])
        ch_col = f"{ch(k, 'trivy')} / {kv['by_severity']['critical'] + kv['by_severity']['high']} / {ch(u, 'trivy')}"
        lines.append(
            f"| `{short(c['kalora']).removeprefix('kalora/')}` | `{short(c['upstream'])}` | {trivy_col} | {red_col} | {grype_col} | {gred_col} | {ch_col} |"
        )

    lines.append("\n### Fixable vulnerabilities, EUVD, EU-KEV and OpenVEX\n")
    lines.append("| Image | Trivy fixable / unfixable | Grype fixable / unfixable | EUVD-listed CVEs (Trivy / Grype) | EU-KEV matches | OpenVEX statements |")
    lines.append("|---|---|---|---|---|---|")
    for r, d in I.items():
        name = short(r).removeprefix("kalora/")
        if "error" in d:
            lines.append(f"| `{name}` | n/a | n/a | n/a | n/a | n/a |")
            continue
        t_fix = f"{d['trivy']['fixable']} / {d['trivy']['unfixable']}"
        g_fix = f"{d['grype']['fixable']} / {d['grype']['unfixable']}"
        euvd_col = f"{d['trivy']['euvd_matches']} / {d['grype']['euvd_matches']}"
        kev_set = set(d["trivy"]["eu_kev_matches"] or []) | set(d["grype"]["eu_kev_matches"] or [])
        vex = d.get("vex")
        if vex and vex.get("has_openvex"):
            if vex["statements"] == 0:
                vex_col = "0 (clean sentinel)"
            else:
                parts = ", ".join(f"{k}: {v}" for k, v in vex["by_status"].items())
                vex_col = f"{vex['statements']} ({parts})"
        else:
            vex_col = "n/a"
        lines.append(f"| `{name}` | {t_fix} | {g_fix} | {euvd_col} | {len(kev_set)} | {vex_col} |")

    lines.append("\n### Size, layers and packages\n")
    lines.append("| Kalora image | Upstream | Compressed MB (Kalora / upstream) | Reduction | Uncompressed MB (Kalora / upstream) | Reduction | Layers (Kalora / upstream) | SBOM packages (Kalora / upstream) | Reduction |")
    lines.append("|---|---|---|---|---|---|---|---|---|")
    for c in s["comparisons"]:
        k, u = I[c["kalora"]], I[c["upstream"]]
        kname = short(c["kalora"]).removeprefix("kalora/")
        uname = short(c["upstream"])
        if "error" in k or "error" in u:
            lines.append(f"| `{kname}` | `{uname}` | n/a | n/a | n/a | n/a | n/a | n/a | n/a |")
            continue
        lines.append(
            f"| `{kname}` | `{uname}` | {mb(k['compressed_bytes'])} / {mb(u['compressed_bytes'])} | {pct(k['compressed_bytes'], u['compressed_bytes'])} | "
            f"{mb(k['uncompressed_bytes'])} / {mb(u['uncompressed_bytes'])} | {pct(k['uncompressed_bytes'], u['uncompressed_bytes'])} | "
            f"{k['layers']} / {u['layers']} | {k['sbom_packages']} / {u['sbom_packages']} | {pct(k['sbom_packages'], u['sbom_packages'])} |"
        )

    lines.append("\n### Attack surface\n")
    lines.append("| Image | Shell | OS package manager | Language package manager | SUID/SGID files | Executable files | ELF binaries | Default user |")
    lines.append("|---|---|---|---|---|---|---|---|")
    for r, d in I.items():
        name = short(r).removeprefix("kalora/")
        if "error" in d:
            lines.append(f"| `{name}` | n/a | n/a | n/a | n/a | n/a | n/a | n/a |")
            continue
        du = "root (not set)" if d["default_user"] == "root (unset)" else str(d["default_user"])
        lines.append(
            f"| `{name}` | {yn(d['shell'])} | {yn(d['os_package_manager'])} | {yn(d['language_package_manager'])} | "
            f"{len(d['setuid_setgid_files'])} | {d['executable_files']} | {d['elf_binaries']} | {du} |"
        )

    lines.append("\n### Digests\n")
    lines.append(f"| Image reference | Platform digest ({s.get('platform', 'linux/amd64')} manifest) |")
    lines.append("|---|---|")
    for r, d in I.items():
        val = "n/a: " + d["error"].splitlines()[-1][:80] if "error" in d else f"`{d['platform_digest']}`"
        lines.append(f"| `{r}` | {val} |")

    return "\n".join(lines) + "\n"


def main():
    if len(sys.argv) != 2:
        sys.exit("Usage: render.py <summary.json>")
    s = json.loads(open(sys.argv[1]).read())
    sys.stdout.write(render_markdown(s))


if __name__ == "__main__":
    main()
