#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Verificateur de la chaine du journal temoin LANXAS AI Black.
Recalcule H_n = SHA256( UTF8(H_(n-1)) || UTF8(canonical_json(E_n)) ) et compare.
Canonicalisation : json.dumps(sort_keys=True, separators=(',',':'), ensure_ascii=False).
H_0 = 64 x '0'. Le champ 'event_hash' est EXCLU du calcul (il porte H_n lui-meme).
Usage : python verify_journal.py journal-temoin-black.jsonl
Sortie : OK/ECHEC par entree + tete finale ; code de sortie 0 si chaine valide."""
import hashlib, json, sys

def canonical(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False)

def sh(t):
    return hashlib.sha256(t.encode("utf-8")).hexdigest()

def main(path):
    H = "0" * 64
    n_ok = 0
    n_entries = 0
    with open(path, encoding="utf-8") as f:
        for ligne in f:
            ligne = ligne.strip()
            if not ligne:
                continue
            obj = json.loads(ligne)
            if not (isinstance(obj, dict) and "E" in obj and "H" in obj):
                continue  # ligne de specification, ignoree (hors chaine)
            n_entries += 1
            E = obj["E"]
            E_calc = {k: v for k, v in E.items() if k != "event_hash"}
            Hn = sh(H + canonical(E_calc))
            ok = (Hn == obj["H"])
            if "previous_hash" in E:
                ok = ok and (E["previous_hash"] == H)
            if "event_hash" in E:
                ok = ok and (E["event_hash"] == Hn)
            seq = E.get("sequence", obj.get("entree"))
            etype = E.get("event_type", "?")
            print("[%s] entree %s (%s) attendu=%s calcule=%s" %
                  ("OK" if ok else "ECHEC", seq, etype, obj["H"][:16], Hn[:16]))
            if not ok:
                print("  -> CHAINE ROMPUE a l'entree", seq)
                return 2
            n_ok += 1
            H = Hn
    print("---")
    print("Entrees validees : %d/%d" % (n_ok, n_entries))
    print("Tete de chaine finale :", H)
    return 0

if __name__ == "__main__":
    p = sys.argv[1] if len(sys.argv) > 1 else "journal-temoin-black.jsonl"
    sys.exit(main(p))
