"""合成离线样本检查。与同名 JSON 及文中列出的附件放在同一目录运行。"""
from pathlib import Path, PurePosixPath
import base64, hashlib, io, inspect, json, math, re, subprocess, sys, tempfile, wave, zipfile
from collections import Counter, defaultdict
from datetime import date, datetime
from decimal import Decimal
sys.dont_write_bytecode=True

def sha(b): return hashlib.sha256(b).hexdigest()
def rejected(fn):
    try: fn()
    except (ValueError,TypeError,KeyError,UnicodeError,OverflowError): return True
    return False

def git(root,*args,input=None,check=True):
    r=subprocess.run(['git','-c','core.autocrlf=false',*args],cwd=root,input=input,capture_output=True,check=check)
    return r

def verify(d,base):
    def read(path):
        with wave.open(str(path),'rb') as f:
            channels=f.getnchannels();width=f.getsampwidth();rate=f.getframerate();frames=f.getnframes();payload=f.readframes(frames)
        expected_bytes=frames*channels*width
        if len(payload)!=expected_bytes:raise ValueError('数据截断')
        return {'channels':channels,'sample_width':width,'rate':rate,'frames':frames,'duration_seconds':frames/rate,'pcm_bytes':len(payload)}
    out=read(base/d['good_file']);assert out==d['expected'];rejected_files=[]
    for name in d['bad_files']:
        try:read(base/name)
        except (wave.Error,EOFError,ValueError):rejected_files.append(name)
    assert rejected_files==d['bad_files']
    return {'header_and_data':out,'rejected':rejected_files,'asr_called':False}

if __name__=='__main__':
    base=Path(__file__).resolve().parent
    data=json.loads((base/'a042.json').read_text('utf-8'))
    result=verify(data,base)
    print(json.dumps({'id':'A042','passed':True,'result':result},ensure_ascii=True))
