#!/bin/sh
# scripts/verify_wheel_contents.sh — PR-01 supply-chain audit (build side).
#
# Inspects the built wheel(s) in dist/ and asserts:
#   1. No `tests/` directory in the wheel (test files MUST NOT ship)
#   2. No `_test.py` / `_test_*.py` files (test modules MUST NOT ship)
#   3. The expected SDK files are present (mgf/hrb/__init__.py + fmt.py + py.typed)
#
# Intended to run AFTER `python -m build` (or `uv build`) as a CI step.
# Exit codes: 0 wheel clean; 1 violation found; 2 no wheel found.

set -eu

REPO_ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
WHEEL=$(ls "$REPO_ROOT"/dist/mgf_hrb-*.whl 2>/dev/null | head -n1 || true)

if [ -z "$WHEEL" ]; then
    printf 'ERROR: no wheel found in dist/. Run `python -m build` first.\n' >&2
    exit 2
fi

printf 'verifying wheel contents: %s\n' "$WHEEL"

# Use unzip -Z1 (file list only, no header). Falls back to `zipinfo` if unzip lacks -Z.
LIST=$(unzip -Z1 "$WHEEL" 2>/dev/null || zipinfo -1 "$WHEEL")

# Rule 1 — no tests/ directory
if printf '%s\n' "$LIST" | grep -E '^tests/' >/dev/null; then
    printf 'FAIL: wheel contains tests/ directory:\n' >&2
    printf '%s\n' "$LIST" | grep -E '^tests/' | head -20 >&2
    exit 1
fi

# Rule 2 — no _test.py files
if printf '%s\n' "$LIST" | grep -E '(_test\.py$|/test_)' >/dev/null; then
    printf 'FAIL: wheel contains test modules:\n' >&2
    printf '%s\n' "$LIST" | grep -E '(_test\.py$|/test_)' | head -20 >&2
    exit 1
fi

# Rule 3 — required SDK files present
for required in mgf/hrb/__init__.py mgf/hrb/fmt.py mgf/hrb/py.typed; do
    if ! printf '%s\n' "$LIST" | grep -F "$required" >/dev/null; then
        printf 'FAIL: wheel missing required file: %s\n' "$required" >&2
        exit 1
    fi
done

printf 'OK — wheel contents clean: no tests, all required SDK files present.\n'
