#!/usr/bin/env python3
"""Copy Ollama's own log lines for each repeat-check.py run out beside that run's answers.

The answers alone cannot show what Ollama did. Its server log can: how many prompt tokens the
model runner it launched processes at once (-b), and whether a request worked the prompt out
fresh or restored it from the cache of an earlier one. This splits a private server's log into
one file per run, keeping only those lines, with the home folder replaced by ~.

    python3 -B runner-log.py SERVER.log RUN_FOLDER [RUN_FOLDER ...]

A run folder is either repeat-check.py's own (results.csv, answer-NN.html) or a folder of
run-NN/ folders, one repeat-check.py --n 1 run each. Every request the server log holds must
belong to one of the runs given, in time order, or nothing is written.
"""
import csv
import datetime as dt
import os
import re
import sys

KEEP = re.compile(r"llama_context: n_(u?)batch|new prompt|restored context checkpoint|cached n_tokens = ")


def runs_in(folder):
    """(started, log path) for every run in a folder, in the order they ran."""
    if os.path.exists(os.path.join(folder, "results.csv")):
        rows = list(csv.DictReader(open(os.path.join(folder, "results.csv"), encoding="utf-8")))
        return [(dt.datetime.fromisoformat(r["started"]),
                 os.path.join(folder, f"ollama-log-{int(r['run']):02d}.txt")) for r in rows]
    out = []
    for d in sorted(x for x in os.listdir(folder) if re.fullmatch(r"run-\d\d", x)):
        (r,) = csv.DictReader(open(os.path.join(folder, d, "results.csv"), encoding="utf-8"))
        out.append((dt.datetime.fromisoformat(r["started"]), os.path.join(folder, d, "ollama-log.txt")))
    return out


def main():
    log, folders = sys.argv[1], sys.argv[2:]
    home = os.path.expanduser("~")
    lines = [l.rstrip("\n").replace(home, "~") for l in open(log, encoding="utf-8", errors="replace")]
    launches = [i for i, l in enumerate(lines) if 'msg="starting llama-server"' in l]
    assert launches, "no model runner was launched in this log"
    tasks = []       # (launch line index, first line, last line) for every request, in order
    for n, a in enumerate(launches):
        b = launches[n + 1] if n + 1 < len(launches) else len(lines)
        starts = [i for i in range(a, b) if "| new prompt," in lines[i]]
        for k, s in enumerate(starts):
            tasks.append((a, s, starts[k + 1] if k + 1 < len(starts) else b))
    runs = sorted(r for f in folders for r in runs_in(f))
    assert len(runs) == len(tasks), f"{len(tasks)} requests in the log, {len(runs)} runs given"
    stamp = lambda i: dt.datetime.fromisoformat(re.match(r"time=(\S+?)\.\d+", lines[i]).group(1))
    seen = set()
    for (started, path), (a, s, e) in zip(runs, tasks):
        first = a not in seen
        seen.add(a)
        if first:
            gap = (stamp(a) - started).total_seconds()
            assert -5 <= gap <= 120, f"{path}: runner launched {gap:.0f} s from the run's start"
        else:
            assert stamp(a) <= started, f"{path}: its runner was launched after it started"
        ctx = [l for l in lines[a:s] if KEEP.search(l) and "llama_context" in l]
        body = [l for l in lines[s:e] if KEEP.search(l)]
        with open(path, "w", encoding="utf-8") as fh:
            fh.write("# Ollama's log for this run, copied by runner-log.py; home folder replaced by ~\n")
            fh.write(("# this request made Ollama launch the model runner:\n" if first else
                      "# the model runner was already running, launched for an earlier run:\n"))
            fh.write(lines[a] + "\n" + "\n".join(ctx + body) + "\n")
        print(f"{path}: {'launched' if first else 'already loaded'}, "
              f"{'restored from cache' if any('restored context checkpoint' in l for l in body) else 'fresh'}")


if __name__ == "__main__":
    main()
