#!/usr/bin/env python3
"""Compare local pyproject.toml version against the latest version on PyPI."""

import json
import sys
import urllib.error
import urllib.request

import tomli


def get_latest_version(project_name: str) -> str | None:
    """Return the latest version of the given package on PyPI."""

    url = f"https://pypi.org/pypi/{project_name}/json"
    try:
        with urllib.request.urlopen(url) as resp:  # noqa: S310
            data = json.loads(resp.read())
        version: str = data["info"]["version"]
        return version
    except urllib.error.HTTPError as e:
        # PLR2004: 404 is the HTTP status code for "not found".
        if e.code == 404:  # noqa: PLR2004
            print(f"{project_name}: not found on PyPI", file=sys.stderr)
        else:
            print(f"PyPI returned HTTP {e.code}", file=sys.stderr)
        return None


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

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

    project = doc.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(2)

    latest = get_latest_version(name)
    if not latest:
        sys.exit(2)

    if latest == version:
        print(f"{name} {version} matches PyPI")
    else:
        print(f"{name} {version} local != {latest} on PyPI")


if __name__ == "__main__":
    main()
