# Usage: python3 marks-and-ticks.py <ref>. For each commit that appends ### marks to an existing line file,
# counts threads ticked and threads added in that same commit, and the words of the new marks. Commits that
# create a line, or that reorder its marks (merges), are not counted. Written for lines/practices-for-swarms.md.
import subprocess, re, sys, collections
if subprocess.run(["git","rev-parse","--is-shallow-repository"],capture_output=True,text=True).stdout.strip()=="true":
    sys.exit("shallow clone: counts would measure the clone, not the history; run git fetch --unshallow first")
REF=sys.argv[1]
def git(*a): return subprocess.run(["git",*a],capture_output=True,text=True).stdout
HR=re.compile(r"^### (\d{4}-\d{2}-\d{2}) \| ([^|]+) \| (\w+)\s*$", re.M)
TR=re.compile(r"^- \[( |x)\] (.*)$", re.M)
k=lambda t: re.sub(r"\W+"," ",t.lower())[:35]
rows=[]
for f in [f for f in git("ls-tree","--name-only",REF,"lines/").split() if f.endswith(".md") and "README" not in f]:
    prev=None
    for h in git("log","--reverse","--format=%H",REF,"--",f).split():
        b=git("show",f"{h}:{f}")
        heads=[m.group(3) for m in HR.finditer(b)]
        th={k(x):s for s,x in TR.findall(b)}
        if prev is not None:
            ph,pth=prev
            new=heads[len(ph):] if heads[:len(ph)]==ph else []
            ticks=sum(1 for kk,s in th.items() if s=="x" and pth.get(kk)==" ")
            added=sum(1 for kk in th if kk not in pth)
            # words of new marks
            if new:
                parts=HR.split(b)
                # last len(new) sections
                secs=re.split(r"^### .*$", b, flags=re.M)[-len(new):]
                words=sum(len(s.split()) for s in secs)
                rows.append((f,new,ticks,added,words))
        prev=(heads,th)
P=[r for r in rows if "pass" in r[1]]; R=[r for r in rows if r[1]==["reading"]]
import statistics as st
def summ(name,X):
    if not X: return
    print(name,"n",len(X),"with>=1 tick",sum(1 for r in X if r[2]),"ticks",sum(r[2] for r in X),"threads added",sum(r[3] for r in X),"median words",st.median(r[4] for r in X),"min",min(r[4] for r in X),"max",max(r[4] for r in X))
summ("passes",P); summ("readings",R); summ("all",rows)
print("pass words quartiles", st.quantiles([r[4] for r in P],n=4))
