#!/usr/bin/env python3
"""Check if the build version in ./pyproject.toml is published on PyPI."""

import sys
import urllib.error
import urllib.request

import tomli


def main() -> None:
    """CLI entry point."""

    try:
        with open("pyproject.toml", "rb") as f:
            data = tomli.load(f)
    except FileNotFoundError:
        print("No pyproject.toml found in current directory", file=sys.stderr)
        sys.exit(1)

    project = data.get("project", {})
    name = project.get("name")
    version = project.get("version")

    if not name or not version:
        print("pyproject.toml missing project name or version", file=sys.stderr)
        sys.exit(1)

    url = f"https://pypi.org/pypi/{name}/{version}/json"
    try:
        with urllib.request.urlopen(url):  # noqa: S310
            print(f"{name} {version} is on PyPI")
    except urllib.error.HTTPError as e:
        # PLR2004: 404 is the HTTP status code for "not found".
        if e.code == 404:  # noqa: PLR2004
            print(f"{name} {version} is NOT on PyPI")
            sys.exit(1)
        else:
            print(f"PyPI returned HTTP {e.code}", file=sys.stderr)
            sys.exit(2)


if __name__ == "__main__":
    main()
