#!/usr/bin/env python3
"""Prepare this library for a new probe release: refresh, earn the row, commit.

    tools/upgrade-upstream v0.6.1
    tools/upgrade-upstream v0.6.1 --dry-run

The compatibility table is a claim about a pair that *ran*: the probe series
vendored, and the library series that loaded its audits. A row typed by hand is
how that table grows a line with no run behind it, so this script does the
whole preparation as one transaction and commits only what the gates approved:

 1. `tools/refresh-upstream vX.Y.Z` — still the only supported way to change
    the vendored copies (schema, fixture, UPSTREAM), with its half-refresh
    guard. Already refreshed by hand? It runs again; the fetch is idempotent.
 2. The new row, written into README **and** SPECS from one string, because
    `test_contract_pin` holds the two tables to being the same table:
      - probe column: the tag's *series* (`v0.6`), since a patch never moves
        the contract;
      - library column: the first pair the table does not already claim — the
        current series when its pair is free, otherwise the next minor. The row
        therefore promises the release that carries it, and `tools/release
        minor` is what keeps that promise;
      - envelope column: the refreshed fixture's own `major.minor`, never a
        number typed by hand.
 3. The gates CI runs: `uv sync --locked --all-groups`, `ruff check`,
    `ruff format --check`, `pytest`. The last one is where the row is earned —
    it is the run that loads the fixture just vendored.

Refuses, before touching anything: a dirty tree outside the five files this
script owns, another branch (you commit what you push), an older series than
the one already at the top of the table, a tag already vendored with its row
(twice in a row is not two runs), and a refreshed fixture whose identity is a
placeholder — `0.0.0-dev` / `unknown` is `go run`, and no `probe.version >= …`
rule in this library accepts it.

On a failed gate the five files are restored to HEAD and nothing is committed:
a half-refreshed tree is the bug this project exists to avoid, and refresh is
one command to run again.

It neither tags nor pushes. `tools/release` makes the version and the tag;
publishing is the maintainer's decision, and the last lines printed are the
commands to do both.
"""

from __future__ import annotations

import argparse
import json
import re
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
README = ROOT / "README.md"
SPECS = ROOT / "SPECS.md"
FIXTURE = ROOT / "tests" / "fixtures" / "audit-offline.json"
UPSTREAM = ROOT / "tests" / "fixtures" / "UPSTREAM"
SCHEMA = ROOT / "src" / "perquisition" / "schema" / "envelope.schema.json"
PYPROJECT = ROOT / "pyproject.toml"

# The five paths this script owns: refresh-upstream writes four of them, this
# script writes the two documents. Everything else must be clean, or the tree
# carries work this transaction would either swallow or commit by accident.
MANAGED = (README, SPECS, UPSTREAM, FIXTURE, SCHEMA)

_VERSION_LINE = re.compile(r'(?m)^version = "([^"]+)"$')
_TAG = re.compile(r"^v?(\d+)\.(\d+)(?:\.(\d+))?$")
_TABLE_HEADER = re.compile(r"^\s*\|\s*probe\s*\|\s*library\s*\|\s*envelope\s*\|\s*$")
_TABLE_ROW = re.compile(r"^\s*\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|\s*$")
_LIBRARY_SERIES = re.compile(r"^\d+\.\d+\.x$")
_PASSED = re.compile(r"(\d+) passed")


class UpgradeError(RuntimeError):
    pass


def run(*args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
    return subprocess.run(args, cwd=ROOT, text=True, capture_output=True, check=check)


def git(*args: str, check: bool = True) -> str:
    return run("git", *args, check=check).stdout.strip()


def series_of(text: str) -> tuple[int, int]:
    match = _TAG.match(text.strip())
    if match is None:
        raise UpgradeError(f"{text!r} is not vMAJOR.MINOR[.PATCH]")
    return int(match.group(1)), int(match.group(2))


def rows_of(text: str, where: str) -> list[tuple[str, str, str]]:
    """Every row of the one compatibility table, like the pin test parses them."""
    lines = text.splitlines()
    starts = [i for i, line in enumerate(lines) if _TABLE_HEADER.match(line)]
    if len(starts) != 1:
        raise UpgradeError(f"{where}: expected exactly one table, found {len(starts)}")
    rows: list[tuple[str, str, str]] = []
    for line in lines[starts[0] + 1 :]:
        if not line.strip().startswith("|"):
            break
        if re.fullmatch(r"\|[\s:|-]+\|", line.strip()):
            continue
        match = _TABLE_ROW.match(line)
        if match is None:
            raise UpgradeError(f"{where}: unreadable table row {line!r}")
        rows.append((match.group(1), match.group(2), match.group(3)))
    if not rows:
        raise UpgradeError(f"{where}: the compatibility table has no rows")
    return rows


def insert_row(text: str, row: str) -> str:
    """Insert `row` keeping the table newest-first, as (probe series, library series)."""
    lines = text.splitlines(keepends=True)
    start = next(i for i, line in enumerate(lines) if _TABLE_HEADER.match(line))
    new_key = (*series_of(row.split("|")[1]), row.split("|")[2].strip())
    position = None
    index = start + 1  # skip the |---| separator
    while index < len(lines) and lines[index].strip().startswith("|"):
        if re.fullmatch(r"\|[\s:|-]+\|", lines[index].strip()):
            index += 1
            continue
        match = _TABLE_ROW.match(lines[index])
        assert match is not None
        key = (*series_of(match.group(1)), match.group(2))
        if key < new_key:
            position = index
            break
        index += 1
    if position is None:  # every row sorts after it, or the table ended
        position = index
    indent = re.match(r"\s*", lines[start]).group(0)
    return "".join(lines[:position]) + f"{indent}{row}\n" + "".join(lines[position:])


def library_series_for(rows: list[tuple[str, str, str]], version: str) -> str:
    """The library series a new row promises.

    The column names the series about to *ship*, not the one running: the
    `v0.3 | 0.2.x` row was written while pyproject still said 0.1.1, and
    `tools/release minor` made the promise true afterwards. So a current series
    that already carries a row has been released and the next minor is the one
    to promise; a current series with no row of its own is still waiting for
    its release, and it is the honest answer.
    """
    major, minor, _patch = (int(n) for n in version.split("."))
    current = f"{major}.{minor}.x"
    released = any(library == current for _, library, _ in rows)
    return f"{major}.{minor + 1}.x" if released else current


def paths_outside(status: str, managed: set[Path], root: Path) -> list[str]:
    """Paths `git status --porcelain` reports that this transaction does not own.

    `status` must be the command's RAW output. Porcelain marks every line with
    two status characters and a space, so a line's leading whitespace *is* the
    data: the `git()` helper strips the whole output, which eats the first
    line's marker — ` M x` comes back as `M x`, and slicing `[3:]` from there
    reports `x` shifted by one character, refusing a file the script owns.
    """
    return [
        line[3:]
        for line in status.splitlines()
        if line and root / line[3:] not in managed
    ]


def preflight(branch: str, managed: set[Path]) -> None:
    if git("rev-parse", "--is-inside-work-tree") != "true":
        raise UpgradeError(f"{ROOT} is not a git repository")

    # Raw on purpose: see paths_outside — `git()` would strip the first line's marker.
    status = run("git", "status", "--porcelain=v1", "--untracked-files=normal").stdout
    outside = paths_outside(status, managed, ROOT)
    if outside:
        raise UpgradeError(
            "the working tree holds work this transaction does not own, and a "
            "failed gate would have to choose what to restore:\n  "
            + "\n  ".join(outside)
        )

    current = git("rev-parse", "--abbrev-ref", "HEAD")
    if current != branch:
        raise UpgradeError(
            f"on branch {current!r}, not {branch!r}. Pass --branch {current} if deliberate."
        )

    try:
        run("git", "fetch", "--quiet", "origin")
    except (subprocess.CalledProcessError, FileNotFoundError):
        print(
            "warning: could not reach origin; skipping the up-to-date check",
            file=sys.stderr,
        )
        return
    upstream = run(
        "git", "rev-parse", "--verify", "--quiet", f"origin/{branch}", check=False
    )
    if upstream.returncode != 0:
        return  # no origin/<branch> to compare against yet
    if (
        run(
            "git",
            "merge-base",
            "--is-ancestor",
            f"origin/{branch}",
            "HEAD",
            check=False,
        ).returncode
        != 0
    ):
        raise UpgradeError(
            f"origin/{branch} has commits this checkout does not have: pull or merge "
            "first, so the upgrade lands on the history you will push"
        )


def vendored_tag() -> str:
    for line in UPSTREAM.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if line and not line.startswith("#"):
            return line.split(" ")[0]
    raise UpgradeError("UPSTREAM holds no tag")


def restore() -> None:
    git("reset", "--quiet", check=False)
    git("checkout", "--", *(str(p) for p in MANAGED), check=False)


def gates(pytest_count: list[str]) -> None:
    """The gates CI runs, in CI's order. A failure restores and re-raises."""
    steps = (
        ("uv sync --locked --all-groups", ["uv", "sync", "--locked", "--all-groups"]),
        ("ruff check", ["uv", "run", "ruff", "check", "."]),
        ("ruff format --check", ["uv", "run", "ruff", "format", "--check", "."]),
        ("pytest", ["uv", "run", "pytest", "-q"]),
    )
    for label, argv in steps:
        result = run(*argv, check=False)
        output = (result.stdout or "") + (result.stderr or "")
        if result.returncode != 0:
            restore()
            raise UpgradeError(f"gate failed: {label}\n{output}")
        if label == "pytest":
            found = _PASSED.findall(output)
            pytest_count.append(found[-1] if found else "?")


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("tag", help="probe release tag to vendor, e.g. v0.6.1")
    parser.add_argument(
        "--branch", default="main", help="branch an upgrade may land on"
    )
    parser.add_argument(
        "--dry-run", action="store_true", help="say what would happen, change nothing"
    )
    args = parser.parse_args(argv)

    managed = {p.resolve() for p in MANAGED}
    try:
        probe_series = series_of(args.tag)
        preflight(args.branch, managed)

        readme_rows = rows_of(README.read_text(encoding="utf-8"), "README.md")
        specs_rows = rows_of(SPECS.read_text(encoding="utf-8"), "SPECS.md")
        if readme_rows != specs_rows:
            raise UpgradeError(
                "README and SPECS tables already disagree: fix that by hand first"
            )

        if probe_series < series_of(readme_rows[0][0]):
            raise UpgradeError(
                f"{args.tag} is older than {readme_rows[0][0]} at the top of the table: "
                "this upgrades the pair, it does not downgrade it"
            )

        version = _VERSION_LINE.findall(PYPROJECT.read_text(encoding="utf-8"))
        if len(version) != 1:
            raise UpgradeError("pyproject.toml: expected exactly one version line")
        major, minor, _patch = (int(n) for n in version[0].split("."))
        current_series = f"{major}.{minor}.x"
        library_series = library_series_for(readme_rows, version[0])
        # A patch upgrade (v0.6.0 → v0.6.1) writes no row at all: the series is
        # already there, and a patch never moves the contract.
        series_in_table = any(series_of(r[0]) == probe_series for r in readme_rows)
        vendored_before = vendored_tag()
        if series_in_table and args.tag == vendored_before:
            raise UpgradeError(
                f"{args.tag} is already vendored with its row: nothing to do"
            )
    except UpgradeError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1

    envelope_now = json.loads(FIXTURE.read_text(encoding="utf-8"))["schema_version"]
    plan = (
        None
        if series_in_table
        else (
            f"| v{probe_series[0]}.{probe_series[1]} | {library_series} | "
            f"{'.'.join(envelope_now.split('.')[:2])} |"
        )
    )
    print(
        f"probe {args.tag} -> series v{probe_series[0]}.{probe_series[1]}, library {library_series}"
    )
    if plan is None:
        print(f"row: unchanged — v{probe_series[0]}.{probe_series[1]} already has one")
    else:
        print(f"row: {plan}")
    if args.dry_run:
        print(
            "dry run: envelope column shown from the *current* fixture; the real value "
            "is read after refresh. Nothing changed."
        )
        return 0

    try:
        refresh = run(str(ROOT / "tools" / "refresh-upstream"), args.tag, check=False)
        if refresh.returncode != 0:
            restore()
            raise UpgradeError(
                f"refresh-upstream failed:\n{refresh.stdout}{refresh.stderr}"
            )

        fixture = json.loads(FIXTURE.read_text(encoding="utf-8"))
        probe = fixture["probe"]
        if probe["version"].startswith("0.0.0-dev") or probe.get("commit") in (
            None,
            "",
            "unknown",
        ):
            restore()
            raise UpgradeError(
                f"the refreshed fixture says probe {probe['version']!r} / commit "
                f"{probe.get('commit')!r}: it was built without ldflags. Regenerate it "
                "on the probe side — `make fixture` on the tag — before vendoring it"
            )
        schema_major, schema_minor, *_ = fixture["schema_version"].split(".")
        if series_in_table:
            # Patch upgrade: the row for this series already exists in both
            # tables, and a patch never moves the contract — nothing to write.
            row = None
            needs_minor = False
        else:
            row = (
                f"| v{probe_series[0]}.{probe_series[1]} | {library_series} | "
                f"{schema_major}.{schema_minor} |"
            )
            for document in (README, SPECS):
                text = document.read_text(encoding="utf-8")
                document.write_text(insert_row(text, row), encoding="utf-8")
            needs_minor = library_series != current_series

        if rows_of(README.read_text(encoding="utf-8"), "README.md") != rows_of(
            SPECS.read_text(encoding="utf-8"), "SPECS.md"
        ):
            restore()
            raise UpgradeError(
                "the two tables diverged while writing them: restored, nothing committed"
            )

        count: list[str] = []
        gates(count)
    except UpgradeError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1

    row_line = (
        "row: unchanged — v"
        f"{probe_series[0]}.{probe_series[1]} was already in both tables "
        "(a patch never moves the contract).\n"
        if row is None
        else f"row: {row}, written in README and SPECS from one string.\n"
    )
    promise = (
        f"Not tagged, not pushed: `tools/release minor` makes the {library_series}\n"
        f"promise true ({version[0]} -> {major}.{minor + 1}.0), and publishing stays yours."
        if needs_minor
        else "Not tagged, not pushed: a patch upgrade, so no version promise to keep.\n"
        "Publishing stays yours — `git push`."
    )
    message = (
        f"upstream: vendor probe {args.tag}, and the row it earned\n"
        f"\n"
        f"tests/fixtures/UPSTREAM: {args.tag} — the only supported way to move it\n"
        f"is refresh-upstream, which this commit ran with its half-refresh guard.\n"
        f"schema/envelope.schema.json: {'unchanged' if _SCHEMA_UNCHANGED() else 'updated'} "
        f"(envelope {schema_major}.{schema_minor}).\n"
        f"tests/fixtures/audit-offline.json: probe {probe['version']} (commit {probe['commit']}),\n"
        f"{len(fixture['results'])} collectors, root {fixture['audit'].get('root')!r}.\n"
        f"{row_line}"
        f"gates: uv sync --locked, ruff check, ruff format --check, "
        f"pytest ({count[0] if count else '?'} passed) — this run is the pair the row claims.\n"
        f"\n"
        f"{promise}"
    )
    try:
        git("add", *(str(p) for p in MANAGED))
        result = run("git", "commit", "-m", message, check=False)
        if result.returncode != 0:
            raise UpgradeError(f"could not commit:\n{result.stdout}{result.stderr}")
    except UpgradeError as exc:
        restore()
        print(
            f"error: {exc}\nworking tree restored, nothing committed", file=sys.stderr
        )
        return 1

    print(f"row: {row}" if row else "row: unchanged (the series was already there)")
    print(f"gates: sync, ruff, format, pytest {count[0] if count else '?'} passed")
    print(f"committed: {git('rev-parse', '--short', 'HEAD')}")
    if needs_minor:
        print(
            f"next:  tools/release minor    # {version[0]} -> {major}.{minor + 1}.0, tag v{major}.{minor + 1}.0"
        )
    print("push:  git push               # publishing is yours")


def _SCHEMA_UNCHANGED() -> bool:
    return run("git", "diff", "--quiet", "--", str(SCHEMA), check=False).returncode == 0


if __name__ == "__main__":
    raise SystemExit(main())
