"""Run with Python 3. Invented manifests; no CRM calls or customer data."""
import copy
import hashlib
import json
from collections import Counter

def version(identity, document, ordinal, text):
    return dict(id=identity, document=document, ordinal=ordinal,
                sha256=hashlib.sha256(text.encode()).hexdigest())
source=[version("A1","A",1,"draft"), version("A2","A",2,"signed"),
        version("A3","A",3,"amended"),version("B1","B",1,"draft"),
        version("B2","B",2,"approved"),version("C1","C",1,"signed")]
current={"A":"A3","B":"B2","C":"C1"}
def reconcile(rows, pointers):
    errors=[]
    for original in source:
        found=[r for r in rows if r["id"]==original["id"]]
        if len(found)!=1:
            errors.append(dict(id=original["id"], fields=["identity_count"]))
        else:
            fields=[f for f in ("document","ordinal","sha256") if found[0][f]!=original[f]]
            if fields: errors.append(dict(id=original["id"],fields=fields))
    extra=sorted(set(r["id"] for r in rows)-set(r["id"] for r in source))
    wrong_pointers=sorted(k for k in set(current)|set(pointers) if pointers.get(k)!=current.get(k))
    return dict(version_count=len(rows),document_count=len(set(r["document"] for r in rows)),
                hash_multiset_equal=Counter(r["sha256"] for r in rows)==Counter(r["sha256"] for r in source),
                errors=errors,extra_ids=extra,wrong_current=wrong_pointers,
                passed=not(errors or extra or wrong_pointers))
broken=copy.deepcopy(source)
broken[0]["document"],broken[3]["document"]="B","A"
broken[1]["sha256"],broken[2]["sha256"]=broken[2]["sha256"],broken[1]["sha256"]
broken[4]["ordinal"]=1
bad_current=dict(current,A="A2")
print(json.dumps(dict(expected_versions=6,expected_documents=3,
                     baseline=reconcile(source,current),damaged=reconcile(broken,bad_current)),indent=2))
