"""主写补验：仅重放原脚本的应用逻辑，不导入 SDK 或 httpx，不测试 HTTP 序列化。
原源码以 AST 提取，跳过仅依赖 SDK/httpx 的定义；其余逻辑不改写。
"""
import ast
import json
import sys
from pathlib import Path
from types import SimpleNamespace as NS

ROOT = Path(__file__).resolve().parent
SOURCE = ROOT / 'weather_tool_call_mock.py'

def load_core():
    tree = ast.parse(SOURCE.read_text(encoding='utf-8'))
    keep = []
    for node in tree.body:
        if isinstance(node, ast.Import) and any(a.name == 'httpx' for a in node.names):
            continue
        if isinstance(node, ast.ImportFrom) and node.module == 'openai':
            continue
        if isinstance(node, ast.FunctionDef) and node.name in ('mock_client', 'verify', 'main'):
            continue
        if isinstance(node, ast.If):
            continue
        keep.append(node)
    env = {'__name__': 'weather_application_core'}
    # Dataclass inspects sys.modules for its class module.
    import types
    mod = types.ModuleType(env['__name__'])
    sys.modules[mod.__name__] = mod
    exec(compile(ast.Module(body=keep, type_ignores=[]), str(SOURCE), 'exec'), mod.__dict__)
    return mod

class Obj(NS):
    def model_dump(self, exclude_none=False):
        def unwrap(x):
            if isinstance(x, Obj):
                return {k: unwrap(v) for k, v in vars(x).items() if not (exclude_none and v is None)}
            if isinstance(x, list): return [unwrap(v) for v in x]
            return x
        return unwrap(self)

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

def fake_result(core, endpoint, turn, case):
    r = core.fixture(endpoint, turn, case)
    x = obj(r)
    # Fill fields the fixed SDK models expose as optional None; not SDK emulation.
    if endpoint == 'chat':
        for c in x.choices:
            for k in ('refusal','function_call','tool_calls'):
                if not hasattr(c.message,k): setattr(c.message,k,None)
    return x

def app_replay():
    c = load_core()
    pair = ['Beijing','Shanghai']
    captures = {}
    scenarios = [('direct',0,'final',1,[],[]),('one',1,'final',2,['Beijing'],['Beijing']),
                 ('pair',1,'final',2,pair,pair[::-1]),('repeat',1,'tool_budget',2,pair,pair[::-1]),
                 ('pair',0,'tool_budget',1,[],[]),('duplicate',1,'duplicate proposal ID',1,[],[]),
                 ('refusal',1,'refusal',1,[],[]),('truncated',1,'truncated',1,[],[])]
    for endpoint in ('chat','responses'):
        for case,budget,expected,n,start,finish in scenarios:
            requests=[]; starts=[]; finishes=[]
            def create(**kwargs):
                turn=len(requests)
                requests.append(json.loads(json.dumps(kwargs)))
                return fake_result(c, endpoint, turn, case)
            client=NS(chat=NS(completions=NS(create=create)),responses=NS(create=create))
            prompt={'one':c.ONE_PROMPT,'direct':c.DIRECT_PROMPT}.get(case,c.PAIR_PROMPT)
            try:
                outcome=c.run_weather(client,endpoint,prompt,starts,finishes,budget)
                assert expected in ('final','tool_budget') and outcome.status==expected
                assert outcome.tool_batches == (1 if start else 0)
                if expected=='final': assert outcome.text=={'one':c.ONE_FINAL,'direct':c.DIRECT_FINAL}.get(case,c.PAIR_FINAL)
                else: assert outcome.text==''
            except c.ProtocolError as e:
                msg={'chat':'invalid Chat turn: length','responses':'invalid Responses turn: incomplete'}[endpoint] if expected=='truncated' else expected
                assert expected not in ('final','tool_budget') and str(e)==msg,(endpoint,case,e)
            assert len(requests)==n and starts==start and finishes==finish
            if n==2:
                h=requests[1]['messages' if endpoint=='chat' else 'input']
                proposals=c.tool_proposals(endpoint,0,start)
                if endpoint=='chat':
                    assert h[1]=={'role':'assistant','tool_calls':proposals}; results=h[2:]; key='tool_call_id'; payload='content'; ids=[p['id'] for p in proposals]
                else:
                    assert h[1:1+len(proposals)]==proposals; results=h[1+len(proposals):]; key='call_id'; payload='output'; ids=[p['call_id'] for p in proposals]
                assert [r[key] for r in results]==ids
                assert [json.loads(r[payload]) for r in results]==[{'city':v,'temperature':c.TEMPERATURES[v],'unit':'C'} for v in start]
            if case=='pair' and budget==1:
                captures[endpoint]={'request_1':requests[0],'response_1':c.fixture(endpoint,0,case),'request_2':requests[1],'response_2':c.fixture(endpoint,1,case)}
            print(f'PASS app_only {endpoint}/{case}/{budget}: app_create_calls={n}, starts={starts}, finishes={finishes}, result={expected}')
    print('16/16 application-only scenarios passed; SDK/HTTP/online not executed in this supplementary replay.')
    return captures

if __name__=='__main__':
    cap=app_replay()
    (ROOT/'application_replay_pair.json').write_text(json.dumps({'scope':'Application-level create() arguments and scripted fixture responses, not HTTP captures; supplementary replay only',**cap},ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
