#!/usr/bin/env python3
"""git-baseline.py — delivery numbers from a repository's git history alone.

The "before" picture for a pilot of AI-driven development: how often the team
releases, how long a change waits from its commit to a release, how big the
changes are and how often they are reverted. It reads git only — no CI, no
issue tracker, nothing sent anywhere — and changes nothing in the repository.

    python3 git-baseline.py --repo path/to/repo
    python3 git-baseline.py --repo . --days 90 --releases tags --tag-pattern 'v*'
    python3 git-baseline.py --repo . --releases merges --format csv > baseline.csv

The pilot's table (pilot-baseline.csv, the same rows as SHEET below):
    python3 git-baseline.py --repo . --format sheet > pilot.csv          # Start filled
    python3 git-baseline.py --repo . --format sheet --column week6 \
        --into pilot.csv > pilot-week6.csv                               # adds Week 6

Before and after the pilot started — the period before the date against
the days from it to --end:
    python3 git-baseline.py --repo . --compare 2026-09-01

Review times from GitHub, through the gh command line, if it is installed and
signed in (the one option that goes to the network; off unless asked):
    python3 git-baseline.py --repo . --github

What counts as a release (--releases):
  tags     a tag matching --tag-pattern, reachable from the branch, dated by
           its tagger date (a lightweight tag has none: its commit's date
           stands in, which makes that commit's lead time zero)
  merges   a merge commit on the branch's first-parent line
  commits  every commit on the branch's first-parent line (no lead time then)
  auto     tags when any falls in the period, else merges, else commits

What it cannot see: when a release really reached production, which releases
failed or how long recovery took. Those come from the deploy log and the
incident system. Review times need --github (or the GitLab API by hand).

Python 3.8+, standard library only. MIT licence, part of SClaude:
https://github.com/personalautomation/SClaude/blob/main/docs/tools/git-baseline.py
How to use it in a pilot:
https://personalautomation.github.io/SClaude/materials/pilot-templates.html
"""
import argparse
import csv
import fnmatch
import json
import math
import os
import re
import statistics
import subprocess
import sys
from datetime import datetime, timedelta, timezone

LOCK_FILES = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock",
              "poetry.lock", "uv.lock", "Pipfile.lock", "go.sum", "Cargo.lock",
              "composer.lock", "Gemfile.lock", "gradle.lockfile", "packages.lock.json"]


def git(repo, *args):
    run = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True,
                         encoding="utf-8", errors="replace")
    if run.returncode != 0:
        sys.exit(f"git {' '.join(args)}: {run.stderr.strip()}")
    return run.stdout


def median(values):
    return statistics.median(values) if values else None


def p85(values):
    if not values:
        return None
    ordered = sorted(values)
    return ordered[max(0, math.ceil(0.85 * len(ordered)) - 1)]


def first_parent(repo, branch, since, until):
    """(sha, commit time, subject) of the branch's first-parent line, oldest first."""
    out = git(repo, "log", "--first-parent", "--reverse", "--format=%H%x09%ct%x09%P%x09%s",
              f"--since=@{since}", f"--until=@{until}", branch)
    rows = []
    for line in out.splitlines():
        sha, ct, parents, subject = (line.split("\t", 3) + [""])[:4]
        rows.append({"sha": sha, "time": int(ct), "merge": len(parents.split()) > 1, "subject": subject})
    return rows


def tag_releases(repo, branch, pattern):
    merged = set(git(repo, "tag", "--merged", branch).split())
    out = git(repo, "for-each-ref", "refs/tags",
              "--format=%(refname:short)%09%(creatordate:unix)%09%(objectname)%09%(*objectname)")
    rows = []
    for line in out.splitlines():
        name, when, obj, peeled = (line.split("\t") + ["", "", ""])[:4]
        if name in merged and fnmatch.fnmatch(name, pattern) and when:
            rows.append({"name": name, "time": int(when), "sha": peeled or obj})
    return sorted(rows, key=lambda r: r["time"])


def lead_times(repo, releases, since, kind, previous=None):
    """Hours from each commit's author date to the release that shipped it.

    previous is the last release before the period, which bounds the first
    release's commits; without one, only commits written in the period count.
    """
    hours = []
    for rel in releases:
        if kind == "merges":
            span = f"{rel['sha']}^1..{rel['sha']}"
        elif previous:
            span = f"{previous['sha']}..{rel['sha']}"
        else:
            span = rel["sha"]
        out = git(repo, "rev-list", "--no-merges", "--format=%at", span)
        for line in out.splitlines():
            if line.startswith("commit "):
                continue
            authored = int(line)
            # The first release of the history has no release before it: only
            # the commits written inside the period count, not years of them.
            if previous is None and kind != "merges" and authored < since:
                continue
            hours.append(max(0.0, (rel["time"] - authored) / 3600))
        previous = rel
    return hours


def change_sizes(repo, branch, since, until, excluded):
    out = git(repo, "log", "--first-parent", "-m", "--numstat", "--format=@%H",
              f"--since=@{since}", f"--until=@{until}", branch)
    sizes, files, current = {}, {}, None
    for line in out.splitlines():
        if line.startswith("@"):
            current = line[1:]
            sizes.setdefault(current, 0)
            files.setdefault(current, 0)
            continue
        parts = line.split("\t")
        if current is None or len(parts) != 3:
            continue
        added, removed, path = parts
        if " => " in path:  # a rename: count it under its new name
            m = re.match(r"(.*)\{(.*) => (.*)\}(.*)", path)
            path = (m[1] + m[3] + m[4]).replace("//", "/") if m else path.split(" => ")[-1]
        name = os.path.basename(path)
        if added == "-" or any(fnmatch.fnmatch(name, p) or fnmatch.fnmatch(path, p) for p in excluded):
            continue
        sizes[current] += int(added) + int(removed)
        files[current] += 1
    return [v for v in sizes.values()], [v for v in files.values()]


def revert_share(repo, branch, since, until):
    out = git(repo, "log", "--first-parent", "--format=%B%x1e", f"--since=@{since}", f"--until=@{until}", branch)
    bodies = [b.strip() for b in out.split("\x1e") if b.strip()]
    if not bodies:
        return None
    # A merge commit carries the pull request's title, 'Revert "…"', on a later line.
    reverts = sum(1 for b in bodies
                  if b.lower().startswith("revert") or "This reverts commit" in b
                  or any(l.startswith('Revert "') for l in b.splitlines()[1:3]))
    return reverts / len(bodies)


def day(text):
    return datetime.strptime(text, "%Y-%m-%d").replace(tzinfo=timezone.utc)


def periods(args):
    """[(since, until)] — one period, or before and after --compare's date."""
    end = day(args.end) + timedelta(days=1) if args.end else datetime.now(timezone.utc)
    if not args.compare:
        return [(int((end - timedelta(days=args.days)).timestamp()), int(end.timestamp()))]
    split = day(args.compare)
    if split >= end:
        sys.exit("--compare: the date must be before the end of the period")
    return [(int((split - timedelta(days=args.days)).timestamp()), int(split.timestamp())),
            (int(split.timestamp()), int(end.timestamp()))]


def release_kind(args, since, until):
    """What counts as a release, decided once for the whole span, so the two
    periods of --compare count the same thing."""
    if args.releases != "auto":
        return args.releases
    tags = tag_releases(args.repo, args.branch, args.tag_pattern)
    if any(since <= t["time"] < until for t in tags):
        return "tags"
    line = first_parent(args.repo, args.branch, since, until)
    return "merges" if any(c["merge"] for c in line) else "commits"


def measure(args, since, until):
    repo = args.repo
    days = (until - since) / 86400
    warnings = []
    if git(repo, "rev-parse", "--is-shallow-repository").strip() == "true":
        warnings.append("the clone is shallow: older history is missing, so the numbers are partial (git fetch --unshallow)")

    line = first_parent(repo, args.branch, since, until)
    kind = args.releases
    tags = tag_releases(repo, args.branch, args.tag_pattern) if kind == "tags" else []
    in_period = [t for t in tags if since <= t["time"] < until]
    if kind == "tags":
        before = [t for t in tags if t["time"] < since]
        releases = in_period
        lead = lead_times(repo, releases, since, "tags", before[-1] if before else None)
    elif kind == "merges":
        releases = [c for c in line if c["merge"]]
        lead = lead_times(repo, releases, since, "merges")
    else:
        releases = line
        lead = []
        warnings.append("every commit counts as a release, so lead time is not computed: use --releases tags or merges, or the deploy log")

    times = sorted(r["time"] for r in releases)
    gaps = [(b - a) / 86400 for a, b in zip(times, times[1:])]
    quick = None
    if kind == "tags" and len(times) > 1:
        follow = sum(1 for g in gaps if g * 24 <= args.hotfix_hours)
        quick = follow / (len(times) - 1)
    sizes, files = change_sizes(repo, args.branch, since, until, LOCK_FILES + args.exclude)

    result = {
        "period": {"from": datetime.fromtimestamp(since, timezone.utc).strftime("%Y-%m-%d"),
                   "to": (datetime.fromtimestamp(until, timezone.utc) - timedelta(seconds=1)).strftime("%Y-%m-%d"),
                   "days": round(days)},
        "release_source": kind,
        "releases": len(releases),
        "releases_per_week": round(len(releases) / (days / 7), 2),
        "days_between_releases_median": median(gaps),
        "lead_time_hours_median": median(lead),
        "lead_time_hours_p85": p85(lead),
        "lead_time_commits": len(lead),
        "changes_on_branch": len(line),
        "change_size_lines_median": median(sizes),
        "change_size_lines_p85": p85(sizes),
        "files_per_change_median": median(files),
        "revert_share": revert_share(repo, args.branch, since, until),
        "quick_next_release_share": quick,
        "quick_next_release_hours": args.hotfix_hours if kind == "tags" else None,
        "review_first_hours_median": None,
        "review_to_merge_hours_median": None,
        "pull_requests": None,
        "warnings": warnings,
    }
    if args.github:
        result.update(github_reviews(repo, since, until, warnings))
    return result


def github_reviews(repo, since, until, warnings):
    """Hours from a pull request opening to its first review by someone else,
    and to its merge, for the pull requests merged in the period — from gh."""
    a = datetime.fromtimestamp(since, timezone.utc).strftime("%Y-%m-%d")
    b = (datetime.fromtimestamp(until, timezone.utc) - timedelta(seconds=1)).strftime("%Y-%m-%d")
    try:
        run = subprocess.run(["gh", "pr", "list", "--state", "merged", "--limit", "1000",
                              "--search", f"merged:{a}..{b}",
                              "--json", "createdAt,mergedAt,author,reviews"],
                             cwd=repo, capture_output=True, text=True, encoding="utf-8", errors="replace")
    except FileNotFoundError:
        warnings.append("--github: the gh command is not installed (https://cli.github.com), so review times are left out")
        return {}
    if run.returncode != 0:
        warnings.append(f"--github: gh could not list the pull requests ({run.stderr.strip()[:200]}), so review times are left out")
        return {}
    stamp = lambda t: datetime.strptime(t, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()
    first, merge = [], []
    prs = json.loads(run.stdout or "[]")
    for pr in prs:
        opened = stamp(pr["createdAt"])
        merge.append((stamp(pr["mergedAt"]) - opened) / 3600)
        who = (pr.get("author") or {}).get("login")
        times = [stamp(r["submittedAt"]) for r in pr.get("reviews") or []
                 if r.get("submittedAt") and (r.get("author") or {}).get("login") != who]
        if times:
            first.append(max(0.0, (min(times) - opened) / 3600))
    if len(prs) == 1000:
        warnings.append("--github: the period has 1,000 merged pull requests or more; the first thousand were counted")
    return {"review_first_hours_median": median(first), "review_to_merge_hours_median": median(merge),
            "pull_requests": len(prs)}


LABELS = [
    ("releases", "Releases in the period"),
    ("releases_per_week", "Releases per week"),
    ("days_between_releases_median", "Days between releases, median"),
    ("lead_time_hours_median", "Lead time commit → release, median"),
    ("lead_time_hours_p85", "Lead time commit → release, 85th percentile"),
    ("lead_time_commits", "Commits in the lead-time count"),
    ("changes_on_branch", "Changes on the branch (first-parent commits)"),
    ("change_size_lines_median", "Change size in lines, median"),
    ("change_size_lines_p85", "Change size in lines, 85th percentile"),
    ("files_per_change_median", "Files per change, median"),
    ("revert_share", "Reverted changes"),
    ("quick_next_release_share", "Releases followed by another within the window"),
    ("pull_requests", "Pull requests merged (--github)"),
    ("review_first_hours_median", "Time to first review, median (--github)"),
    ("review_to_merge_hours_median", "Pull request open to merge, median (--github)"),
]

# The pilot's table, row for row as docs/tools/pilot-baseline.csv has it
# (tests/site.py checks the two agree): group, metric, source, how to get
# it, the number of this script that fills the row, if any, and which way
# is better ("lower", "higher", or "" where a number does not apply; the
# site's spreadsheet and page colour the change by it). Numbers go
# in as numbers — hours, a count, a percentage — so a spreadsheet can
# compare the columns.
SHEET_HEAD = ["Group", "Metric", "Source", "How to get it", "Start (before the pilot)", "Week 6", "Final (week 13)", "Comment"]
COLUMNS = {"start": 4, "week6": 5, "final": 6}
SHEET = [
    ("Speed", "Lead time commit → release, median (hours)", "Git: release tag or merge against commit time", "git-baseline.py", "lead_time_hours_median", "lower"),
    ("Speed", "Lead time commit → release, 85th percentile (hours)", "Git", "git-baseline.py", "lead_time_hours_p85", "lower"),
    ("Speed", "Releases per week", "Git tags or the CI deploy log", "git-baseline.py or a CI export", "releases_per_week", "higher"),
    ("Speed", "Time to first review, median (hours)", "GitHub or GitLab API", "git-baseline.py --github, or the GitLab API", "review_first_hours_median", "lower"),
    ("Speed", "Pull request open to merge, median (hours)", "GitHub or GitLab API", "git-baseline.py --github, or the GitLab API", "review_to_merge_hours_median", "lower"),
    ("Stability", "Change failure rate (%)", "Incident system, CI rollbacks", "Releases rolled back or hot-fixed / all releases", None, "lower"),
    ("Stability", "Time to restore, median (hours)", "Incident system", "From the start of an incident a release caused to recovery", None, "lower"),
    ("Stability", "Unplanned fix releases (%)", "Deploy log, bug tickets", "Fix releases / all releases; git-baseline.py's quick follow-ups are a rough stand-in", None, "lower"),
    ("Process", "Change size in lines, median", "Git", "git-baseline.py", "change_size_lines_median", "lower"),
    ("Process", "Reverted changes (%)", "Git", "git-baseline.py", "revert_share", "lower"),
    ("AI", "Agent changes merged without a manual fix (%)", "Git: agent commits and human edits in the same pull request", "The weekly look at manual edits", None, "higher"),
    ("AI", "Defects traced to agent changes", "Tracker: defect linked to its spec and pull request", "Count for the period", None, "lower"),
    ("AI", "Model spend per task", "LLM gateway logs or provider invoices", "Spend for the period / tasks closed", None, "lower"),
    ("Team", "Short survey: where time goes, what gets in the way", "A five-minute team survey", "At the start and at the end of the pilot", None, ""),
]


def cell(key, value):
    """A number for the sheet: a share as a percentage, one decimal."""
    if value is None:
        return ""
    if key.endswith("_share"):
        value *= 100
    return round(value, 1) if isinstance(value, float) else value


def sheet(results, column, into):
    """The pilot's table with this run's numbers in it. One result fills
    column; two (--compare) fill Start with the first and column with the
    second. into: a table already started, whose other cells are kept."""
    rows = [list(r[:4]) + [""] * 4 for r in SHEET]
    if into:
        with open(into, newline="", encoding="utf-8-sig") as f:
            kept = {r[1]: r for r in list(csv.reader(f))[1:] if len(r) > 1}
        for row in rows:
            old = kept.get(row[1])
            if old:
                row[4:] = (old + [""] * 8)[4:8]
    targets = [COLUMNS[column]] if len(results) == 1 else [COLUMNS["start"], COLUMNS[column]]
    for spec, row in zip(SHEET, rows):
        key = spec[4]
        if key:
            for target, result in zip(targets, results):
                row[target] = cell(key, result[key])
    out = csv.writer(sys.stdout)
    out.writerow(SHEET_HEAD)
    out.writerows(rows)


# Counts depend on the period's length, which differs between the two
# periods of --compare: no change is given for them.
COUNTS = {"releases", "lead_time_commits", "changes_on_branch", "pull_requests"}


def change(key, before, after):
    """After against before: points for a share, per cent for the rest."""
    if before is None or after is None or key in COUNTS:
        return None
    if key.endswith("_share"):
        return f"{(after - before) * 100:+.1f} pp"
    if before == 0:
        return None
    return f"{(after - before) / before * 100:+.0f}%"


def shown(key, value):
    if value is None:
        return "—"
    if key.endswith("_share"):
        return f"{value * 100:.1f}%"
    if "_hours" in key:
        return f"{value:.1f} h" if value < 48 else f"{value / 24:.1f} days"
    if isinstance(value, float):
        return f"{value:.1f}"
    return str(value)


def main():
    ap = argparse.ArgumentParser(description="Delivery numbers from git history alone.",
                                 formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__.split("\n\n", 2)[2])
    ap.add_argument("--repo", default=".", help="the repository (default: .)")
    ap.add_argument("--branch", default="HEAD", help="the main branch (default: HEAD)")
    ap.add_argument("--days", type=int, default=90, help="length of the period in days (default: 90)")
    ap.add_argument("--end", help="last day of the period, YYYY-MM-DD (default: now)")
    ap.add_argument("--releases", choices=["auto", "tags", "merges", "commits"], default="auto",
                    help="what counts as a release (default: auto)")
    ap.add_argument("--tag-pattern", default="*", help="glob for release tags, e.g. 'v*' (default: *)")
    ap.add_argument("--hotfix-hours", type=float, default=24,
                    help="a release this soon after the previous one counts as a quick follow-up; tags only (default: 24)")
    ap.add_argument("--exclude", action="append", default=[],
                    help="a file glob left out of change sizes; repeatable (lock files are left out already)")
    ap.add_argument("--compare", metavar="YYYY-MM-DD",
                    help="the day the pilot started: --days before it against the days from it to --end")
    ap.add_argument("--github", action="store_true",
                    help="add review times from GitHub through gh (goes to the network; off by default)")
    ap.add_argument("--format", choices=["text", "json", "csv", "sheet"], default="text",
                    help="sheet: the pilot's table (pilot-baseline.csv) with these numbers in it")
    ap.add_argument("--column", choices=sorted(COLUMNS), default=None,
                    help="the sheet's column to fill (default: start; with --compare, final for the second period)")
    ap.add_argument("--into", metavar="FILE",
                    help="a pilot table already started: its other cells are kept (the result goes to stdout)")
    args = ap.parse_args()
    if args.days <= 0:
        ap.error("--days must be positive")
    if (args.column or args.into) and args.format != "sheet":
        ap.error("--column and --into go with --format sheet")
    if args.compare and args.column == "start":
        ap.error("--compare puts the earlier period in Start: give --column week6 or final")
    git(args.repo, "rev-parse", "--git-dir")

    spans = periods(args)
    args.releases = release_kind(args, spans[0][0], spans[-1][1])
    results = [measure(args, since, until) for since, until in spans]
    for w in dict.fromkeys(w for r in results for w in r["warnings"]):
        print(f"warning: {w}", file=sys.stderr)
    keys = [k for k, _ in LABELS if args.github or k not in ("pull_requests", "review_first_hours_median", "review_to_merge_hours_median")]
    if args.format == "sheet":
        sheet(results, args.column or ("final" if args.compare else "start"), args.into)
    elif args.format == "json":
        if len(results) == 1:
            print(json.dumps(results[0], indent=2))
        else:
            print(json.dumps({"before": results[0], "after": results[1],
                              "change": {k: change(k, results[0][k], results[1][k]) for k in keys}}, indent=2))
    elif args.format == "csv":
        out = csv.writer(sys.stdout)
        value = lambda v: "" if v is None else round(v, 3) if isinstance(v, float) else v
        names = dict(LABELS)
        if len(results) == 1:
            out.writerow(["metric", "name", "value"])
            for key in keys:
                out.writerow([key, names[key], value(results[0][key])])
        else:
            out.writerow(["metric", "name", "before", "after", "change"])
            for key in keys:
                out.writerow([key, names[key], value(results[0][key]), value(results[1][key]),
                              change(key, results[0][key], results[1][key]) or ""])
    else:
        names = dict(LABELS)
        r = results[0]
        if r["quick_next_release_hours"] is not None:
            names["quick_next_release_share"] = f"Releases followed by another within {r['quick_next_release_hours']:g} h"
        width = max(len(names[k]) for k in keys)
        for n, res in zip(("Before: ", "After:  ") if len(results) > 1 else ("Period: ",), results):
            p = res["period"]
            print(f"{n}{p['from']} → {p['to']} ({p['days']} days), releases counted from: {res['release_source']}")
        if len(results) == 1:
            for key in keys:
                print(f"  {names[key].ljust(width)}  {shown(key, r[key])}")
        else:
            a, b = results
            print(f"  {'':{width}}  {'before':>12}  {'after':>12}  change")
            for key in keys:
                print(f"  {names[key].ljust(width)}  {shown(key, a[key]):>12}  {shown(key, b[key]):>12}  {change(key, a[key], b[key]) or '—'}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
