#!/usr/bin/env python3
"""Join two decls.tsv files (audited export vs pristine Mathlib export) by declaration name."""
import sys, collections
a_path, b_path, out_prefix = sys.argv[1], sys.argv[2], sys.argv[3]
def load(p):
    d = {}
    with open(p, encoding="utf-8") as f:
        hdr = f.readline().rstrip("\n").split("\t")
        for line in f:
            r = line.rstrip("\n").split("\t")
            d[r[3]] = r
    return d
A = load(a_path); B = load(b_path)
ident = differ_core = differ_strict_only = absent = 0
kinds_ident = collections.Counter(); kinds_absent = collections.Counter()
cone_ident = cone_absent = cone_differ = 0
diff_rows = []; absent_rows = []
for name, r in A.items():
    kind = r[2]; in_meaning = r[9] == "1"
    b = B.get(name)
    if b is None:
        absent += 1; kinds_absent[kind] += 1; absent_rows.append(r)
        if in_meaning: cone_absent += 1
        continue
    if b[4] == r[4] and b[5] == r[5] and b[2] == kind:
        ident += 1; kinds_ident[kind] += 1
        if in_meaning: cone_ident += 1
    else:
        if b[5] == r[5] and b[2] == kind: differ_strict_only += 1
        else: differ_core += 1
        diff_rows.append((r, b))
        if in_meaning: cone_differ += 1
print(f"declarations in audited export : {len(A)}")
print(f"declarations in pristine export: {len(B)}")
print(f"  identical to pristine: {ident}   {dict(kinds_ident)}")
print(f"  same name but DIFFERENT content: {differ_core}  (differ only in hints/'all' metadata: {differ_strict_only})")
print(f"  not present in pristine Mathlib (= the project's own): {absent}   {dict(kinds_absent)}")
print(f"meaning cone of the statement: identical={cone_ident} different={cone_differ} project-own={cone_absent}")
with open(out_prefix + ".differ.tsv", "w", encoding="utf-8") as f:
    for r, b in diff_rows: f.write("\t".join(r) + "\t||\t" + "\t".join(b) + "\n")
with open(out_prefix + ".own.tsv", "w", encoding="utf-8") as f:
    for r in absent_rows: f.write("\t".join(r) + "\n")
