#!/usr/bin/env python3
"""Publish the beta of a develop commit to Gitea Releases, from the build PC. Run from the repository root."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import tomllib
import urllib.error
import urllib.parse
import urllib.request


def git(*args, check=True):
    result = subprocess.run(["git", *args], capture_output=True, text=True)
    if check and result.returncode:
        raise ValueError(f"git {args[0]} : {result.stderr.strip()}")
    return result.stdout.strip() if result.returncode == 0 else None


def target(commit):
    """The stable version the cycle leads to: the workspace version in the commit's Cargo.toml."""
    version = tomllib.loads(git("show", f"{commit}:Cargo.toml"))["workspace"]["package"]["version"]
    if not re.fullmatch(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", version):
        raise ValueError(f"Cible de cycle X.Y.Z attendue dans Cargo.toml, pas {version}")
    return version


def tagged_commit(tag):
    return git("rev-parse", "-q", "--verify", f"refs/tags/{tag}^{{commit}}", check=False)


def number(commit, version):
    """(N, tag exists) for the commit's beta of version, or None when a newer beta tag contains it."""
    if tagged_commit(f"v{version}"):
        raise ValueError(f"La {version} est déjà publiée : fixer la cible du cycle suivant dans Cargo.toml")
    betas = {}
    for tag in git("tag", "--list", f"v{version}-beta.*").split():
        if match := re.fullmatch(rf"v{re.escape(version)}-beta\.([1-9][0-9]*)", tag):
            betas[int(match[1])] = tagged_commit(tag)
    for n, sha in betas.items():
        if sha == commit:
            return n, True
    # A commit older than the newest beta's is already in it, published or once its publication resumes.
    if betas:
        ancestor = subprocess.run(["git", "merge-base", "--is-ancestor", commit, betas[max(betas)]]).returncode
        if ancestor not in (0, 1):
            raise ValueError("git merge-base a échoué")
        if ancestor == 0:
            return None
    return max(betas, default=0) + 1, False


def package_file(version):
    return f"ArenaTracker-{version}-beta-full.nupkg"


def files(version):
    return {"ArenaTracker-beta-Setup.exe", "release-beta.json", "release-beta.sig", package_file(version)}


def expect(reply, *statuses):
    status, body = reply
    if status not in statuses:
        raise ValueError(f"Gitea a répondu HTTP {status} : {body}")
    return body


def check(api, release, commit, version, key):
    """Accept a published Release only if it is the complete, signed beta of this commit."""
    assets = {asset["name"]: asset for asset in release["assets"]}
    if set(assets) != files(version) or not release["prerelease"]:
        raise ValueError(f"La Release publiée {version} est incomplète ou n’est pas une préversion : rien n’est remplacé")
    package = package_file(version)
    with tempfile.TemporaryDirectory() as work:
        for name in ("release-beta.json", "release-beta.sig", package):
            (Path(work) / name).write_bytes(api.fetch(assets[name]["browser_download_url"]))
        public = Path(work) / "public.pem"
        subprocess.run(["openssl", "pkey", "-in", key, "-pubout", "-out", public], check=True)
        manifest = Path(work) / "release-beta.json"
        signed = subprocess.run(["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", public, "-rawin",
                                 "-in", manifest, "-sigfile", manifest.with_suffix(".sig")], capture_output=True)
        digest = base64.b64encode(hashlib.sha256((Path(work) / package).read_bytes()).digest()).decode()
        if signed.returncode or json.loads(manifest.read_bytes()) != {
            "app": "ArenaTracker", "target": "win-x64", "channel": "beta", "version": version,
            "commit": commit, "package": package, "sha256": digest,
        }:
            raise ValueError(f"La Release publiée {version} ne correspond pas au commit {commit} : rien n’est remplacé")


def publish(api, commit, version, tagged, build, key):
    """Publish version at commit as a complete prerelease, or reuse it if a previous run did."""
    tag = f"v{version}"
    status, release = api.call("GET", f"/releases/tags/{tag}") if tagged else (404, None)
    if status == 404:
        release = None
    elif status != 200:
        raise ValueError(f"Gitea a répondu HTTP {status} : {release}")
    if release and not release["draft"]:
        check(api, release, commit, version, key)
        print(f"{version} est déjà publiée au commit {commit} : publication réutilisée")
        return
    with tempfile.TemporaryDirectory() as work:
        out = Path(work) / "release"
        build(commit, version, out, key)
        if not tagged:
            # Atomic: Gitea refuses an existing tag, so two publications never share a number.
            expect(api.call("POST", "/tags", {"tag_name": tag, "target": commit}), 200, 201)
        if not release:
            release = expect(api.call("POST", "/releases", {
                "tag_name": tag, "name": f"Arena Tracker {version}", "body": f"Commit {commit}",
                "draft": True, "prerelease": True}), 201)
        # A draft is invisible to clients: its files are replaced as one set, built together.
        for asset in release["assets"]:
            expect(api.call("DELETE", f"/releases/{release['id']}/assets/{asset['id']}"), 204)
        for path in out.iterdir():
            name = urllib.parse.quote(path.name)
            expect(api.call("POST", f"/releases/{release['id']}/assets?name={name}", data=path.read_bytes()), 201)
    draft = expect(api.call("GET", f"/releases/{release['id']}"), 200)
    if {asset["name"] for asset in draft["assets"]} != files(version):
        raise ValueError(f"Le brouillon {version} n’a pas les fichiers attendus : il reste invisible")
    expect(api.call("PATCH", f"/releases/{release['id']}", {"draft": False, "prerelease": True}), 200)
    print(f"{version} publiée au commit {commit}")


def release_beta(api, commit, build, key):
    """Publish the commit's beta, provided it is on develop and its CI checks passed."""
    if subprocess.run(["git", "merge-base", "--is-ancestor", commit, "refs/remotes/origin/develop"]).returncode:
        raise ValueError(f"Le commit {commit} n’est pas dans develop sur Gitea : le pousser d’abord")
    state = expect(api.call("GET", f"/commits/{commit}/status"), 200)["state"]
    if state != "success":
        raise ValueError(f"Les contrôles CI du commit {commit} n’ont pas réussi (état : {state}) : rien n’est publié")
    version = target(commit)
    found = number(commit, version)
    if found is None:
        print(f"Le commit {commit} est déjà contenu dans la dernière bêta de {version} : aucune publication")
        return
    n, tagged = found
    publish(api, commit, f"{version}-beta.{n}", tagged, build, key)


class Gitea:
    def __init__(self, repo_url, token):
        self.repo_url = repo_url
        self.headers = {"Authorization": f"token {token}"}

    def request(self, url, method="GET", headers=None, data=None):
        request = urllib.request.Request(url, data, {**self.headers, **(headers or {})}, method=method)
        with urllib.request.urlopen(request, timeout=600) as response:
            return response.status, response.read()

    def call(self, method, path, body=None, data=None):
        kind = "application/octet-stream"
        if body is not None:
            data, kind = json.dumps(body).encode(), "application/json"
        try:
            status, reply = self.request(self.repo_url + path, method, {"Content-Type": kind}, data)
        except urllib.error.HTTPError as err:
            return err.code, err.read().decode(errors="replace")
        return status, json.loads(reply) if reply else None

    def fetch(self, url):
        return self.request(url)[1]


def build(commit, version, out, key):
    subprocess.run([Path(__file__).with_name("package"), commit, version, "beta", out],
                   env=dict(os.environ, ARENA_SIGNING_KEY=key), check=True)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("commit", nargs="?", default="origin/develop", help="dernier commit de develop par défaut")
    args = parser.parse_args()
    try:
        key = str(Path(os.environ["ARENA_SIGNING_KEY"]).resolve(strict=True))
        # Out of the environment before the build, which never sees it.
        api = Gitea("https://gitea.nessar.fr/api/v1/repos/nessar/arena-tracker", os.environ.pop("GITEA_TOKEN"))
        # Gitea's develop and beta tags, which the checks and the numbering read.
        git("fetch", "--quiet", "--force", "--tags", "origin", "develop")
        commit = git("rev-parse", "--verify", "--end-of-options", args.commit + "^{commit}")
        release_beta(api, commit, build, key)
    except (ValueError, OSError, KeyError, subprocess.CalledProcessError) as err:
        raise SystemExit(f"Erreur : {err}")
