"""Maintainer check: is our pinned upstream release still the latest?

    poetry run python -m dnd5e_db.check

Exit 0 when the pin matches upstream's latest release, 1 when upstream has
published something newer (time to run the bump workflow), 2 on lookup
failure.
"""

from __future__ import annotations

import json
import sys
import urllib.request

from dnd5e_db.fetch import UPSTREAM_REPO, UPSTREAM_TAG


def fetch_latest_tag(repo: str = UPSTREAM_REPO) -> str:
    request = urllib.request.Request(
        f"https://api.github.com/repos/{repo}/releases/latest",
        headers={"User-Agent": "5e-database-sqlite", "Accept": "application/vnd.github+json"},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)["tag_name"]


def compare(pinned: str, latest: str) -> int:
    if pinned == latest:
        print(f"up to date: pinned {pinned} is upstream's latest release")
        return 0
    print(f"update available: pinned {pinned}, but upstream latest is {latest}")
    print("bump workflow: edit upstream-tag in pyproject.toml, run fetch,")
    print("validate, update README, commit together")
    return 1


def main() -> None:
    try:
        latest = fetch_latest_tag()
    except OSError as exc:
        print(f"error: could not query upstream releases: {exc}", file=sys.stderr)
        sys.exit(2)
    sys.exit(compare(UPSTREAM_TAG, latest))


if __name__ == "__main__":
    main()
