"""Regression of *literal V0.4 Markdown* (§2.2/5.1/6.1), no live HTTP.
object: SimpleNamespace fixtures; sdk: exact openai 1.109.1 + frozen MockTransport.
Exit 2 = environment unavailable, not a pass. SDK decode exceptions are reported
separately from consumer assertions. Run without -O (assertions are required).
"""
import argparse, hashlib, json, re, runpy, sys, platform
from copy import deepcopy
from importlib.metadata import version, PackageNotFoundError
from pathlib import Path
from types import SimpleNamespace as NS

BASE = Path(__file__).resolve().parent
BODY = BASE / 'K05.01.02_结构化输出与JSON约束_知识正文_V1.0.md'

def digest(raw): return hashlib.sha256(raw).hexdigest()
def block(body, heading, lang):
    start = body.index(heading)
    section = re.split(r'\n#{2,3} ', body[start:], maxsplit=1)[0]
    found = re.findall(r'```'+lang+r'\n(.*?)\n```', section, re.S)
    assert len(found) == 1, (heading, len(found))
    return found[0]

def objectify(x):
    if isinstance(x, dict): return NS(**{k: objectify(v) for k,v in x.items()})
    if isinstance(x, list): return [objectify(v) for v in x]
    return x

GOOD='{"city":"Beijing","temperature":21,"unit":"C"}'
MODEL='gpt-4o-2024-08-06'
CALL={'type':'function_call','id':'fc_fixture','call_id':'call_fixture','name':'get_weather','arguments':'{}','status':'completed'}
CHAT_CALL={'type':'function','id':'call_fixture','function':{'name':'get_weather','arguments':'{}'}}
UNKNOWN={'type':'future_unknown_item','id':'future_fixture'}
REASONING={'type':'reasoning','id':'rs_fixture','summary':[]}
PART={'type':'future_unknown_part','text':'unknown auxiliary content'}

def chat(text=GOOD, reason='stop', **message):
    return {'id':'chatcmpl_fixture','object':'chat.completion','created':0,'model':MODEL,
            'choices':[{'index':0,'finish_reason':reason,'message':{'role':'assistant','content':text,'refusal':None,**message}}]}

def part(text=GOOD): return {'type':'output_text','text':text,'annotations':[]}
def message(parts=None, **fields):
    return {'id':'msg_fixture','type':'message','role':'assistant','status':'completed','content':[part()] if parts is None else parts,**fields}
def response(output=None, status='completed', reason=None):
    return {'id':'resp_fixture','object':'response','created_at':0,'model':MODEL,'status':status,'error':None,
            'incomplete_details':{'reason':reason} if reason else None,'output':[message()] if output is None else output,
            'parallel_tool_calls':False,'tool_choice':'none','tools':[]}

def cases():
    # (name, api, wire fixture, exact decision, evaluate calls, object-only)
    out=[]
    def c(name, api, wire, expected, evals=0, object_only=False): out.append((name,api,wire,expected,evals,object_only))
    c('chat normal','chat',chat(),'accepted',1)
    c('chat empty tool_calls','chat',chat(tool_calls=[]),'accepted',1)
    c('chat null tool fields','chat',chat(tool_calls=None,function_call=None),'accepted',1)
    c('chat zero choice','chat',{**chat(),'choices':[]},'expected_one_choice')
    c('chat multi choice','chat',{**chat(),'choices':[chat()['choices'][0],{**chat()['choices'][0],'index':1}]},'expected_one_choice')
    c('chat refusal with good text','chat',chat(refusal='Fixture refusal'),'refusal')
    c('chat refusal empty string','chat',chat(refusal=''),'refusal')
    c('chat length with valid JSON','chat',chat(reason='length'),'finish:length')
    c('chat content filter','chat',chat(reason='content_filter'),'finish:content_filter')
    c('chat unknown finish','chat',chat(reason='future_unknown_finish'),'finish:future_unknown_finish')
    c('chat finish tool_calls','chat',chat(reason='tool_calls',tool_calls=[CHAT_CALL]),'finish:tool_calls')
    c('chat finish function_call','chat',chat(reason='function_call',function_call=CHAT_CALL['function']),'finish:function_call')
    c('chat stop + tool_calls','chat',chat(tool_calls=[CHAT_CALL]),'unexpected_tool_call')
    c('chat stop + legacy function_call','chat',chat(function_call=CHAT_CALL['function']),'unexpected_tool_call')
    c('chat stop + both tool fields','chat',chat(tool_calls=[CHAT_CALL],function_call=CHAT_CALL['function']),'unexpected_tool_call')
    c('chat wrong role','chat',chat(role='user'),'unexpected_message')
    c('chat unexpected audio','chat',chat(audio={'id':'audio_fixture','data':'','expires_at':0,'transcript':'fixture'}),'unexpected_message')
    c('chat missing text','chat',chat(None),'missing_text')
    c('chat blank text','chat',chat('  '),'missing_text')
    c('chat nonstring text','chat',chat(123),'missing_text',object_only=True)
    c('responses normal','responses',response(),'accepted',1)
    c('responses zero messages','responses',response([]),'expected_one_message')
    c('responses multiple messages','responses',response([message(),message([])]),'expected_one_message')
    c('responses zero text parts','responses',response([message([])]),'expected_one_text')
    c('responses multiple text parts','responses',response([message([part(),part()])]),'expected_one_text')
    c('responses only function_call','responses',response([CALL]),'unexpected_tool_call')
    c('responses good + function_call','responses',response([message(),CALL]),'unexpected_tool_call')
    c('responses function_call + good','responses',response([CALL,message()]),'unexpected_tool_call')
    c('responses good + unknown item','responses',response([message(),UNKNOWN]),'unexpected_output_item')
    c('responses unknown item + good','responses',response([UNKNOWN,message()]),'unexpected_output_item')
    c('responses good + reasoning','responses',response([message(),REASONING]),'unexpected_output_item')
    c('responses good + unknown part','responses',response([message([part(),PART])]),'unexpected_content_part')
    c('responses unknown part + good','responses',response([message([PART,part()])]),'unexpected_content_part')
    c('responses refusal only','responses',response([message([{'type':'refusal','refusal':'Fixture refusal'}])]),'refusal')
    c('responses good + refusal','responses',response([message([part(),{'type':'refusal','refusal':'Fixture refusal'}])]),'refusal')
    c('responses unknown state','responses',response(status='future_unknown_status'),'status:future_unknown_status')
    c('responses incomplete with full JSON','responses',response(status='incomplete',reason='max_output_tokens'),'incomplete:max_output_tokens')
    c('responses incomplete filter','responses',response(status='incomplete',reason='content_filter'),'incomplete:content_filter')
    c('responses incomplete no detail','responses',response(status='incomplete'),'status:incomplete')
    c('responses incomplete + refusal','responses',response([message([{'type':'refusal','refusal':'Fixture refusal'}])],status='incomplete',reason='content_filter'),'incomplete:content_filter')
    c('responses failed with good text','responses',response(status='failed'),'status:failed')
    c('responses wrong role','responses',response([message(role='user')]),'unexpected_message')
    c('responses incomplete message','responses',response([message(status='incomplete')]),'unexpected_message')
    c('responses blank text','responses',response([message([part('  ')])]),'missing_text')
    c('responses nonstring text','responses',response([message([part(123)])]),'missing_text',object_only=True)
    c('responses missing output list','responses',{**response(),'output':None},'unexpected_output_shape',object_only=True)
    c('responses missing content list','responses',response([message(content=None)]),'unexpected_content_shape',object_only=True)
    c('responses missing item discriminator','responses',response([message(),{'id':'no_type'}]),'unexpected_output_item',object_only=True)
    c('responses missing part discriminator','responses',response([message([part(),{'text':'no_type'}])]),'unexpected_content_part',object_only=True)
    for api, maker in [('chat',chat),('responses',lambda t:response([message([part(t)])]))]:
        for label,payload,expect in [('malformed',GOOD[:-1]+',}','invalid_json'),('wrong type',GOOD.replace('21','"21"'),'schema:type'),('wrong city',GOOD.replace('Beijing','Shanghai'),'business:request_mismatch'),('overflow',GOOD.replace('21','1e400'),'numeric_range')]:
            c(f'{api} {label}',api,maker(payload),expect,1)
    return out

def main():
    parser=argparse.ArgumentParser(); parser.add_argument('--mode',choices=['object','sdk'],required=True); args=parser.parse_args()
    assert __debug__, 'do not use -O'
    raw=BODY.read_bytes(); body=raw.decode('utf-8')
    print('mode:',args.mode,'Python',platform.python_version(),'body SHA-256',digest(raw),flush=True)
    print('dependencies:',end=' ')
    versions={}
    for p in ('openai','httpx','pydantic','jsonschema'):
        try: versions[p]=version(p)
        except PackageNotFoundError: versions[p]='missing'
    print(versions,flush=True)
    schema_code=block(body,'### 2.2 ','json'); consumer=block(body,'### 5.1 ','python'); validator=block(body,'### 6.1 ','python')
    for label,code in [('schema',schema_code),('consumer',consumer),('validator',validator)]: print(label,'SHA-256',digest(code.encode()))
    if args.mode=='sdk':
        required={'openai':'1.109.1','httpx':'0.28.1','pydantic':'2.11.9','jsonschema':'4.25.1'}
        if any(versions[p]!=v for p,v in required.items()):
            print('NOT_RUN fixed dependency mismatch:',required); return 2
        from openai import APIResponseValidationError
        frozen=runpy.run_path(str(BASE/'verify_structured_output.py'))
        assert frozen['SCHEMA']==json.loads(schema_code)
    ns={'SCHEMA':json.loads(schema_code)}
    exec(compile(validator,'V0.4 §6.1','exec'),ns);exec(compile(consumer,'V0.4 §5.1','exec'),ns)
    original=ns['evaluate']; calls=[]
    def observed(*a,**kw): calls.append(1);return original(*a,**kw)
    ns['evaluate']=observed
    passed=predecode=skipped=0
    for name,api,wire,expected,evals,object_only in cases():
        calls.clear(); wire=deepcopy(wire)
        if args.mode=='sdk':
            if object_only:
                print('SKIP_OBJECT_ONLY',name);skipped+=1;continue
            try: obj=frozen['mock_call'](api,'strict',wire,schema=ns['SCHEMA'])
            except APIResponseValidationError as exc:
                if expected=='accepted': raise
                print('SDK_REJECTED_BEFORE_CONSUMER',name,type(exc).__name__);predecode+=1;continue
        else: obj=objectify(wire)
        result=ns['consume_'+api](obj)
        want=(expected,json.loads(GOOD) if expected=='accepted' else None)
        assert result==want,(name,result,want)
        assert len(calls)==evals,(name,len(calls),evals)
        print('PASS',name,':',repr(result),'evaluate_calls=',len(calls));passed+=1
    print(f'SUMMARY mode={args.mode} pass={passed} sdk_rejected_before_consumer={predecode} skipped_object_only={skipped} total={len(cases())}; no real API')
    if predecode: print('NOTE SDK-layer rejected branches did not execute consumer; object-mode evidence separate.')
    return 0
if __name__=='__main__': sys.exit(main())
