#!/usr/bin/env python3
"""Read the typing lines Notesmith for Mac writes to its own performance log.

Notesmith times every key you type in a note, from the moment macOS stamps the key
event to the end of the pass that draws it, and writes one summary line for every 200
keys. A line holds counts and durations only, never a character, a key code or a note.
This script lists those lines, grouped by the build that wrote them.

    python3 typing-lines.py                      # your log, every build
    python3 typing-lines.py --csv > typing.csv   # the same, as a spreadsheet
    python3 typing-lines.py PATH/performance.log # a log you copied somewhere

Standard library only. It reads the log and changes nothing.
"""
import argparse
import csv
import os
import re
import sys

# Notesmith for Mac is sandboxed, so its log is inside its container.
DEFAULT_LOG = os.path.expanduser(
    "~/Library/Containers/com.langberg.privatenote/Data/Library/Application Support/"
    "PrivateNote/performance.log")

LAUNCH = re.compile(r"^(\S+)\s+launch (\S+) \((\d+)\)")
TYPING = re.compile(
    r"^(\S+)\s+typing · (\d+) keys · p50 (\d+)ms p95 (\d+)ms max (\d+)ms · (\d+) over 50ms"
    r"(?: · load ([\d.]+))?")
HANG = re.compile(r"^(\S+)\s+HANG (\d+)ms\s+@ (.*?)(?: · load ([\d.]+))?$")

COLUMNS = ["build", "utc", "keys", "p50_ms", "p95_ms", "max_ms", "over_50ms", "load"]


def read(path):
    """Yield (kind, row) for each launch, typing and hang line, in file order."""
    build = "before the first launch line"
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            line = line.rstrip("\n")
            m = LAUNCH.match(line)
            if m:
                build = f"{m.group(2)} ({m.group(3)})"
                yield "launch", {"build": build, "utc": m.group(1)}
                continue
            m = TYPING.match(line)
            if m:
                yield "typing", {"build": build, "utc": m.group(1), "keys": int(m.group(2)),
                                 "p50_ms": int(m.group(3)), "p95_ms": int(m.group(4)),
                                 "max_ms": int(m.group(5)), "over_50ms": int(m.group(6)),
                                 "load": m.group(7) or ""}
                continue
            m = HANG.match(line)
            if m:
                yield "hang", {"build": build, "utc": m.group(1), "ms": int(m.group(2)),
                               "where": m.group(3), "load": m.group(4) or ""}


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("log", nargs="?", default=DEFAULT_LOG, help="a performance.log (default: Notesmith's own)")
    ap.add_argument("--csv", action="store_true", help="write the typing lines as CSV")
    ap.add_argument("--since", default="", help="only lines from this UTC date on, like 2026-11-04")
    args = ap.parse_args()
    if not os.path.exists(args.log):
        sys.exit(f"no log at {args.log}. Notesmith writes one once you have typed in a note.")

    rows = [(k, r) for k, r in read(args.log) if r["utc"] >= args.since]
    typing = [r for k, r in rows if k == "typing"]
    if args.csv:
        w = csv.DictWriter(sys.stdout, fieldnames=COLUMNS, lineterminator="\n")
        w.writeheader()
        w.writerows(typing)
        return

    if not typing:
        sys.exit("the log has no typing lines yet. A line is written for every 200 keys typed in a note.")
    current = None
    for kind, r in rows:
        if kind == "typing":
            if r["build"] != current:
                current = r["build"]
                print(f"\nNotesmith {current}")
                print(f"  {'UTC':<21}{'keys':>5}{'p50':>8}{'p95':>8}{'max':>8}{'over 50':>9}{'load':>7}")
            print(f"  {r['utc']:<21}{r['keys']:>5}{r['p50_ms']:>6}ms{r['p95_ms']:>6}ms{r['max_ms']:>6}ms"
                  f"{r['over_50ms']:>9}{r['load']:>7}")
    hangs = [r for k, r in rows if k == "hang" and "typing" in r["where"]]
    if hangs:
        print(f"\n{len(hangs)} time(s) the main thread was blocked for 300 ms or more while you typed:")
        for r in hangs:
            print(f"  {r['utc']}  {r['ms']} ms  build {r['build']}")


if __name__ == "__main__":
    main()
