"""A GitHub Release carries the artifacts and their provenance.

Every tag already produced a Release, and the wheel was already attested at
build time -- but the Release carried no assets, so the attestation existed
only inside the workflow run and OpenSSF Signed-Releases reported "no releases
found" for a repository with 20 of them. An attestation nobody can fetch beside
the artifact is not provenance.
"""

from __future__ import annotations

import pathlib

import yaml

ROOT = pathlib.Path(__file__).resolve().parents[2]
RELEASE = yaml.safe_load((ROOT / ".github" / "workflows" / "release.yml").read_text())


def _steps(job: str) -> list[dict]:
    return RELEASE["jobs"][job]["steps"]


def test_the_wheel_is_attested_before_it_is_published() -> None:
    names = [step.get("uses", "") for step in _steps("publish-pypi")]

    assert any("attest-build-provenance" in use for use in names)


def test_the_artifacts_reach_the_release_job() -> None:
    """`publish-pypi` builds them; `create-release` is a different runner."""
    uploads = [step for step in _steps("publish-pypi") if "upload-artifact" in step.get("uses", "")]
    downloads = [step for step in _steps("create-release") if "download-artifact" in step.get("uses", "")]

    assert uploads and downloads
    assert uploads[0]["with"]["name"] == downloads[0]["with"]["name"]


def test_the_attestation_is_not_in_the_package_directory() -> None:
    """`gh-action-pypi-publish` uploads every file in `packages-dir`.

    2.15.0 built, attested, passed `twine check` and then failed at the upload,
    because the bundle sat in `dist/` and PyPI rejects anything that is not a
    distribution. The wheel never left the runner.
    """
    collect = next(step for step in _steps("publish-pypi") if step.get("name", "").startswith("Collect"))

    assert "dist/" not in collect["run"]

    publish = next(step for step in _steps("publish-pypi") if "pypi-publish" in step.get("uses", ""))
    assert publish["with"]["packages-dir"] == "dist/"


def test_the_download_lands_where_the_release_globs_look() -> None:
    """The two halves of the hand-off have to agree about the directory layout.

    `upload-artifact` keys a multi-path upload on the least common ancestor, so
    an artifact carrying `dist/` and `attestation/` unpacks to those names
    wherever it is put. Unpacking it under `dist/` gives `dist/dist/*.whl`;
    every glob then matches nothing and the release publishes with **no
    assets**, successfully. 2.15.0 shipped exactly that.
    """
    download = next(step for step in _steps("create-release") if "download-artifact" in step.get("uses", ""))
    release = next(step for step in _steps("create-release") if "action-gh-release" in step.get("uses", ""))

    assert download["with"]["path"] == "."
    # Every attached glob names a directory the artifact actually carries.
    upload = next(step for step in _steps("publish-pypi") if "upload-artifact" in step.get("uses", ""))
    carried = {line.strip().rstrip("/") for line in upload["with"]["path"].splitlines() if line.strip()}
    for pattern in release["with"]["files"].split():
        assert pattern.split("/")[0] in carried, f"{pattern} is not in the uploaded artifact"


def test_the_release_attaches_the_artifacts_and_the_provenance() -> None:
    release_step = next(step for step in _steps("create-release") if "action-gh-release" in step.get("uses", ""))
    attached = release_step["with"]["files"]

    assert ".whl" in attached
    assert ".tar.gz" in attached
    # The bundle is what makes the release verifiable, and what Signed-Releases
    # reads. Losing it would leave the check unscored with the assets in place.
    assert ".intoto.jsonl" in attached
