"""Inspect a bounded PCM WAV container, not speech quality or model identity."""

import argparse
import json
import wave
from pathlib import Path


def inspect_wav(path, max_bytes=25_000_000):
    if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes <= 0:
        raise ValueError('max_bytes must be a positive integer')
    path = Path(path)
    if not path.is_file() or path.stat().st_size > max_bytes:
        raise ValueError('Missing file or file exceeds the inspection byte limit')
    try:
        with wave.open(str(path), 'rb') as audio:
            rate, channels = audio.getframerate(), audio.getnchannels()
            width, frames = audio.getsampwidth(), audio.getnframes()
            if audio.getcomptype() != 'NONE' or width not in (1, 2, 3, 4):
                raise ValueError('This checker supports integer PCM WAV only')
            if min(rate, channels, frames) <= 0:
                raise ValueError('Positive rate, channels and frame count are required')
            data = audio.readframes(frames + 1)
            if len(data) != frames * channels * width:
                raise ValueError('Audio frame data does not match the declared length')
    except (wave.Error, EOFError) as error:
        raise ValueError('Not a supported PCM WAV container') from error
    silence_byte = 128 if width == 1 else 0
    digital_silence = all(byte == silence_byte for byte in data)
    return {'status': 'STRUCTURAL_CHECK_COMPLETE_NOT_SPEECH_ACCEPTANCE',
            'sampleRateHz': rate, 'channels': channels, 'sampleWidthBytes': width,
            'frames': frames, 'durationSeconds': frames / rate,
            'digitalSilenceDetected': digital_silence,
            'speechAcceptanceVerified': False, 'speakerIdentityVerified': False,
            'networkRequests': 0}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('path')
    args = parser.parse_args()
    try:
        print(json.dumps(inspect_wav(args.path), indent=2))
    except (OSError, ValueError) as error:
        parser.exit(1, str(error) + '\n')
