# How many words of each hook line come from the template text and how many from the fill. Reads hooks.ts templates, the tool output and the fill list.
import json, re, statistics as st
src = open('hooks.ts').read()
tpls = re.findall(r"^\s+'((?:[^'\\]|\\.)*)',?\s*$", src, re.M)
tpls = [t for t in tpls if '{' in t or len(t.split()) > 2]
print('templates parsed', len(tpls))
assert len(tpls) == 30
def words(t): return len([w for w in re.split(r'\s+', t) if re.search(r'[A-Za-z0-9]', w)])
d = json.load(open('hooks-analysed.json'))
fills = {'default': dict(topic='podcasting', audience='new creators', n='3', result='my first 1,000 listeners'),
         'meal-prep': dict(topic='meal prep', audience='busy parents', n='5', result='ten free hours a week'),
         'video-editing': dict(topic='video editing', audience='beginners', n='3', result='a clean 30 second edit')}
stat_w, fill_w = [], []
bad = 0
for r in d:
    t = tpls[r['i']]; f = fills[r['fill']]
    stat = words(re.sub(r'\{\w+\}', '', t))
    filled = words(t.replace('{topic}', f['topic']).replace('{audience}', f['audience']).replace('{n}', f['n']).replace('{result}', f['result']))
    if filled != r['w']: bad += 1
    r['static'] = stat; r['fillw'] = r['w'] - stat
    stat_w.append(stat); fill_w.append(r['fillw'])
print('own rebuild of the filled line matches the tool word count on', len(d) - bad, 'of', len(d))
print('words from template text: median %g min %d max %d' % (st.median(stat_w), min(stat_w), max(stat_w)))
print('words from your fill: median %g min %d max %d' % (st.median(fill_w), min(fill_w), max(fill_w)))
for f in fills:
    g = [r for r in d if r['fill'] == f]
    print(f, 'fill words total per line median', st.median([r['fillw'] for r in g]), 'static median', st.median([r['static'] for r in g]))
# no-placeholder-only: shortest template text
print('templates with most static words:', max(stat_w), '; fewest:', min(stat_w))
# per kind median seconds & words, for the chart
kinds = ['Question']*4+['Mistake']*4+['Number']*4+['Result first']*4+['Contrarian']*4+['Story']*4+['Curiosity']*6
out = {}
for k in dict.fromkeys(kinds):
    g = [r for r in d if kinds[r['i']] == k]
    ws = [r['w'] for r in g]
    out[k] = dict(n=len(g), wmin=min(ws), wmed=st.median(ws), wmax=max(ws), smin=round(min(ws)/155*60, 2), smed=round(st.median(ws)/155*60, 2), smax=round(max(ws)/155*60, 2))
    print(k, out[k])
json.dump(out, open('kind-stats.json', 'w'))
