"""Compare CBOMkit and CRYPTAGION CBOMs for keycloak/keycloak @ 4246609 (26.8.0).

usage: analyse_keycloak.py <schemas-dir> <cbomkit-run-1.json> <cbomkit-run-2.json>
                           <cryptagion-run-1-dir> <cryptagion-run-2-dir> <out.json>
"""
import json, re, sys, collections
from pathlib import Path
from jsonschema import Draft7Validator
from referencing import Registry, Resource

schemas, k1p, k2p, c1d, c2d, outp = map(Path, sys.argv[1:7])
res = []
for f in schemas.glob("*.json"):
    o = json.loads(f.read_text())
    if "$id" in o: res.append((o["$id"], Resource.from_contents(o)))
reg = Registry().with_resources(res)
schema = json.loads((schemas / "bom-1.6.schema.json").read_text())
UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")

def load(p): return json.loads(Path(p).read_text())
def errors(c): return [e.message for e in Draft7Validator(schema, registry=reg).iter_errors(c)]
def norm_kit(c): return sorted(UUID.sub("<id>", json.dumps({k: v for k, v in x.items() if k != "bom-ref"}, sort_keys=True)) for x in c["components"])
def norm_ours(d):
    """Same rule as validate_pyca.py: drop id and detected_at; compare risk records with asset ids mapped."""
    scan = load(d / "scan.json")["assets"]
    stable = {}
    for a in scan:
        b = {k: v for k, v in a.items() if k not in ("id", "detected_at")}
        b["source"] = dict(b["source"]); b["source"]["file_path"] = b["source"]["file_path"].split("/ext/keycloak/")[-1]
        stable[a["id"]] = json.dumps(b, sort_keys=True)
    risks = []
    for r in load(d / "risk.json"):
        r = dict(r); r.pop("assessed_at", None); r["asset_id"] = stable[r["asset_id"]]; risks.append(json.dumps(r, sort_keys=True))
    return sorted(stable.values()), sorted(risks)

def is_test(path):
    p = "/" + path
    return "/src/test/" in p or p.startswith("/testsuite/") or p.startswith("/tests/") or "/test-framework/" in p

def family(name):
    n = name.upper().replace("_", "-")
    for f, keys in [("RSA", ["RSA"]), ("ECDSA/EC", ["ECDSA", "EC", "ES256", "ES384"]), ("ECDH", ["ECDH"]), ("EdDSA", ["EDDSA", "ED25519", "ED448"]),
                    ("AES", ["AES"]), ("HMAC", ["HMAC"]), ("SHA-1", ["SHA-1", "SHA1"]), ("SHA-2", ["SHA-256", "SHA256", "SHA-384", "SHA384", "SHA-512", "SHA512", "SHA2"]),
                    ("MD5", ["MD5"]), ("TLS", ["TLS"])]:
        if any(n == k or n.startswith(k + "-") or n.startswith(k) for k in keys): return f
    return "other"

k1, k2 = load(k1p), load(k2p)
o1 = load(c1d / "cbom.json")
r = {}
r["schema_errors"] = {"cbomkit_run_1": len(errors(k1)), "cbomkit_run_2": len(errors(k2)), "cryptagion_run_1": len(errors(o1))}
r["repeat_identical"] = {"cbomkit": norm_kit(k1) == norm_kit(k2), "cryptagion": norm_ours(c1d) == norm_ours(c2d)}
r["cbomkit_metadata"] = k1["metadata"].get("properties")

def kit_occ(c):
    out = []
    for comp in c["components"]:
        cp = comp.get("cryptoProperties", {})
        for o in comp.get("evidence", {}).get("occurrences", []):
            out.append({"name": UUID.sub("<id>", comp["name"]), "assetType": cp.get("assetType"), "location": o.get("location"), "line": o.get("line")})
    return out
def our_occ(c):
    out = []
    for comp in c["components"]:
        sc = next((p["value"] for p in comp.get("properties", []) if p["name"] == "cryptagion:source:scope"), None)
        for o in comp.get("evidence", {}).get("occurrences", []):
            out.append({"name": comp["name"], "scope": sc, "location": o.get("location"), "line": o.get("line")})
    return out

K, O = kit_occ(k1), our_occ(o1)
r["cbomkit"] = {"components": len(k1["components"]), "dependencies": len(k1.get("dependencies", [])),
                "asset_types": collections.Counter(c.get("cryptoProperties", {}).get("assetType") for c in k1["components"]),
                "occurrences": len(K), "unique_lines": len({(x["location"], x["line"]) for x in K}),
                "unique_lines_test_paths": len({(x["location"], x["line"]) for x in K if is_test(x["location"])}),
                "algorithm_lines_by_family": collections.Counter(family(x["name"]) for x in {(x["location"], x["line"], x["name"]): x for x in K if x["assetType"] in ("algorithm", "protocol")}.values())}
r["cryptagion"] = {"findings": len(o1["components"]), "by_scope": collections.Counter(x["scope"] for x in O),
                   "unique_lines": len({(x["location"], x["line"]) for x in O}),
                   "by_family": collections.Counter(family(x["name"]) for x in O)}

kl = {(x["location"], x["line"]) for x in K}
ol = {(x["location"], x["line"]) for x in O}
kl_prod = {x for x in kl if not is_test(x[0])}
ol_prod = {(x["location"], x["line"]) for x in O if x["scope"] != "test"}
r["overlap"] = {"lines_both": len(kl & ol), "lines_cbomkit_only": len(kl - ol), "lines_cryptagion_only": len(ol - kl),
                "prod_lines_both": len(kl_prod & ol_prod), "prod_lines_cbomkit_only": len(kl_prod - ol_prod), "prod_lines_cryptagion_only": len(ol_prod - kl_prod)}
kf = {x[0] for x in kl}; of = {x[0] for x in ol}
r["files"] = {"cbomkit": len(kf), "cryptagion": len(of), "both": len(kf & of), "cbomkit_only": len(kf - of), "cryptagion_only": len(of - kf)}
r["lines_both"] = sorted(kl & ol)
r["prod_lines_cbomkit_only"] = sorted(kl_prod - ol_prod)
r["prod_lines_cryptagion_only"] = sorted(ol_prod - kl_prod)
r["test_rule"] = "a path is test code if it contains /src/test/ or starts with testsuite/, tests/ or contains /test-framework/"
outp.write_text(json.dumps(r, indent=1, default=list))
print(json.dumps({k: v for k, v in r.items() if k not in ("lines_both", "prod_lines_cbomkit_only", "prod_lines_cryptagion_only")}, indent=1, default=list))
