#!/usr/bin/env python3
from __future__ import annotations

import argparse
import importlib.metadata
import sys
import tarfile
import zipfile
from pathlib import Path


def check_archive(artifact: Path, expectations: list[str]) -> list[str]:
    if artifact.suffix == ".whl" or artifact.suffix == ".zip":
        with zipfile.ZipFile(artifact) as archive:
            names = archive.namelist()
    elif artifact.name.endswith(".tar.gz"):
        with tarfile.open(artifact, "r:gz") as archive:
            names = archive.getnames()
    else:
        raise ValueError(f"Unsupported artifact type: {artifact}")

    missing = []
    for expectation in expectations:
        if not any(expectation in name for name in names):
            missing.append(expectation)
    return missing


def check_distribution(distribution: str, expectations: list[str]) -> list[str]:
    files = importlib.metadata.files(distribution) or []
    names = [str(path) for path in files]
    missing = []
    for expectation in expectations:
        if not any(expectation in name for name in names):
            missing.append(expectation)
    return missing


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--artifact", action="append", default=[])
    parser.add_argument("--distribution")
    parser.add_argument("--expect", action="append", default=[])
    args = parser.parse_args()

    if not args.expect:
        raise SystemExit("At least one --expect value is required")

    failures: list[str] = []

    for artifact_name in args.artifact:
        artifact = Path(artifact_name)
        missing = check_archive(artifact, args.expect)
        if missing:
            failures.append(f"{artifact}: missing {', '.join(missing)}")

    if args.distribution:
        missing = check_distribution(args.distribution, args.expect)
        if missing:
            failures.append(
                f"{args.distribution} installed distribution missing {', '.join(missing)}"
            )

    if failures:
        for failure in failures:
            print(failure, file=sys.stderr)
        return 1

    print("package-data-check-ok")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
