"""Summarise p256-ca-results.csv (output of p256-ca-survey.py).

A site counts as "chains to a P-256 CA key" when any CA certificate on the
path the server sent (walking leaf -> issuer by subject name) has an ECDSA
P-256 public key, or when the root that path ends at has one in Mozilla's
bundle. The leaf's own key is reported separately: Chrome's change is about
CA keys, not server keys.

Usage: python p256-ca-analyze.py p256-ca-results.csv cacert.pem
"""
import csv
import json
import re
import sys
from collections import Counter

from cryptography import x509
from cryptography.hazmat.primitives.asymmetric import ec

PEM_RE = re.compile(rb"-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----", re.S)


def p256_roots(path):
    names = set()
    for pem in PEM_RE.findall(open(path, "rb").read()):
        c = x509.load_pem_x509_certificate(pem)
        k = c.public_key()
        if isinstance(k, ec.EllipticCurvePublicKey) and k.curve.name == "secp256r1":
            names.add(c.subject.rfc4514_string())
    return names


def path_from_leaf(chain):
    path = [chain[0]]
    by_subject = {c["subject"]: c for c in chain[1:]}
    seen = set()
    while True:
        cur = path[-1]
        if cur["issuer"] == cur["subject"] or cur["issuer"] in seen:
            break
        nxt = by_subject.get(cur["issuer"])
        if not nxt:
            break
        seen.add(cur["issuer"])
        path.append(nxt)
    return path


def cn(name):
    m = re.search(r"CN=([^,]+)", name)
    return m.group(1) if m else name


def pct(a, b):
    return f"{a}/{b} = {100 * a / b:.1f}%"


def main():
    rows = list(csv.DictReader(open(sys.argv[1], encoding="utf-8")))
    p256_root_names = p256_roots(sys.argv[2])
    ok = [r for r in rows if r["ok"] == "True"]
    print(f"domains: {len(rows)}; chain received: {len(ok)}")
    print(f"no chain, by reason: {dict(Counter(r['err'] for r in rows if r['ok'] != 'True'))}")
    print(f"Mozilla roots with a P-256 key: {len(p256_root_names)}")
    for n in sorted(p256_root_names):
        print(f"  {cn(n)}")

    leaf_keys = Counter(r["leaf_key"] for r in ok)
    issuer_keys = Counter(r["issuer_key"] or "(issuer not sent)" for r in ok)
    affected, by_issuer, by_reason = [], Counter(), Counter()
    cross = Counter()
    for r in ok:
        chain = json.loads(r["chain"])
        path = path_from_leaf(chain)
        p256_cas = [c for c in path[1:] if c["key"] == "P-256"]
        root_p256 = r["root_name"] in p256_root_names
        if p256_cas or root_p256:
            affected.append(r)
            if p256_cas:
                by_issuer[cn(p256_cas[0]["subject"])] += 1
                by_reason["P-256 intermediate on sent path"] += 1
            else:
                by_issuer["root: " + cn(r["root_name"])] += 1
                by_reason["P-256 root only"] += 1
        cross[(r["leaf_key"], r["issuer_key"] or "?")] += 1

    print("\n== leaf (server) key ==")
    for k, v in leaf_keys.most_common():
        print(f"{k}: {pct(v, len(ok))}")
    print("\n== key of the CA that signed the leaf ==")
    for k, v in issuer_keys.most_common():
        print(f"{k}: {pct(v, len(ok))}")
    print("\n== leaf key x issuing-CA key ==")
    for (lk, ik), v in cross.most_common():
        print(f"leaf {lk:9s} issuer {ik:9s} {v}")

    print(f"\n== chains to a P-256 CA key (Chrome 2027-03-15 change) ==")
    print(f"affected: {pct(len(affected), len(ok))}")
    for k, v in by_reason.most_common():
        print(f"  {k}: {v}")
    leaf_p256 = sum(1 for r in ok if r["leaf_key"] == "P-256")
    both = sum(1 for r in affected if r["leaf_key"] == "P-256")
    print(f"leaf key is P-256: {leaf_p256}; of those, CA also P-256: {both}; "
          f"affected sites with a non-P-256 leaf: {len(affected) - both}")
    late = [r for r in affected if r["leaf_not_after"] >= "2027-03-15"]
    print(f"affected leaf certs still valid on 2027-03-15: {len(late)} "
          f"(the other {len(affected) - len(late)} expire before it)")
    life = Counter(r["leaf_not_after"][:7] for r in affected)
    print(f"affected leaf expiry by month: {dict(sorted(life.items()))}")
    late_by = Counter(cn(r["issuer_name"]) for r in late)
    print(f"still valid on 2027-03-15, by issuer: {dict(late_by.most_common())}")
    print("\n== affected sites by first P-256 CA on the path ==")
    for k, v in by_issuer.most_common():
        print(f"{v:4d}  {k}")

    print("\n== by rank band ==")
    for lo, hi in ((1, 100), (101, 300), (301, 600), (601, 1000)):
        b_ok = [r for r in ok if lo <= int(r["rank"]) <= hi]
        b_aff = [r for r in affected if lo <= int(r["rank"]) <= hi]
        print(f"ranks {lo}-{hi}: {pct(len(b_aff), len(b_ok))}")

    print("\n== top 20 ranked affected sites ==")
    for r in sorted(affected, key=lambda r: int(r["rank"]))[:20]:
        print(f"{r['rank']:>4} {r['domain']:28s} leaf {r['leaf_key']:8s} "
              f"issuer {cn(r['issuer_name'])}")


if __name__ == "__main__":
    main()
