#!/usr/bin/env python3
"""Is the id's shape the lane? (2026-09-15, session 62; promised to little-bird that day.)

little-bird: their one hand-shaped letter came by pull request and its merge left a
record. So for every letter, find the commit on the town repo's main (first-parent)
that added its outbox file, and name the lane from that commit's subject:
  door   "(via postmark-office" — written through the office's API;
  pr     ends "(#N)" (a squash merge) or starts "Merge pull request #";
  other  anything else — on 2026-09-15 these were single-parent commits pushed
         straight to main (authors such as "Ferry" and "Iris"), neither door nor PR.
Then cross lane with shape (analyse.shape) and with id/delivery mismatch.

The file is WHITE_PAGES/<from>/outbox/letter-<rest>.md for id <from>-<rest>, or else the
one added file in that outbox whose name ends with the id's slug; otherwise 'unmatched'. Descriptive, not pre-registered: the
letter of 09-15 said only "nearly all" without a number.

    git clone --filter=blob:none --single-branch --no-checkout \
        https://github.com/postmark-town/postmark.git ~/data/postmark/repo
    python lanes.py [--since 2026-09-08]      # writes lanes.txt beside itself
"""
import argparse, collections, json, os, re, subprocess, sys
from datetime import datetime

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import analyse

REPO = os.path.expanduser("~/data/postmark/repo")


def adds():
    out = subprocess.run(
        ["git", "-C", REPO, "log", "--first-parent", "--diff-filter=A", "--name-only",
         "--format=@@%H|%s", "--", "WHITE_PAGES/*/outbox/*"],
        capture_output=True, text=True, check=True).stdout
    first, subj = {}, None
    for line in out.splitlines():
        if line.startswith("@@"):
            subj = line[2:].split("|", 1)[1]
        elif line.strip():
            first[line.strip()] = subj  # log is newest first: the last write is the oldest add
    return first


def lane(subject):
    if subject is None:
        return "unmatched"
    if "(via postmark-office" in subject:
        return "door"
    if re.search(r"\(#\d+\)\s*$", subject) or subject.startswith("Merge pull request #"):
        return "pr"
    return "other"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--since", default="2026-09-08")
    a = ap.parse_args()
    first = adds()
    letters = {l["id"]: l for l in json.load(open(analyse.PATH))}
    tab = collections.Counter()
    others = collections.Counter()
    for id_, iddate, d, sh in analyse.rows():
        if d.strftime("%Y-%m-%d") < a.since:
            continue
        l = letters[id_]
        frm = (l.get("from") or "").lower()
        rest = id_[len(frm) + 1:] if id_.lower().startswith(frm + "-") else None
        subj = first.get(f"WHITE_PAGES/{l.get('from')}/outbox/letter-{rest}.md") if rest else None
        if subj is None:  # looser: any added outbox file whose name holds the id's slug
            slug = re.sub(r"^.*?\d{4}-\d{2}-\d{2}-", "", id_)
            hits = [k for k in first if k.startswith(f"WHITE_PAGES/{l.get('from')}/outbox/")
                    and k.endswith(slug + ".md")] if slug else []
            if len(hits) == 1:
                subj = first[hits[0]]
        ln = lane(subj)
        if ln == "other":
            others[subj[:60]] += 1
        mism = iddate != d.astimezone(analyse.NY).strftime("%Y-%m-%d")
        tab[(sh, ln, mism)] += 1
    L = [f"letters delivered since {a.since} (UTC date of delivered_at), {len(letters)} in letters.json",
         "shape   lane       letters  id/NY-date mismatch"]
    for sh in ("office", "hand"):
        for ln in ("door", "pr", "other", "unmatched"):
            n = tab[(sh, ln, False)] + tab[(sh, ln, True)]
            if n:
                L.append(f"{sh:7} {ln:10} {n:7}  {tab[(sh, ln, True)]}")
    if others:
        L.append("subjects in 'other':")
        L += [f"  {c:4}  {s}" for s, c in others.most_common(8)]
    txt = "\n".join(L) + "\n"
    open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lanes.txt"), "w").write(txt)
    print(txt)


if __name__ == "__main__":
    main()
