"""合成离线样本检查。与同名 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 closed(rows):
        calls={};outs={}
        for i,r in enumerate(rows):
            if r['type']=='function_call':
                if r['call_id'] in calls:return False
                calls[r['call_id']]=i
            if r['type']=='function_call_output':
                if r['call_id'] in outs:return False
                outs[r['call_id']]=i
        return set(calls)==set(outs) and all(calls[k]<outs[k] for k in calls)
    assert closed(d['history']);assert not closed(d['history'][-1:])
    indexes=[i for i,r in enumerate(d['history']) if r.get('call_id')==d['retain_group']]
    assert indexes==d['expected_indexes']
    pruned=[d['history'][i] for i in indexes];assert closed(pruned)
    assert not closed(d['history'][2:])
    return {'retained_indexes':indexes,'pruned':pruned,'naive_tail_rejected':True,'damaged_input_rejected':True}

if __name__=='__main__':
    base=Path(__file__).resolve().parent
    data=json.loads((base/'a029.json').read_text('utf-8'))
    result=verify(data,base)
    print(json.dumps({'id':'A029','passed':True,'result':result},ensure_ascii=True))
