"""Count explicit correspondence edges with source hashes, without inferring trust."""
from collections import Counter
from email import policy
from email.parser import BytesParser
from email.utils import getaddresses
import hashlib
import json


def correspondence_graph(messages):
    edges, evidence = Counter(), []
    for index, raw in enumerate(messages):
        message = BytesParser(policy=policy.default).parsebytes(raw)
        senders = [address.lower() for _, address in getaddresses(message.get_all("From", [])) if address]
        recipients = {address.lower() for _, address in getaddresses(
            message.get_all("To", []) + message.get_all("Cc", [])) if address}
        if len(senders) != 1:
            evidence.append({"index": index, "sha256": hashlib.sha256(raw).hexdigest(),
                             "status": "ambiguous_sender"})
            continue
        for recipient in sorted(recipients):
            edges[(senders[0], recipient)] += 1
        evidence.append({"index": index, "sha256": hashlib.sha256(raw).hexdigest(),
                         "status": "parsed", "from": senders[0], "to": sorted(recipients)})
    return {"edges": [{"from": sender, "to": recipient, "messages": count}
                      for (sender, recipient), count in sorted(edges.items())],
            "evidence": evidence}


def replay():
    messages = [
        b"From: curator@example.invalid\nTo: researcher@example.invalid\nCc: researcher@example.invalid\n\nOWNED FIXTURE A",
        b"From: researcher@example.invalid\nTo: curator@example.invalid\n\nOWNED FIXTURE B",
        b"From: first@example.invalid, second@example.invalid\nTo: curator@example.invalid\n\nAMBIGUOUS",
    ]
    result = correspondence_graph(messages)
    assert len(result["edges"]) == 2
    assert all(edge["messages"] == 1 for edge in result["edges"])
    assert result["evidence"][2]["status"] == "ambiguous_sender"
    assert result["evidence"][0]["sha256"] == hashlib.sha256(messages[0]).hexdigest()
    assert correspondence_graph([]) == {"edges": [], "evidence": []}
    return {"assertions": 5, "result": result,
            "scope": "Synthetic supplied messages. Headers are claims, not authenticated identities or proof of trust."}


if __name__ == "__main__":
    print(json.dumps(replay(), indent=2))
