import csv, glob, math, os, sys, hashlib
D = sys.argv[1]
G, MS, RS = 6.674e-8, 1.98847e33, 6.957e10
def f(r, k):
    try:
        v = r.get(k, "");  return float(v) if v not in ("", None) else None
    except ValueError: return None
def err(r, k):
    a, b = f(r, k + "err1"), f(r, k + "err2")
    vals = [abs(x) for x in (a, b) if x is not None]
    return sum(vals) / len(vals) if vals else 0.0
csvs = [p for p in glob.glob(os.path.join(D, "*.csv"))]
src = None
for p in csvs:
    with open(p, newline="") as fh:
        h = fh.readline()
    if "pl_ratdor" in h and "default_flag" in h: src = p; break
print("source:", src, hashlib.sha256(open(src, "rb").read()).hexdigest() if src else "-")
if not src: print("EXO-THIRD-KEY fail reason=no-csv-with-pl_ratdor-and-default_flag"); sys.exit(0)
rows = list(csv.DictReader(open(src, newline="")))
print("rows:", len(rows)); print("header:", list(rows[0].keys()) if rows else "-")
from collections import Counter
print("default_flag values:", Counter(r.get("default_flag") for r in rows).most_common(5))
need = [k + e for k in ("pl_orbper", "pl_ratdor", "st_mass", "st_rad") for e in ("", "err1", "err2")]
print("missing columns:", [k for k in need if rows and k not in rows[0]])
print("planets:", len({r.get("pl_name") for r in rows}))
def test(r):
    P, a, M, R = f(r, "pl_orbper"), f(r, "pl_ratdor"), f(r, "st_mass"), f(r, "st_rad")
    eP, ea, eM, eR = err(r, "pl_orbper"), err(r, "pl_ratdor"), err(r, "st_mass"), err(r, "st_rad")
    if None in (P, a, M, R, eP, ea, eM, eR) or min(P, a, M, R) <= 0: return None
    rt = 3 * math.pi * a ** 3 / (G * (P * 86400) ** 2)
    rm = M * MS / (4 / 3 * math.pi * (R * RS) ** 3)
    st = rt * math.hypot(2 * eP / P, 3 * ea / a)
    sm = rm * math.hypot(eM / M, 3 * eR / R)
    d = abs(rt - rm)
    return d / rm > 0.25 and d > 3 * math.hypot(st, sm)
bypl = {}
for r in rows: bypl.setdefault(r.get("pl_name"), []).append(r)
flags, testable = [], 0
cls = {"agrees": 0, "allfail": 0, "single": 0, "notestable": 0}
for pl, rs in bypl.items():
    dflt = [r for r in rs if str(r.get("default_flag", "")).strip().lower() in ("1", "1.0", "true", "t", "yes")]
    if not dflt: continue
    t = test(dflt[0])
    if t is None: continue
    testable += 1
    if not t: continue
    flags.append(pl)
    others = [test(r) for r in rs if r is not dflt[0]]
    tested = [x for x in others if x is not None]
    if not others: cls["single"] += 1
    elif not tested: cls["notestable"] += 1
    elif any(x is False for x in tested): cls["agrees"] += 1
    else: cls["allfail"] += 1
tsvs = sorted(glob.glob(os.path.join(D, "density-flags-*.tsv")))
tf = set()
if tsvs:
    tr = list(csv.DictReader(open(tsvs[-1], newline=""), delimiter="\t"))
    k = "pl_name" if tr and "pl_name" in tr[0] else (list(tr[0].keys())[0] if tr else None)
    tf = {x[k] for x in tr} if k else set()
    print("tsv:", tsvs[-1], "key:", k)
mine = set(flags)
print("only_mine:", sorted(mine - tf)[:40]); print("only_tsv:", sorted(tf - mine)[:40])
print(f"EXO-THIRD-KEY done defaults_testable={testable} flags={len(mine)} tsv_flags={len(tf)} both={len(mine & tf)} only_mine={len(mine - tf)} only_tsv={len(tf - mine)} agrees={cls['agrees']} allfail={cls['allfail']} single={cls['single']} notestable={cls['notestable']}")
