from __future__ import annotations

import subprocess
from pathlib import Path

from awspipe import __version__

DIST_KEEP = {".gitignore"}


def _run(command: list[str], cwd: Path) -> None:
    subprocess.run(command, cwd=cwd, check=True)


def _clean_dist(dist_dir: Path) -> None:
    dist_dir.mkdir(exist_ok=True)
    for path in dist_dir.iterdir():
        if path.name in DIST_KEEP:
            continue
        if path.is_dir():
            raise RuntimeError(f"Unexpected directory in dist: {path.name}")
        path.unlink()


def _expected_artifacts(dist_dir: Path) -> list[Path]:
    return [
        dist_dir / f"awspipe-{__version__}.tar.gz",
        dist_dir / f"awspipe-{__version__}-py3-none-any.whl",
    ]


def prepare_publish(project_root: Path) -> list[Path]:
    dist_dir = project_root / "dist"
    _clean_dist(dist_dir)
    _run(["uv", "build"], cwd=project_root)

    artifacts = _expected_artifacts(dist_dir)
    missing = [str(path.name) for path in artifacts if not path.exists()]
    if missing:
        raise RuntimeError(f"Build did not produce expected artifacts: {', '.join(missing)}")

    _run(["uvx", "twine", "check", *[str(path) for path in artifacts]], cwd=project_root)
    return artifacts


def main() -> None:
    project_root = Path(__file__).resolve().parents[2]
    artifacts = prepare_publish(project_root)
    print("Prepared artifacts for uv publish:")
    for artifact in artifacts:
        print(f"- {artifact.relative_to(project_root)}")
