"""logs/*.jsonl を1行ずつ読み、1周(=モデル呼び出し)ごとの表と、runごとの要約を出す。"""
import json, glob, os, sys

def load(path):
    return [json.loads(l) for l in open(path)]

def laps(events):
    """assistantメッセージをmessage.idでまとめて「モデル呼び出し1回=1周」にする。"""
    out, order = {}, []
    for e in events:
        if e["type"] != "assistant":
            continue
        m = e["message"]
        if m["usage"]["input_tokens"] + m["usage"]["cache_read_input_tokens"] + m["usage"]["cache_creation_input_tokens"] == 0:
            continue  # /goal が最初に出す "Goal set" の合成メッセージ(APIは呼んでいない)
        if m["id"] not in out:
            out[m["id"]] = {"tools": [], "text": False, "usage": m["usage"]}
            order.append(m["id"])
        for b in m["content"]:
            if b["type"] == "tool_use":
                out[m["id"]]["tools"].append(b["name"])
            elif b["type"] == "text":
                out[m["id"]]["text"] = True
    return [out[i] for i in order]

def feedbacks(events):
    n = 0
    for e in events:
        if e["type"] == "user" and isinstance(e["message"]["content"], list):
            if any(b.get("type") == "text" and b["text"].startswith("Stop hook feedback") for b in e["message"]["content"]):
                n += 1
    return n

def total_in(u):
    return u["input_tokens"] + u["cache_read_input_tokens"] + u["cache_creation_input_tokens"]

rows = {}
for p in sorted(glob.glob(os.path.join(os.path.dirname(__file__), "logs", "*.jsonl"))):
    if "-r" in os.path.basename(p):  # outer-<n>-r<周>.jsonl は下で束ねる
        continue
    ev = load(p)
    res = [e for e in ev if e["type"] == "result"][0]
    ls = laps(ev)
    name = os.path.basename(p)[:-6]
    final = open(p[:-6] + ".final.txt").read().strip().replace("\n", " / ")
    rows[name] = {
        "model_calls": len(ls),
        "tool_calls": sum(len(l["tools"]) for l in ls),
        "tool_sequence": [",".join(l["tools"]) if l["tools"] else "(text only)" for l in ls],
        "input_tokens_per_call": [total_in(l["usage"]) for l in ls],
        "stop_hook_feedbacks": feedbacks(ev),
        "num_turns": res["num_turns"],
        "cost_usd": round(res["total_cost_usd"], 4),
        "subtype": res["subtype"],
        "final_state": final,
    }
# 外側のループ: シェルが呼び直した周ごとの新しいセッションを束ねる
for n in sorted({os.path.basename(p).split("-")[1] for p in glob.glob(os.path.join(os.path.dirname(__file__), "logs", "outer-*-r*.jsonl"))}):
    rounds = sorted(glob.glob(os.path.join(os.path.dirname(__file__), "logs", f"outer-{n}-r*.jsonl")))
    per, sessions, cost = [], set(), 0.0
    for p in rounds:
        ev = load(p)
        res = [e for e in ev if e["type"] == "result"][0]
        ls = laps(ev)
        sessions.add(res["session_id"])
        cost += res["total_cost_usd"]
        per.append({"model_calls": len(ls), "tool_calls": sum(len(l["tools"]) for l in ls)})
    final = open(os.path.join(os.path.dirname(__file__), "logs", f"outer-{n}.final.txt")).read().strip().replace("\n", " / ")
    rows[f"outer-{n}"] = {"rounds": len(rounds), "distinct_sessions": len(sessions), "per_round": per,
                         "model_calls": sum(x["model_calls"] for x in per), "cost_usd": round(cost, 4), "final_state": final}
json.dump(rows, open(os.path.join(os.path.dirname(__file__), "summary.json"), "w"), ensure_ascii=False, indent=1)
for k, v in rows.items():
    print(k, {a: b for a, b in v.items() if a not in ("tool_sequence", "input_tokens_per_call")})
