"""Teaching-only agentic loop. Python 3.9+ stdlib; no network, keys or real tools.

The scripted model below picks its next step from history; the loop never
plans an order. The loop only decides whether a step may happen (budget,
cancel) and keeps history closed: every call it records gets one result.
"""
import json
import time
from copy import deepcopy

EXIT_CODES = {'completed': 0, 'failed': 1, 'stopped': 4, 'cancelled': 130}
SOFT_LANDING_AT = (4, 2, 1)  # remaining requests; one note per newly crossed threshold


class Cancel:
    """Set by the surface (Esc). The loop and the tools only read it."""

    def __init__(self):
        self.requested = False

    def request(self):
        self.requested = True


class Budget:
    """Independently optional limits. None means unlimited."""

    def __init__(self, max_turns=None, max_tool_calls=None, max_cost=None,
                 max_wall_ms=None, clock=None):
        self.limits = {'turns': max_turns, 'tool_calls': max_tool_calls,
                       'cost': max_cost, 'wall_ms': max_wall_ms}
        for name, value in self.limits.items():
            if value is not None and (type(value) is not int or value <= 0):
                raise ValueError('%s 必须是正整数或 None' % name)
        self.clock = clock or (lambda: int(time.monotonic() * 1000))
        self.started = self.clock()
        self.used = {'turns': 0, 'tool_calls': 0, 'cost': 0, 'wall_ms': 0}
        self.noted = 0  # soft-landing thresholds already delivered

    def exhausted(self, skip_turns=False):
        self.used['wall_ms'] = self.clock() - self.started
        counts = ('tool_calls',) if skip_turns else ('turns', 'tool_calls')
        for dim in counts:  # counts are used up once they reach the limit
            limit = self.limits[dim]
            if limit is not None and self.used[dim] >= limit:
                return dim
        for dim in ('cost', 'wall_ms'):  # receipts: stop once exceeded
            limit = self.limits[dim]
            if limit is not None and self.used[dim] > limit:
                return dim
        return None

    def admit_turn(self):
        stop = self.exhausted()
        if stop is None:
            self.used['turns'] += 1
        return stop

    def admit_calls(self, count):
        """All or nothing for one batch of calls from the same reply."""
        stop = self.exhausted(skip_turns=True)
        limit = self.limits['tool_calls']
        if stop is None and limit is not None and self.used['tool_calls'] + count > limit:
            stop = 'tool_calls'
        if stop is None:
            self.used['tool_calls'] += count
        return stop

    def record_cost(self, cost):
        self.used['cost'] += cost  # already spent; checked at the next admission

    def soft_landing(self):
        limit = self.limits['turns']
        if limit is None:
            return None
        left = limit - self.used['turns']
        crossed = sum(1 for at in SOFT_LANDING_AT if left <= at)
        if left <= 0 or crossed <= self.noted:
            return None
        self.noted = crossed
        return ('[额度提醒] 这次运行还剩 %d 次模型请求（上限 %d）。先做最要紧、还没验证的部分；'
                '做不完就写清进度和下一步。不要因为额度快用完就宣布完成。' % (left, limit))


def calls_are_closed(history):
    """Every recorded call has exactly one result and no result is orphaned."""
    open_ids = set()
    for item in history:
        if item['role'] == 'tool':
            if item['tool_call_id'] not in open_ids:
                return False
            open_ids.discard(item['tool_call_id'])
            continue
        if open_ids:
            return False  # something else arrived before all results came back
        if item['role'] == 'assistant':
            ids = [call['id'] for call in item.get('tool_calls', [])]
            if len(set(ids)) != len(ids):
                return False
            open_ids = set(ids)
    return not open_ids


def finish_reply(text, calls, reason, usage):
    cost = usage.get('input_tokens', 0) + 4 * usage.get('output_tokens', 0)
    if reason == 'length':
        return {'status': 'truncated', 'text': text, 'calls': [], 'cost': cost}
    normal = (reason == 'stop' and not calls) or (reason == 'tool_calls' and calls)
    if not normal:
        return {'status': 'error', 'error': 'finish_mismatch', 'text': text,
                'calls': [], 'cost': cost}
    return {'status': 'ok', 'text': text, 'calls': calls, 'cost': cost}


def stream_reply(model, history, cancel, emit):
    """Consume one streamed reply. Text reaches the surface at once; calls are
    handed back only after a normal finish."""
    text, calls = [], []
    stream = iter(model(deepcopy(history)))
    try:
        for event in stream:
            kind = event[0]
            if kind == 'text':
                text.append(event[1])
                emit(('text', event[1]))
            elif kind == 'call':
                calls.append({'id': event[1], 'name': event[2], 'args': event[3]})
                emit(('call', event[1], event[2]))  # progress only, nothing runs yet
            elif kind == 'finish':
                return finish_reply(''.join(text), calls, event[1], event[2])
            elif kind == 'error':
                return {'status': 'error', 'error': event[1], 'text': ''.join(text),
                        'calls': [], 'cost': 0}
            if cancel.requested:
                return {'status': 'cancelled', 'text': ''.join(text), 'calls': [], 'cost': 0}
        return {'status': 'error', 'error': 'no_finish', 'text': ''.join(text),
                'calls': [], 'cost': 0}
    finally:
        close = getattr(stream, 'close', None)
        if close:
            close()  # stop reading; a real client also drops the connection


def keep_visible_text(history, text, why):
    """Keep what the user already saw, marked as cut short; drop any calls."""
    if text.strip():
        history.append({'role': 'assistant', 'content': text, 'tool_calls': [],
                        'cut_short': why})


def close_unstarted(history, calls, why):
    for call in calls:
        history.append({'role': 'tool', 'tool_call_id': call['id'], 'status': 'not_started',
                        'started': False, 'content': '没有执行：' + why})


def run_tool(tools, call, cancel):
    base = {'role': 'tool', 'tool_call_id': call['id']}
    entry = tools.get(call['name'])
    if entry is None:
        return dict(base, status='error', started=False, content='没有这个工具：' + call['name'])
    fn, params = entry
    args = call['args']
    if (not isinstance(args, dict) or set(args) != params
            or not all(isinstance(value, str) for value in args.values())):
        return dict(base, status='error', started=False,
                    content='参数不符合约定：' + json.dumps(args, ensure_ascii=False))
    try:
        outcome = fn(cancel=cancel, **args)
    except Exception as exc:  # a crashing tool is feedback for the model too
        return dict(base, status='error', started=True,
                    content='%s: %s' % (type(exc).__name__, exc))
    return dict(base, started=True, **outcome)


def run_loop(model, tools, task=None, history=None, budget=None, cancel=None, emit=None):
    """Run until the model stops calling tools, a limit is hit, Esc, or a failure.

    Every result names its terminal, and its history is closed, so the next
    request or a resumed run starts from a valid boundary.
    """
    if history is None:
        history = [{'role': 'user', 'content': task}]
    elif not calls_are_closed(history):
        raise ValueError('历史里还有没回结果的调用，不能接着跑')
    else:
        history = list(history)
    budget = budget or Budget()
    cancel = cancel or Cancel()
    emit = emit or (lambda event: None)

    def end(terminal, reason, text=None):
        emit(('end', terminal, reason))
        return {'terminal': terminal, 'reason': reason, 'exit_code': EXIT_CODES[terminal],
                'final_text': text, 'usage': dict(budget.used),
                'resumable': calls_are_closed(history), 'history': history}

    while True:
        if cancel.requested:
            return end('cancelled', 'user')
        stop = budget.admit_turn()  # previous results are all in: a clean boundary
        if stop:
            return end('stopped', stop)
        note = budget.soft_landing()
        if note:
            history.append({'role': 'system', 'content': note})
            emit(('notice', note))

        reply = stream_reply(model, history, cancel, emit)
        budget.record_cost(reply['cost'])
        if reply['status'] == 'cancelled':
            keep_visible_text(history, reply['text'], 'interrupted')
            return end('cancelled', 'user')
        if reply['status'] == 'truncated':
            keep_visible_text(history, reply['text'], 'output_limit')
            return end('failed', 'output_limit')
        if reply['status'] == 'error':
            return end('failed', reply['error'])

        calls = reply['calls']
        history.append({'role': 'assistant', 'content': reply['text'], 'tool_calls': calls})
        if not calls:
            return end('completed', 'model_ended', reply['text'])

        stop = budget.admit_calls(len(calls))
        if stop:
            close_unstarted(history, calls, '额度用完（%s）' % stop)
            return end('stopped', stop)
        for index, call in enumerate(calls):
            if cancel.requested:
                close_unstarted(history, calls[index:], '用户中断')
                return end('cancelled', 'user')
            emit(('tool', call['id'], call['name'], 'started'))
            result = run_tool(tools, call, cancel)
            history.append(result)
            emit(('tool', call['id'], call['name'], result['status']))


# ---- fixture: a tiny repo, fake tools and a model that reads history ----

TASK = '修好 to_seconds：2m 应该返回 120，现在返回 2。'


def demo_repo():
    return {
        'src/convert.py': "def to_seconds(text):\n    return int(text.removesuffix('m'))\n",
        'tests/test_convert.py': "got = to_seconds('2m')\nassert got == 120, '%r != 120' % got\n",
    }


def make_tools(repo):
    """Fake tools over an in-memory repo. Each checks cancel the way a real
    tool would check on its child process."""
    def read_file(path, cancel):
        if cancel.requested:
            return {'status': 'cancelled', 'content': '读取被中断'}
        if path not in repo:
            return {'status': 'error', 'content': '文件不存在：' + path}
        return {'status': 'ok', 'content': repo[path]}

    def edit(path, old, new, cancel):
        source = repo.get(path)
        if source is None or source.count(old) != 1:
            return {'status': 'error', 'content': 'old 必须在文件里恰好出现一次'}
        if cancel.requested:
            return {'status': 'cancelled', 'content': '修改被中断，文件可能没变，先重新读取'}
        repo[path] = source.replace(old, new)
        return {'status': 'ok', 'content': '已修改 ' + path}

    def run_tests(cancel):
        if cancel.requested:
            return {'status': 'cancelled', 'exit_code': 130, 'content': 'exit 130\n测试被中断'}
        scope = {}
        try:
            exec(repo['src/convert.py'], scope)
            exec(repo['tests/test_convert.py'], scope)
        except AssertionError as exc:
            return {'status': 'error', 'exit_code': 1,
                    'content': 'exit 1\nAssertionError: %s' % exc}
        return {'status': 'ok', 'exit_code': 0, 'content': 'exit 0\n1 passed'}

    return {'read_file': (read_file, {'path'}), 'edit': (edit, {'path', 'old', 'new'}),
            'run_tests': (run_tests, set())}


def calls_with_results(history):
    results = {item['tool_call_id']: item for item in history if item['role'] == 'tool'}
    return [(call, results.get(call['id'])) for item in history
            if item['role'] == 'assistant' for call in item.get('tool_calls', [])]


def fake_model(history):
    """Stand-in for a model: it looks at what happened and picks the next step."""
    done = calls_with_results(history)
    usage = {'input_tokens': 30 * len(history), 'output_tokens': 15}
    next_id = 'c%d' % (len(done) + 1)
    if not done:
        yield ('text', '先看')
        yield ('text', '实现和测试。')
        yield ('call', 'c1', 'read_file', {'path': 'src/convert.py'})
        yield ('call', 'c2', 'read_file', {'path': 'tests/test_convert.py'})
        yield ('finish', 'tool_calls', usage)
        return
    call, result = done[-1]
    status = result['status'] if result else None
    if status == 'ok' and call['name'] in ('read_file', 'edit'):
        yield ('text', '跑一下测试。')
        yield ('call', next_id, 'run_tests', {})
        yield ('finish', 'tool_calls', usage)
    elif call['name'] == 'run_tests' and status == 'error':
        yield ('text', '少乘了 60，改实现。')
        yield ('call', next_id, 'edit', {'path': 'src/convert.py',
                                         'old': "int(text.removesuffix('m'))",
                                         'new': "int(text.removesuffix('m')) * 60"})
        yield ('finish', 'tool_calls', usage)
    elif call['name'] == 'run_tests' and status == 'ok':
        yield ('text', '改好了：2m 现在返回 120，')
        yield ('text', '测试也过了。')
        yield ('finish', 'stop', usage)
    else:
        yield ('text', '上一步没有完成，先停在这里说明情况。')
        yield ('finish', 'stop', usage)


def run_demo(budget=None, cancel_on=None, model=fake_model):
    repo, cancel, shown = demo_repo(), Cancel(), []

    def emit(event):
        shown.append(event)
        if cancel_on and cancel_on(event):
            cancel.request()

    result = run_loop(model, make_tools(repo), TASK, budget=budget, cancel=cancel, emit=emit)
    return result, shown, repo


def brief(item):
    if item['role'] == 'assistant':
        calls = ', '.join('%s %s' % (call['id'], call['name']) for call in item['tool_calls'])
        cut = ' [%s]' % item['cut_short'] if item.get('cut_short') else ''
        return 'assistant%s: %s%s' % (cut, item['content'], ' -> ' + calls if calls else '')
    if item['role'] == 'tool':
        return 'tool %s %s: %s' % (item['tool_call_id'], item['status'],
                                    item['content'].splitlines()[0][:40])
    return '%s: %s' % (item['role'], item['content'][:40])


def main():
    scenarios = [
        ('不设上限', {}),
        ('max_turns=3', {'budget': Budget(max_turns=3)}),
        ('max_tool_calls=1', {'budget': Budget(max_tool_calls=1)}),
        ('文字流到一半按 Esc', {'cancel_on': lambda e: e == ('text', '先看')}),
        ('读第一个文件时按 Esc', {'cancel_on': lambda e: e == ('tool', 'c1', 'read_file', 'started')}),
    ]
    for title, kwargs in scenarios:
        result, _, _ = run_demo(**kwargs)
        print('== %s：%s / %s，退出码 %d，历史成对 %s，用量 %s' % (
            title, result['terminal'], result['reason'], result['exit_code'],
            result['resumable'], json.dumps(result['usage'])))
        for item in result['history'][1:]:
            print('   ' + brief(item))


if __name__ == '__main__':
    main()
