import argparse, hashlib, json, tempfile, wave
from pathlib import Path

def inspect(path):
    with wave.open(str(path), "rb") as f:
        if f.getsampwidth() != 2 or f.getnchannels() not in (1, 2) or f.getframerate() <= 0 or f.getnframes() <= 0:
            raise ValueError("Unsupported or empty PCM WAV")
        raw = f.readframes(f.getnframes())
        if len(raw) != f.getnframes() * f.getnchannels() * 2:
            raise ValueError("Truncated PCM frames")
        return {"name": path.name, "sampleRate": f.getframerate(), "channels": f.getnchannels(), "frames": f.getnframes(), "seconds": f.getnframes() / f.getframerate(), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}

def main():
    p = argparse.ArgumentParser(); p.add_argument("--file", type=Path); p.add_argument("--self-test", action="store_true"); a = p.parse_args()
    root = Path(__file__).resolve().parent
    if a.self_test:
        with tempfile.TemporaryDirectory() as tmp:
            bad = Path(tmp) / "bad.wav"; bad.write_bytes(b"not a WAV")
            try: inspect(bad)
            except (ValueError, EOFError, wave.Error): pass
            else: raise AssertionError("Bad WAV accepted")
            empty = Path(tmp) / "empty.wav"
            with wave.open(str(empty), "wb") as f: f.setparams((1, 2, 48000, 0, "NONE", "not compressed"))
            try: inspect(empty)
            except ValueError: pass
            else: raise AssertionError("Empty WAV accepted")
        print("Two invalid audio inputs rejected")
        return
    files = [a.file] if a.file else sorted(root.glob("*.wav"))
    if not files: raise ValueError("No WAV files to check")
    records = [inspect(file) for file in files]
    expected_file = root / "input-hashes.json"
    if not a.file and expected_file.exists():
        for name, expected in json.loads(expected_file.read_text()).items():
            file = root / name
            if hashlib.sha256(file.read_bytes()).hexdigest() != expected: raise ValueError("Original fixture changed: " + name)
    print(json.dumps({"audio": records, "boundary": "File validation alone does not prove separation quality, words, model execution or AV sync"}, ensure_ascii=False, indent=2))

if __name__ == "__main__": main()
