# Usage: python3 thread-ages.py <ref> <out.json>. Follows every lines/*.md through its git history and records,
# for each thread (keyed on its first 35 normalised characters), the number of ### marks on the line when it
# first appeared and when it was ticked. A reworded opening counts as a new thread. Written for
# lines/practices-for-swarms.md, pass of 2026-11-28 (thread ages).
import subprocess, re, sys, collections, json
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] if len(sys.argv) > 1 else "HEAD"
def git(*a): return subprocess.run(["git",*a],capture_output=True,text=True).stdout
files = [f for f in git("ls-tree","--name-only",REF,"lines/").split() if f.endswith(".md") and not f.endswith("README.md")]
HEAD_RE = re.compile(r"^### (\d{4}-\d{2}-\d{2}) \| ([^|]+) \| (\w+)", re.M)
TH_RE = re.compile(r"^- \[( |x)\] (.*)$", re.M)
def key(t): return re.sub(r"\W+"," ",t.lower())[:35]
out = {}
for f in files:
    commits = git("log","--reverse","--format=%H %aI",REF,"--",f).split("\n")
    commits = [c.split() for c in commits if c]
    seen = {}  # key -> dict(intro_marks, intro_time, tick_marks, tick_time, last_state, text)
    marks_hist = []
    for h,t in commits:
        body = git("show",f"{h}:{f}")
        if not body: continue
        marks = HEAD_RE.findall(body)
        n = len(marks)
        kinds = collections.Counter(k for _,_,k in marks)
        threads = {key(x):(s,x) for s,x in TH_RE.findall(body)}
        for k,(s,x) in threads.items():
            d = seen.setdefault(k, dict(intro_marks=n, intro=t, tick_marks=None, tick=None, state=s, text=x, present=True))
            if s=="x" and d["tick"] is None and d["state"]!="x":
                d["tick_marks"]=n; d["tick"]=t
            if s=="x" and d["state"]=="x" and d["tick"] is None and d["intro"]==t:
                d["tick_marks"]=n; d["tick"]=t; d["born_ticked"]=True
            d["state"]=s; d["present"]=True
        for k,d in seen.items():
            if k not in threads: d["present"]=False
        final_n, final_kinds, final_t = n, kinds, t
    out[f]=dict(marks=final_n, kinds=dict(final_kinds), threads=seen, commits=len(commits))
json.dump(out, open(sys.argv[2],"w"), indent=1, default=str)
