#!/usr/bin/env python3
"""score.py -> results.json: AI tells per 100 words, planted facts kept, new numbers, length. Same fixed list for every arm."""
import json,re,glob,os,statistics as st
HERE=os.path.dirname(os.path.abspath(__file__))
WORDS=r"delve|tapestry|testament|seamless(ly)?|robust|leverag(e|es|ing)|crucial|pivotal|landscape|realm|elevat(e|es)|empower(s|ing)?|unlock|harness|game[- ]changer|cutting[- ]edge|navigat(e|ing)|foster|vibrant|ever[- ]evolving|furthermore|moreover|additionally|ultimately|comprehensive|streamline[ds]?|embark|journey|revolutioni[sz]e|synergy|transformative|groundbreaking|remarkable|myriad|thrilled|excited|blazing[- ]fast|nuanced|fundamentally|deep dive|reimagin\w+"
PHRASES=r"in today's|it's worth noting|it's important to note|in summary|in conclusion|here's what you can expect|ready to|i hope this (email )?finds you well|looking forward to|can't wait|the future of \w+ is|one thing is clear|nothing short of|at the heart of|full potential|what truly matters|new heights|it just works"
CONTRAST=r"\bisn't just\b|\bnot just\b|\bnot only\b|\bit's not about\b"
TELLS={'stock_words':WORDS,'stock_phrases':PHRASES,'not_x_but_y':CONTRAST,'dashes':r"—|–| - ",'bold_labels':r"\*\*[^*\n]{1,40}:\*\*",'exclamations':r"!"}
FACTS={
 'launch':[r"Ledgerly 3\.0",r"\b2 days|two days|to 2\b|to two\b",r"\b9\b|nine",r"94 ?%|94 percent",r"NetSuite",r"Xero",r"QuickBooks",r"SOC 2 Type II",r"\$49",r"March 4|4 March"],
 'study':[r"University of Leeds",r"3,?200",r"14 countries|fourteen countries",r"18 months|eighteen months",r"three days|3 days",r"22 ?%|22 percent",r"twice|2x|two times|double"],
 'email':[r"Maria",r"Calder Logistics",r"Rotterdam",r"Norvik Freight",r"31 ?%|31 percent",r"first quarter|Q1",r"20 minutes|twenty minutes",r"4 hours|four hours",r"15[- ]minute",r"Tuesday",r"Tom Hale"],
 'release':[r"Pipewright 2\.4",r"3\.1 ?x|3\.1 times",r"Node 22",r"Python 3\.13",r"pipewright\.toml",r"YAML",r"3\.0",r"Windows Server 2016"]}
def words(t): return len(re.findall(r"[A-Za-z0-9$%'.-]+",t))
def tells(t):
    lo=t.lower(); out={k:len(re.findall(rx,t if k in('dashes','bold_labels','exclamations') else lo)) for k,rx in TELLS.items()}
    out['total']=sum(out.values()); return out
def nums(t): return set(re.findall(r"\d+(?:[.,]\d+)?",t))
res=[];base={}
for f in glob.glob(HERE+'/drafts/*.md'):
    k=os.path.basename(f)[:-3]; t=open(f).read(); base[k]=dict(words=words(t),tells=tells(t),per100=round(100*tells(t)['total']/words(t),2),bullets=len(re.findall(r'^\s*[-*] ',t,re.M)))
for d in sorted(glob.glob(HERE+'/runs/*-*-*')):
    if not os.path.exists(d+'/time.json'): continue
    name=os.path.basename(d); arm,draft,rep=name.rsplit('-',2)
    meta=json.load(open(d+'/out.json')) if os.path.getsize(d+'/out.json') else {}
    o=d+'/out.md'; r=dict(arm=arm,draft=draft,rep=int(rep),cost=meta.get('total_cost_usd'),turns=meta.get('num_turns'),secs=json.load(open(d+'/time.json'))['secs'],made=os.path.exists(o) and os.path.getsize(o)>0)
    if r['made']:
        t=open(o).read(); src=open(HERE+f'/drafts/{draft}.md').read()
        r['words']=words(t); r['length_ratio']=round(words(t)/base[draft]['words'],2); r['tells']=tells(t); r['per100']=round(100*r['tells']['total']/max(1,words(t)),2)
        miss=[p for p in FACTS[draft] if not re.search(p,t,re.I)]; r['facts_kept']=len(FACTS[draft])-len(miss); r['facts_total']=len(FACTS[draft]); r['facts_missing']=miss
        r['new_numbers']=sorted(nums(t)-nums(src))
        sents=[len(x.split()) for x in re.split(r'(?<=[.!?])\s+|\n+',t) if len(x.split())>=3]
        r['sentence_cv']=round(st.pstdev(sents)/st.mean(sents),2) if len(sents)>1 else 0
        r['bullets']=len(re.findall(r'^\s*[-*] ',t,re.M))
    res.append(r)
json.dump(dict(drafts=base,runs=res),open(HERE+'/results.json','w'),indent=1)
print('drafts per100:',{k:v['per100'] for k,v in base.items()}, 'mean',round(st.mean(v['per100'] for v in base.values()),2))
arms=['plain','humanizer','avoid-ai-writing','ce-noslop','antislop-copywriting','unslop','sloptrim']
print(f"{'arm':22} n  per100  tells  facts      lenratio cost   secs newnums")
for a in arms:
    q=[x for x in res if x['arm']==a and x['made']]
    if not q: continue
    print(f"{a:22} {len(q):<2} {st.mean(x['per100'] for x in q):6.2f} {sum(x['tells']['total'] for x in q):5}  {sum(x['facts_kept'] for x in q)}/{sum(x['facts_total'] for x in q):<6} {st.median(x['length_ratio'] for x in q):5.2f}  {sum(x['cost'] or 0 for x in q):.3f} {st.median(x['secs'] for x in q):5} {sum(len(x['new_numbers']) for x in q)}")

print('draft bullets',sum(v['bullets'] for v in base.values()),'draft tells',sum(v['tells']['total'] for v in base.values()))
for a in arms:
    q=[x for x in res if x['arm']==a and x['made']]
    cat={k:sum(x['tells'][k] for x in q) for k in TELLS}
    print(f"{a:22} cv {st.mean(x['sentence_cv'] for x in q):.2f} bullets {sum(x['bullets'] for x in q)} turns {st.median(x['turns'] for x in q)} words {st.median(x['words'] for x in q)}",cat)
