"""Generate SHA256 checksums for release artifacts."""

from __future__ import annotations

import hashlib
import sys
from pathlib import Path


def sha256sum(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(8192), b""):
            digest.update(chunk)
    return digest.hexdigest()


def main(dist_dir: Path) -> None:
    if not dist_dir.exists():
        raise SystemExit(f"Distribution directory {dist_dir} does not exist.")
    output = dist_dir / "SHA256SUMS"
    lines: list[str] = []
    for artifact in sorted(dist_dir.iterdir()):
        if artifact.is_file() and artifact.suffix in {".whl", ".tar.gz", ".zip"}:
            checksum = sha256sum(artifact)
            lines.append(f"{checksum}  {artifact.name}")
    output.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
    print(f"[aurora-se] Checksums written to {output}")


if __name__ == "__main__":
    target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("dist")
    main(target)
