#!/usr/bin/env python3
"""Refresh the artifacts vendored from a published `perquisition` release.

This project never reads the probe's Go source. It consumes exactly two files
from the probe repository, at a tag:

  schema/envelope.schema.json          the contract, and its source of truth
  schema/fixtures/audit-offline.json   a real, sanitised audit

Both are copied into the package and the test suite, and the tag is recorded in
`tests/fixtures/UPSTREAM` so a test can say which release the library was
checked against.

Usage:
    tools/refresh-upstream v0.2
    GITHUB_TOKEN=... tools/refresh-upstream v0.2

The probe repository is private for now, so a token with `repo` read scope is
required until it is published; after that the token becomes optional. The
token is read from GITHUB_TOKEN or GH_TOKEN and never written anywhere.

The GitHub *contents* API is used rather than raw.githubusercontent.com because
raw URLs carry no Authorization header, and a private repository answers them
with 404 — indistinguishable from "the tag has no schema/". A 404 here is
therefore reported with both possibilities named.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import sys
import urllib.error
import urllib.request
from pathlib import Path

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

DEFAULT_REPO = "athoune/perquisition"
DEFAULT_API = "https://api.github.com"

_TAG = re.compile(r"^v?\d+\.\d+(\.\d+)?$")


class RefreshError(RuntimeError):
    pass


def token() -> str | None:
    """The token, from the environment only. Never a config file, never argv."""
    for name in ("GITHUB_TOKEN", "GH_TOKEN"):
        value = os.environ.get(name)
        if value:
            return value
    return None


def fetch(api: str, repo: str, path: str, ref: str) -> bytes:
    url = f"{api.rstrip('/')}/repos/{repo}/contents/{path}?ref={ref}"
    request = urllib.request.Request(url, headers={"Accept": "application/vnd.github.raw"})
    if (secret := token()) is not None:
        request.add_header("Authorization", f"Bearer {secret}")
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            return response.read()
    except urllib.error.HTTPError as exc:
        if exc.code == 404:
            raise RefreshError(
                f"{repo}: {path} is not readable at {ref}. Two possibilities, and "
                "they are not distinguishable from here: the ref does not carry "
                "that file (the schema is published from the release that adds "
                "it), or the repository is private and no token was supplied "
                "(set GITHUB_TOKEN with `repo` read scope)."
            ) from exc
        if exc.code in (401, 403):
            raise RefreshError(
                f"{repo}: GitHub refused the credentials ({exc.code}); a token "
                "with `repo` read scope is needed while the repository is private."
            ) from exc
        raise RefreshError(f"{repo}: {path} at {ref}: HTTP {exc.code}") from exc
    except urllib.error.URLError as exc:
        raise RefreshError(f"cannot reach {api}: {exc.reason}") from exc


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("tag", help="probe release tag, e.g. v0.2")
    parser.add_argument("--repo", default=DEFAULT_REPO, help="probe repository, owner/name")
    parser.add_argument("--api", default=DEFAULT_API, help="GitHub API base URL")
    args = parser.parse_args(argv)

    if not _TAG.match(args.tag):
        print(f"error: {args.tag!r} is not a release tag", file=sys.stderr)
        return 2

    try:
        schema = fetch(args.api, args.repo, "schema/envelope.schema.json", args.tag)
        fixture = fetch(args.api, args.repo, "schema/fixtures/audit-offline.json", args.tag)
    except RefreshError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1

    # Refuse a half-refresh before writing anything: the two files must agree
    # on the envelope major, or the library would validate against one version
    # and test against another.
    major = json.loads(schema)["x-envelope-major"]
    fixture_major = json.loads(fixture)["schema_version"].split(".")[0]
    if str(major) != fixture_major:
        print(
            f"error: schema declares major {major}, fixture carries "
            f"{fixture_major}: refusing a half-refresh",
            file=sys.stderr,
        )
        return 1

    SCHEMA.write_bytes(schema)
    FIXTURE.write_bytes(fixture)
    UPSTREAM.write_text(
        "# Source of the vendored artifacts. Written by tools/refresh-upstream,\n"
        "# never by hand: a hand-edited answer is worse than no answer.\n"
        f"{args.tag} ({args.repo})\n",
        encoding="utf-8",
    )
    print(f"refreshed from {args.repo} {args.tag}: envelope major {major}")
    print(f"  {SCHEMA.relative_to(ROOT)}")
    print(f"  {FIXTURE.relative_to(ROOT)}")
    return 0


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