"""合成离线样本检查。与同名 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):
    from PIL import Image,__version__ as pillow_version
    def audit(url):
        header,sep,payload=url.partition(',')
        allowed={'data:image/png;base64':'PNG','data:image/jpeg;base64':'JPEG'}
        if not sep or header not in allowed:return 'header_rejected',None
        try:raw=base64.b64decode(payload,validate=True)
        except ValueError:return 'invalid_base64',None
        if len(raw)>d['max_decoded_bytes']:return 'byte_budget',None
        try:
            with Image.open(io.BytesIO(raw)) as image:fmt=image.format;image.verify()
            with Image.open(io.BytesIO(raw)) as image:image.load()
        except (OSError,ValueError,SyntaxError):return 'invalid_image',None
        if fmt!=allowed[header]:return 'mime_mismatch',None
        return 'accepted',raw
    out=[audit(s) for s in d['urls']]
    assert [x[0] for x in out]==d['expected'];assert out[0][1]==(base/d['source_file']).read_bytes()
    return {'decisions':[x[0] for x in out],'normal_bytes_preserved':True,'pillow_version':pillow_version,'uploaded':False}

if __name__=='__main__':
    base=Path(__file__).resolve().parent
    data=json.loads((base/'a040.json').read_text('utf-8'))
    result=verify(data,base)
    print(json.dumps({'id':'A040','passed':True,'result':result},ensure_ascii=True))
