import copy
import json
from pathlib import Path
import unittest
from stream_demo import collect, finalize, next_history, sample, serialize_request

class ProviderTests(unittest.TestCase):
    def reject(self, events, status='failed'):
        reply=collect(events)
        self.assertEqual(reply['status'],status)
        self.assertEqual(reply['calls'],[])
        return reply

    def test_interleaved_calls(self):
        r=collect(sample());self.assertEqual(r['status'],'ok')
        self.assertEqual([c['args']['path'] for c in r['calls']],['src/convert.py','tests/test_convert.py'])

    def test_all_split_points(self):
        text='{"path":"src/中文.py"}'
        for i in range(len(text)+1):
            e=[{'type':'call_start','id':'a','name':'read_file'},
               {'type':'args','id':'a','text':text[:i]},
               {'type':'args','id':'a','text':text[i:]},
               {'type':'call_end','id':'a'},{'type':'finish','reason':'tool_calls'}]
            self.assertEqual(collect(e)['calls'][0]['args']['path'],'src/中文.py')

    def test_json_complete_without_finish(self): self.reject(sample()[:10])
    def test_missing_call_end(self): self.reject([e for e in sample() if not(e['type']=='call_end' and e['id']=='c1')])
    def test_bad_json(self):
        e=sample();e[8]['text']='bad';self.reject(e)
    def test_schema_invalid(self):
        for value in [[],{}, {'path':0},{'path':' '},{'path':'x','extra':1}]:
            e=sample();e[5]['text']=json.dumps(value);e[8]['text']='';self.reject(e)
    def test_non_success_reason(self):
        for reason in ['length','content_filter','unknown']:
            e=sample();e[10]['reason']=reason;self.reject(e)
    def test_error_after_valid_json_preserves_usage_reason(self):
        r=self.reject(sample()[:10]+[{'type':'error','message':'合成错误原因'}])
        self.assertEqual(r['error'],'合成错误原因');self.assertEqual(r['usage'],{'input':40,'output':1})
    def test_error_after_finish(self): self.reject(sample()+[{'type':'error','message':'模拟结束异常'}])
    def test_cancel_preserves_latest_known_usage(self):
        r=self.reject(sample()[:10]+[{'type':'cancel','message':'模拟取消'}], 'cancelled')
        self.assertEqual(r['usage']['input'],40)
    def test_cumulative_usage_replaces_not_adds(self):
        self.assertEqual(collect(sample())['usage'],{'input':40,'output':8,'cached':20})
    def test_missing_usage_unknown(self):
        self.assertEqual(collect([e for e in sample() if e['type']!='usage'])['usage'],{})
    def test_usage_after_finish_is_metadata(self): self.assertEqual(collect(sample())['status'],'ok')
    def test_bad_usage(self):
        for v in [-1,True,'10']:
            self.reject([{'type':'usage','data':{'input':v}}])
    def test_usage_cannot_decrease(self):
        self.reject([{'type':'usage','data':{'input':10}},{'type':'usage','data':{'input':9}}])
    def test_unknown_id(self):
        e=sample();e[5]['id']='missing';self.reject(e)
    def test_duplicate_id(self):
        e=sample();e[4]['id']='c1';self.reject(e)
    def test_data_after_call_end(self):
        e=sample();e.insert(8,{'type':'args','id':'c2','text':' '});self.reject(e)
    def test_data_after_finish(self): self.reject(sample()+[{'type':'text','text':'late'}])
    def test_unknown_event(self): self.reject([{'type':'unknown'}])
    def test_transport_exception(self):
        def stream():
            yield from sample()[:10]
            raise OSError('模拟断线')
        r=self.reject(stream());self.assertEqual(r['error'],'模拟断线');self.assertEqual(r['usage']['input'],40)
    def test_plain_text_response(self):
        r=collect([{'type':'text','text':'说明'},{'type':'finish','reason':'stop'}])
        self.assertEqual(r['status'],'ok');self.assertEqual(r['text'],'说明')
    def test_finish_content_mismatch(self):
        e=sample();e[10]['reason']='stop';self.reject(e)
        self.reject([{'type':'finish','reason':'tool_calls'}])
    def test_opaque_items_kept(self):
        r=collect(sample());self.assertEqual(r['replay_items'],[{'opaque':'synthetic-replay-item'}])
    def test_result_association(self):
        h=[{'role':'user','content':'任务'}];before=copy.deepcopy(h)
        r=collect(sample());n=next_history(h,r,{'c2':'测试','c1':'实现'})
        self.assertEqual(h,before)
        self.assertEqual([x['call_id'] for x in n if x.get('type')=='tool_result'],['c1','c2'])
        self.assertIn({'opaque':'synthetic-replay-item'},n)
    def test_missing_or_unknown_tool_result_rejected(self):
        for results in [{},{'c1':'x'},{'c1':'x','c2':'y','extra':'z'}]:
            with self.assertRaises(ValueError): next_history([],collect(sample()),results)
    def test_failed_reply_cannot_continue(self):
        with self.assertRaises(ValueError):next_history([],collect(sample()[:10]),{})
    def test_capability_failure_before_serialization(self):
        request=dict(model='demo',stream=True,tools=[{'name':'read_file'}])
        for cap in [dict(stream=False,tools=True),dict(stream=True,tools=False)]:
            with self.assertRaises(ValueError): serialize_request(request,cap)
    def test_request_roundtrip_no_mutation(self):
        r=dict(model='demo',stream=True,history=[{'role':'user','content':'任务'}],tools=[])
        self.assertEqual(json.loads(serialize_request(r,dict(stream=True,tools=True))),r)
    def test_one_bad_call_commits_none(self):
        e=sample();e[4]['name']='unknown';self.reject(e)

if __name__=='__main__':
    result=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(ProviderTests))
    Path(__file__).with_name('test-results.json').write_text(json.dumps(dict(tests=result.testsRun,failures=len(result.failures),errors=len(result.errors),success=result.wasSuccessful()),ensure_ascii=False,indent=2))
    raise SystemExit(not result.wasSuccessful())
