"""Teaching-only logical provider. No SDK, network, keys, files or tool execution."""
import copy
import json


def serialize_request(request, capabilities):
    if request.get('stream') and not capabilities.get('stream'):
        raise ValueError('此适配器不支持流式')
    if request.get('tools') and not capabilities.get('tools'):
        raise ValueError('此适配器不支持工具调用')
    if request.get('model') != 'demo':
        raise ValueError('本例只接受 demo 模型标记')
    # This is a logical teaching wire format, NOT an API request schema.
    return json.dumps(request, ensure_ascii=False).encode('utf-8')


def finalize(calls, reason, usage, error=None):
    result = dict(status='failed', finish_reason=reason,
                  calls=[], usage=dict(usage), error=error)
    if error:
        return result
    if reason not in ('stop', 'tool_calls'):
        result['error'] = '缺少正常终止，或返回被截断'
        return result
    if (reason == 'stop' and calls) or (reason == 'tool_calls' and not calls):
        result['error'] = '终止原因与调用内容矛盾'
        return result
    ready = []
    for call_id, call in calls.items():
        try:
            if not call['ended'] or call['name'] != 'read_file':
                raise ValueError
            args = json.loads(''.join(call['parts']))
            if (not isinstance(args, dict) or set(args) != {'path'}
                    or not isinstance(args['path'], str) or not args['path'].strip()):
                raise ValueError
        except (ValueError, TypeError):
            result['error'] = '调用未完成，或参数不符合约定'
            return result
        ready.append(dict(id=call_id, name=call['name'], args=args))
    result.update(status='ok', calls=ready)
    return result


def collect(events):
    calls, usage, text, replay = {}, {}, [], []
    reason, error, cancelled = None, None, False
    try:
        for event in events:
            kind = event['type']
            if kind == 'usage':  # Normalized cumulative snapshot, not a delta.
                for key, value in event['data'].items():
                    if key not in ('input', 'output', 'cached') or type(value) is not int or value < 0:
                        raise ValueError('非法用量快照')
                    if key in usage and value < usage[key]:
                        raise ValueError('用量快照倒退')
                    usage[key] = value
                continue
            if kind in ('error', 'cancel'):
                error = event.get('message') or '上游失败'
                cancelled = kind == 'cancel'
                break
            if reason is not None:
                raise ValueError('语义结束之后仍有内容事件')
            if kind == 'finish':
                reason = event['reason']
                continue
            if kind == 'text':
                text.append(event['text'])
                continue
            if kind == 'provider_item':
                replay.append(copy.deepcopy(event['data']))
                continue
            call_id = event.get('id')
            if kind == 'call_start':
                if not isinstance(call_id, str) or not call_id or call_id in calls:
                    raise ValueError('调用标识缺失或重复')
                calls[call_id] = dict(name=event['name'], parts=[], ended=False)
                continue
            if call_id not in calls or calls[call_id]['ended']:
                raise ValueError('分片没有对应的未结束调用')
            if kind == 'args' and isinstance(event['text'], str):
                calls[call_id]['parts'].append(event['text'])
            elif kind == 'call_end':
                calls[call_id]['ended'] = True
            else:
                raise ValueError('未知教学事件')
    except (ValueError, KeyError, TypeError, OSError) as exc:
        # Only fixture errors in this simulation. Real upstream messages need redaction.
        error = str(exc) or type(exc).__name__
    result = finalize(calls, reason, usage, error)
    if cancelled:
        result['status'] = 'cancelled'
    result.update(text=''.join(text), replay_items=replay)
    return result


def next_history(history, reply, results):
    if reply['status'] != 'ok':
        raise ValueError('失败返回不能提交为可执行调用')
    expected = {call['id'] for call in reply['calls']}
    if set(results) != expected:
        raise ValueError('工具结果必须和调用 ID 一一对应')
    # These are INTERNAL teaching items, NOT vendor-native API items.
    items = copy.deepcopy(history) + copy.deepcopy(reply['replay_items'])
    for call in reply['calls']:
        items.append(dict(type='tool_call', **copy.deepcopy(call)))
    for call in reply['calls']:
        items.append(dict(type='tool_result', call_id=call['id'], output=results[call['id']]))
    return items


def sample():
    return [
        {'type':'usage', 'data':{'input':40, 'output':1}},
        {'type':'text', 'text':'先读实现和测试。'},
        {'type':'provider_item', 'data':{'opaque':'synthetic-replay-item'}},
        {'type':'call_start', 'id':'c1', 'name':'read_file'},
        {'type':'call_start', 'id':'c2', 'name':'read_file'},
        {'type':'args', 'id':'c1', 'text':'{"path":"src/'},
        {'type':'args', 'id':'c2', 'text':'{"path":"tests/test_convert.py"}'},
        {'type':'call_end', 'id':'c2'},
        {'type':'args', 'id':'c1', 'text':'convert.py"}'},
        {'type':'call_end', 'id':'c1'},
        {'type':'finish', 'reason':'tool_calls'},
        {'type':'usage', 'data':{'input':40, 'output':8, 'cached':20}},
    ]


if __name__ == '__main__':
    history = [{'role':'user', 'content':'修好 2m 返回 2 的问题'}]
    request = dict(model='demo', history=history, tools=[{'name':'read_file'}], stream=True)
    serialize_request(request, dict(stream=True, tools=True))
    ok = collect(sample())
    print('正常：', json.dumps(ok, ensure_ascii=False))
    failed = collect(sample()[:10] + [{'type':'error', 'message':'模拟流尾错误'}])
    print('失败：', json.dumps(failed, ensure_ascii=False))
    cancelled = collect(sample()[:10] + [{'type':'cancel', 'message':'模拟用户取消'}])
    print('取消：', json.dumps(cancelled, ensure_ascii=False))
    resumed = next_history(history, ok, {'c1':'假实现内容', 'c2':'假测试内容'})
    print('下一轮内部记录：', json.dumps(resumed, ensure_ascii=False))
