from pathlib import Path

import pytest

from awspipe import __version__
from awspipe.release import prepare_publish


def test_prepare_publish_cleans_dist_and_checks_expected_artifacts(tmp_path, monkeypatch) -> None:
    dist_dir = tmp_path / "dist"
    dist_dir.mkdir()
    (dist_dir / ".gitignore").write_text("\n")
    (dist_dir / "awspipe-0.1.1.tar.gz").write_text("old")
    (dist_dir / "awspipe-0.1.1-py3-none-any.whl").write_text("old")

    calls = []

    def fake_run(command: list[str], cwd: Path) -> None:
        calls.append((command, cwd))
        if command == ["uv", "build"]:
            (dist_dir / f"awspipe-{__version__}.tar.gz").write_text("sdist")
            (dist_dir / f"awspipe-{__version__}-py3-none-any.whl").write_text("wheel")

    monkeypatch.setattr("awspipe.release._run", fake_run)

    artifacts = prepare_publish(tmp_path)

    assert [path.name for path in artifacts] == [
        f"awspipe-{__version__}.tar.gz",
        f"awspipe-{__version__}-py3-none-any.whl",
    ]
    assert sorted(path.name for path in dist_dir.iterdir()) == [
        ".gitignore",
        f"awspipe-{__version__}-py3-none-any.whl",
        f"awspipe-{__version__}.tar.gz",
    ]
    assert calls == [
        (["uv", "build"], tmp_path),
        (["uvx", "twine", "check", str(dist_dir / f"awspipe-{__version__}.tar.gz"), str(dist_dir / f"awspipe-{__version__}-py3-none-any.whl")], tmp_path),
    ]


def test_prepare_publish_raises_when_build_output_is_missing(tmp_path, monkeypatch) -> None:
    (tmp_path / "dist").mkdir()
    monkeypatch.setattr("awspipe.release._run", lambda command, cwd: None)

    with pytest.raises(RuntimeError, match="Build did not produce expected artifacts"):
        prepare_publish(tmp_path)
