#!/usr/bin/env python3
"""Compares measured read lengths with words / wpm * 60. Usage: python3 analyze.py <texts-folder> <measured.tsv> <calc-results.tsv>"""
import sys, os, math
if len(sys.argv) != 4:
    print("usage: python3 analyze.py <texts-folder> <measured.tsv> <calc-results.tsv>", file=sys.stderr); sys.exit(2)
tdir, mfile, cfile = sys.argv[1:]
words = {}
for f in sorted(os.listdir(tdir)):
    if f.endswith(".txt"):
        words[f[:-4]] = len(open(os.path.join(tdir, f), encoding="utf-8").read().replace("\r", "").split())
print("WORDS (whitespace-separated tokens, same as wc -w)")
for k, v in words.items(): print(f"  {k}: {v}")
meas = {}
for line in open(mfile, encoding="utf-8"):
    n, whole, trim = line.rstrip("\n").split("\t")
    t, r = n.rsplit(".", 1)[0].split("__")
    meas[(t, r)] = (float(whole), float(trim))
readers = sorted({r for _, r in meas}, key=lambda r: meas[("C", r)][0], reverse=True)
print("\nMEASUREMENT: figures use column 2 (whole file length); column 3 (first to last sound) failed on %d of %d files" % (sum(1 for v in meas.values() if v[0]-v[1] > 0.05), len(meas)))
print("\nCONTROL: tone 10 s with 2 s silence before and 3 s after (file 15.000 s)")
for line in open(os.path.join(os.path.dirname(mfile) or ".", "ctl.tsv")):
    n, w, tr = line.split("\t"); print(f"  file {w.strip()} s, first-to-last-sound {tr.strip()} s (known sound length 10.0; the method keeps up to 0.3 s of the trailing silence): {'PASS' if 10.0 <= float(tr) <= 10.35 else 'FAIL'}")
print("\nPACE of each synthetic reader, measured on script C (words / file seconds * 60)")
pace = {}
for r in readers:
    pace[r] = words["C"] / meas[("C", r)][0] * 60
    print(f"  {r}: {words['C']} words in {meas[('C', r)][0]:.3f} s = {pace[r]:.1f} wpm")
print("\nPREDICTED vs MEASURED seconds (prediction = words / pace measured on C * 60; error = (measured - predicted) / predicted)")
print("  text\twords\treader\tpace_wpm\tpredicted_s\tmeasured_s\terror_pct")
errs = {}
for t in ["A", "B", "B-written", "B-spoken", "B-spoken-twice"]:
    for r in readers:
        p = words[t] / pace[r] * 60; m = meas[(t, r)][0]; e = (m - p) / p * 100
        errs.setdefault(t, []).append(e)
        print(f"  {t}\t{words[t]}\t{r}\t{pace[r]:.1f}\t{p:.2f}\t{m:.2f}\t{e:+.1f}")
print("\nERROR RANGE per text across the 5 readers (percent)")
for t, v in errs.items(): print(f"  {t}: {min(v):+.1f} to {max(v):+.1f}")
print("\nTHE URL AND CODE: seconds added to B (60 words) by the call to action")
print("  reader\tcta_form\twords_added\tadded_s\tseconds_if_at_reader_pace\tratio")
for r in readers:
    b = meas[("B", r)][0]
    for t in ["B-written", "B-spoken", "B-spoken-twice"]:
        wa = words[t] - words["B"]; add = meas[(t, r)][0] - b; at = wa / pace[r] * 60
        print(f"  {r}\t{t}\t{wa}\t{add:.2f}\t{at:.2f}\t{add/at:.2f}")
print("\nCALCULATOR (live page) vs our arithmetic: words, wpm, target s -> calculator length | words that fit | difference; ours = round(words/wpm*60) and round(target*wpm/60)")
ok = 0; n = 0
def fmt(s):
    s = int(s); return f"{s//60}m {s%60}s" if s >= 60 else f"{s}s"
for line in open(cfile, encoding="utf-8"):
    w, wpm, tg, ln, fit, df = line.rstrip("\n").split("\t")
    w, wpm, tg = float(w), float(wpm), float(tg)
    sec = int(math.floor(w / wpm * 60 + 0.5)); fitn = int(math.floor(tg * wpm / 60 + 0.5))
    good = fmt(sec) == ln and str(fitn) == fit
    n += 1; ok += good
    print(f"  {w:g}, {wpm:g}, {tg:g}: calculator {ln} | {fit} | {df}; ours {fmt(sec)} | {fitn}: {'MATCH' if good else 'DIFF'}")
print(f"  {ok} of {n} rows match")
print("\nWORDS PER SLOT (our arithmetic, rounded DOWN: floor(seconds * wpm / 60))")
print("  slot_s\t120\t130\t150\t170\t180")
for s in (15, 30, 60): print("  " + str(s) + "\t" + "\t".join(str(int(s * w // 60)) for w in (120, 130, 150, 170, 180)))
print("\nPUBLISHED WORD COUNTS expressed as pace (words / 30 s * 60)")
for name, lo, hi in (("Spotify Ads 60-90 words for 30 s", 60, 90), ("Acast 65-75 words for 30 s", 65, 75)):
    print(f"  {name}: {lo/30*60:.0f} to {hi/30*60:.0f} wpm")
print("\nWORD BUDGET after the spelled-out URL and code line (our arithmetic: words per slot minus words in the line)")
print("  slot_s\twpm\twords_fit\tminus_18_once\tminus_34_twice\twith_10pct_free(floor(0.9*fit))\tminus_18_once\tminus_34_twice")
for s in (15, 30, 60):
    for w in (130, 150):
        f = int(s * w // 60); g = int(f * 0.9); print(f"  {s}\t{w}\t{f}\t{f-18}\t{f-34}\t{g}\t{g-18}\t{g-34}")
print("\nSECONDS THE SPELLED-OUT LINE TOOK (measured: B-spoken minus B, and B-spoken-twice minus B), across the 5 readers")
for t in ("B-spoken", "B-spoken-twice"):
    v = [meas[(t, r)][0] - meas[("B", r)][0] for r in readers]
    print(f"  {t}: {min(v):.2f} to {max(v):.2f} s")
print("\nPOSITION vs the 30 s slot at the 148.0 wpm reader (alex-r80), measured seconds")
for t in ("B", "B-written", "B-spoken", "B-spoken-twice"):
    m = meas[(t, "alex-r80")][0]; print(f"  {t} ({words[t]} words): {m:.2f} s, {'inside' if m <= 30 else 'over'} 30 s by {abs(30-m):.2f} s")
print("\nSHORT READ vs the 15 s slot (script A, 32 words), measured seconds")
for r in readers: print(f"  {r}: {meas[('A', r)][0]:.2f} s, {'inside' if meas[('A', r)][0] <= 15 else 'over'} 15 s")
