#!/usr/bin/env python3
"""Measure the Fable-signature metrics on a single subagent transcript (RED/GREEN oracle)."""
import json, sys, statistics

SELF = ("i'll", "let me", "i will", "let's", "i'm going to", "i can ", "i'd ", "i am going", "i'm going", "now i", "first, i", "i need to", "i should")

f = sys.argv[1]
text_blocks = tool_blocks = prose_msgs = asst = selfopen = 0
words, openers = [], []
for line in open(f, errors="ignore"):
    try:
        o = json.loads(line)
    except Exception:
        continue
    m = o.get("message") or {}
    if m.get("role") != "assistant":
        continue
    asst += 1
    c = m.get("content")
    if not isinstance(c, list):
        continue
    msg_text = ""
    for b in c:
        if not isinstance(b, dict):
            continue
        if b.get("type") == "text":
            text_blocks += 1
            msg_text += b.get("text", "")
        elif b.get("type") == "tool_use":
            tool_blocks += 1
    if msg_text.strip():
        prose_msgs += 1
        words.append(len(msg_text.split()))
        first = msg_text.strip().split("\n")[0]
        openers.append(first[:70])
        if msg_text.lower().lstrip().startswith(SELF):
            selfopen += 1

ttr = tool_blocks / (text_blocks or 1)
print(f"file: {f.split('/')[-1]}")
print(f"assistant msgs : {asst}")
print(f"tool blocks    : {tool_blocks}")
print(f"text blocks    : {text_blocks}")
print(f"tool:text ratio: {ttr:.2f}   (Fable target ~5.0, ungoverned Opus ~1.4)")
print(f"prose-emission : {100*prose_msgs/(asst or 1):.1f}%   (Fable ~10%, Opus ~32%)")
print(f"self-opener %  : {100*selfopen/(prose_msgs or 1):.1f}%   (lower = result-first)")
if words:
    print(f"median words   : {int(statistics.median(words))}   mean {sum(words)/len(words):.0f}")
print("first lines of each prose msg:")
for o in openers:
    print(f"   • {o}")
