"""Summarise pq-tls-results.csv (written by pq-tls-survey.py).

Usage: python pq-tls-analyze.py pq-tls-results.csv > pq-tls-analysis-output.txt
"""
import csv
import sys
from collections import Counter

rows = list(csv.DictReader(open(sys.argv[1], newline="")))
ok = [r for r in rows if r["tls_ok"] == "True"]
fail = [r for r in rows if r["tls_ok"] != "True"]


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


print(f"domains: {len(rows)}")
print(f"TLS handshake completed: {len(ok)} "
      f"(bare name {sum(r['host'] == r['domain'] for r in ok)}, "
      f"www fallback {sum(r['host'] != r['domain'] for r in ok)})")
print("no handshake, by reason:", dict(Counter(r["err"] for r in fail)))

pq = [r for r in ok if r["proto"] == "TLSv1.3" and r["group"] == "X25519MLKEM768"]
t13 = [r for r in ok if r["proto"] == "TLSv1.3"]
t12 = [r for r in ok if r["proto"] != "TLSv1.3"]
cap_not_pref = [r for r in ok if r["pq_only_ok"] == "True"]
nopq = [r for r in ok if r not in pq and r not in cap_not_pref]

print("\n== key exchange, browser-like offer (X25519MLKEM768 + X25519 shares) ==")
print(f"negotiated X25519MLKEM768: {len(pq)} ({pct(len(pq), len(ok))})")
print(f"supports it but picked a classical group: {len(cap_not_pref)} ({pct(len(cap_not_pref), len(ok))})")
print(f"no post-quantum group at all: {len(nopq)} ({pct(len(nopq), len(ok))})")
print(f"  of which TLS 1.2 only: {len(t12)}; TLS 1.3 without PQ: {len(nopq) - len(t12)}")
print("groups chosen by the non-PQ sites:", dict(Counter(r["group"] for r in nopq + cap_not_pref)))

print("\n== by rank band (share of completed handshakes that negotiated PQ) ==")
for lo, hi in [(1, 100), (101, 300), (301, 600), (601, 1000)]:
    band = [r for r in ok if lo <= int(r["rank"]) <= hi]
    n = sum(r in pq for r in band)
    print(f"ranks {lo}-{hi}: {n}/{len(band)} = {pct(n, len(band))}")


def key_class(k):
    k = k.strip()
    if k.startswith("EC") and "prime256v1" in k:
        return "ECDSA P-256"
    if k.startswith("EC") and "secp384r1" in k:
        return "ECDSA P-384"
    if k.startswith("EC"):
        return "EC other: " + k
    if k.startswith("RSA"):
        bits = int(k.split(",")[1].split()[0])
        return f"RSA {bits}"
    return k or "unknown"


print("\n== leaf certificate key (all completed handshakes) ==")
leaf = Counter(key_class(r["leaf_key"]) for r in ok)
for k, v in leaf.most_common():
    print(f"{k}: {v} ({pct(v, len(ok))})")

print("\n== leaf certificate key, PQ-negotiating sites only ==")
leafpq = Counter(key_class(r["leaf_key"]) for r in pq)
for k, v in leafpq.most_common():
    print(f"{k}: {v} ({pct(v, len(pq))})")


def has_p256_anywhere(r):
    keys = [r["leaf_key"]] + [k for k in r["chain_keys"].split("|") if k.strip()]
    return any(key_class(k) == "ECDSA P-256" for k in keys)


both = [r for r in pq if key_class(r["leaf_key"]) not in ("ECDSA P-256",) and not has_p256_anywhere(r)]
print("\n== both halves ==")
print(f"PQ key exchange and no P-256 key in leaf or sent chain: {len(both)} ({pct(len(both), len(ok))})")
print(f"PQ key exchange but a P-256 key somewhere in what was sent: {len(pq) - len(both)}")
print("leaf keys among the 'both' group:", dict(Counter(key_class(r["leaf_key"]) for r in both)))

print("\n== sample: top-ranked sites without PQ (first 25) ==")
for r in sorted(nopq + cap_not_pref, key=lambda r: int(r["rank"]))[:25]:
    print(r["rank"], r["host"], r["proto"], r["group"], "pq_only_ok=" + r["pq_only_ok"])
