"""合成离线样本检查。与同名 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 split(rows):
        out=[];current=b''
        for row in rows:
            line=(json.dumps(row,ensure_ascii=False,separators=(',',':'))+'\n').encode()
            if len(line)>d['budget_bytes']:raise ValueError('单行超预算')
            if current and len(current)+len(line)>d['budget_bytes']:out.append(current);current=b''
            current+=line
        if current:out.append(current)
        return out
    parts=split(d['requests']);assert len(parts)==3
    joined=[]
    for part,item in zip(parts,d['shards']):
        actual=(base/item['file']).read_bytes();assert actual==part and len(actual)==item['bytes']<=d['budget_bytes']
        lines=actual.splitlines();assert len(lines)==item['lines'];joined.extend(json.loads(x) for x in lines)
    assert joined==d['requests'];assert split([])==[]
    assert rejected(lambda:split([d['oversize']]))
    return {'shards':d['shards'],'roundtrip_records':len(joined),'oversize_rejected':True,'submitted':False}

if __name__=='__main__':
    base=Path(__file__).resolve().parent
    data=json.loads((base/'a032.json').read_text('utf-8'))
    result=verify(data,base)
    print(json.dumps({'id':'A032','passed':True,'result':result},ensure_ascii=True))
