#!/usr/bin/env python3
"""Publish a beta of develop or a stable of main 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 channel(version):
    """The package contract's channel: beta for X.Y.Z-beta.N, stable for X.Y.Z."""
    return "beta" if "-beta." in version else "stable"


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


def files(version):
    kind = channel(version)
    return {f"ArenaTracker-{kind}-Setup.exe", f"release-{kind}.json", f"release-{kind}.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 matches(folder, commit, version, key):
    """Whether the folder's manifest, signature and package are the signed release of version at commit."""
    manifest = folder / f"release-{channel(version)}.json"
    signed = subprocess.run(["openssl", "pkeyutl", "-verify", "-inkey", key, "-rawin",
                             "-in", manifest, "-sigfile", manifest.with_suffix(".sig")], capture_output=True)
    digest = base64.b64encode(hashlib.sha256((folder / package_file(version)).read_bytes()).digest()).decode()
    return not signed.returncode and json.loads(manifest.read_bytes()) == {
        "app": "ArenaTracker", "target": "win-x64", "channel": channel(version), "version": version,
        "commit": commit, "package": package_file(version), "sha256": digest,
    }


def check(api, release, commit, version, key):
    """Accept a published Release only if it is the complete, signed release of this commit, in its channel."""
    assets = {asset["name"]: asset for asset in release["assets"]}
    if set(assets) != files(version) or release["prerelease"] != (channel(version) == "beta"):
        raise ValueError(f"La Release publiée {version} est incomplète ou mal marquée (préversion) : rien n’est remplacé")
    with tempfile.TemporaryDirectory() as work:
        for name in files(version) - {f"ArenaTracker-{channel(version)}-Setup.exe"}:
            (Path(work) / name).write_bytes(api.fetch(assets[name]["browser_download_url"]))
        if not matches(Path(work), commit, version, key):
            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 Release, a prerelease for a beta, or reuse it if a previous run did."""
    tag = f"v{version}"
    beta = channel(version) == "beta"
    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 matches(out, commit, version, key):
            raise ValueError(f"La compilation n’a pas produit la {version} signée du commit {commit} : rien n’est publié")
        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 release:
            # 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)
        else:
            # The target places a tag that only exists locally on this commit, not on the default branch.
            # Gitea 28.1 then lists unrelated files in its reply: a new draft has none, so they are ignored.
            release = expect(api.call("POST", "/releases", {
                "tag_name": tag, "target_commitish": commit, "name": f"Arena Tracker {version}",
                "body": f"Commit {commit}", "draft": True, "prerelease": beta}), 201)
        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": beta}), 200)
    print(f"{version} publiée au commit {commit}")


def ready(api, commit, branch):
    """Refuse a commit absent from the branch on Gitea, or whose CI checks did not pass."""
    if subprocess.run(["git", "merge-base", "--is-ancestor", commit, f"refs/remotes/origin/{branch}"]).returncode:
        raise ValueError(f"Le commit {commit} n’est pas dans {branch} 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é")


def release_stable(api, commit, build, key):
    """Publish the cycle target as a stable at the commit, provided it is on main and its CI checks passed."""
    ready(api, commit, "main")
    version = target(commit)
    tagged = tagged_commit(f"v{version}")
    if tagged not in (None, commit):
        raise ValueError(f"Le tag v{version} est déjà au commit {tagged} : il ne se déplace pas, "
                         "fixer la version suivante dans Cargo.toml")
    publish(api, commit, version, tagged == commit, build, key)


def release_beta(api, commit, build, key):
    """Publish the commit's beta, provided it is on develop and its CI checks passed."""
    ready(api, commit, "develop")
    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, channel(version), out],
                   env=dict(os.environ, ARENA_SIGNING_KEY=key), check=True)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("channel", choices=("beta", "stable"))
    parser.add_argument("commit", nargs="?", help="dernier commit de develop (beta) ou de main (stable) par défaut")
    args = parser.parse_args()
    branch, release_channel = {"beta": ("develop", release_beta), "stable": ("main", release_stable)}[args.channel]
    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 branch and version tags, which the checks and the numbering read.
        git("fetch", "--quiet", "--force", "--tags", "origin", branch)
        commit = git("rev-parse", "--verify", "--end-of-options", (args.commit or f"origin/{branch}") + "^{commit}")
        release_channel(api, commit, build, key)
    except (ValueError, OSError, KeyError, subprocess.CalledProcessError) as err:
        raise SystemExit(f"Erreur : {err}")
