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

run_turn is chapter 7's loop in miniature: one outer turn. The Goal layer
around it makes the three decisions that loop cannot: whether a completion
claim holds, whether another outer turn may start, and which state the goal
is left in. The model can only ask; the runtime decides.
"""
from copy import deepcopy

SAME_GAP_LIMIT = 3         # the same model-fixable gap, three outer turns in a row
MAX_CONSECUTIVE_STOPS = 8  # outer turns in a row that ran into the request cap
BLOCKER_KINDS = ('user_decision', 'missing_authority', 'external_state',
                 'environment_contradiction', 'unverifiable_requirement')
NO_PROGRESS = {'fingerprint': 'no_substantive_progress',
               'summary': '这一轮没有改动，也没有提交可核对的结论'}


class ControlPlaneError(Exception):
    """The runtime cannot honour the Goal protocol. The model cannot fix this."""


class Cancel:
    def __init__(self):
        self.requested = False


class GoalStore:
    """Owns the goal record. Every decision is journaled before anyone acts on it."""

    def __init__(self, objective, done_when=('run_tests',), token_budget=None):
        if token_budget is not None and (type(token_budget) is not int or token_budget <= 0):
            raise ValueError('token_budget 必须是正整数或 None')
        self.goal = {'objective': objective, 'done_when': tuple(done_when), 'state': 'active',
                     'pause_reason': None, 'message': '', 'token_budget': token_budget,
                     'tokens_used': 0, 'outer_turns': 0, 'last_gap': None, 'gap_streak': 0,
                     'stops': 0, 'open_gap': None, 'evidence': None, 'blocker': None}
        self.journal = []
        self.observer = None             # the surface watches; it never decides
        self.intent_writes_fail = False  # test hook: persistence breaks mid-run

    def record(self, event, **fields):
        entry = dict(fields, event=event)
        self.journal.append(entry)
        if self.observer:
            self.observer(entry)

    def accept_intent(self, intent):
        if self.intent_writes_fail:
            raise ControlPlaneError('goal store 写入失败')
        self.record('goal.intent.acknowledged', status=intent['status'])

    def transition(self, state, reason=None, message='', **extra):
        self.goal.update(state=state, pause_reason=reason, message=message, **extra)
        self.record('goal.transitioned', state=state, reason=reason, message=message)


def update_goal(ctx, status=None, reason='', evidence=None, blocker=None):
    """The model's only way to say done or stuck. It files a claim; it never
    writes a terminal state."""
    def rejected(code, text):  # the model can read this and try again
        return {'status': 'error', 'ack': 'rejected', 'code': code, 'content': text}

    if ctx is None:
        return {'status': 'error', 'content': '当前没有正在运行的 Goal，这个工具不可用'}
    if status not in ('complete', 'blocked'):
        return rejected('invalid_status', 'status 只能是 complete 或 blocked')
    if not evidence or not all(isinstance(item, dict) and item.get('target')
                               for item in evidence):
        return rejected('missing_evidence', '要附上证据：指出是哪一次工具调用')
    if status == 'blocked' and (not isinstance(blocker, dict)
                                or blocker.get('kind') not in BLOCKER_KINDS):
        return rejected('missing_blocker', 'blocked 要说明阻塞类型：' + '、'.join(BLOCKER_KINDS))
    if ctx['pending']:
        return rejected('already_pending', '这一轮已经提交过一次，等审核结果')
    intent = {'status': status, 'reason': reason, 'evidence': evidence, 'blocker': blocker}
    ctx['store'].accept_intent(intent)  # may raise ControlPlaneError
    ctx['pending'] = intent
    return {'status': 'ok', 'ack': 'deferred_to_turn_end',
            'content': '已记录，这一轮结束后审核。现在还不算完成。'}


def run_tool(tools, call):
    base = {'role': 'tool', 'tool_call_id': call['id']}
    fn = tools.get(call['name'])
    if fn is None:
        return dict(base, status='error', content='没有这个工具：' + call['name'])
    try:
        return dict(base, **fn(**call['args']))
    except TypeError as exc:  # wrong arguments are feedback for the model
        return dict(base, status='error', content='参数不符合约定：%s' % exc)


def run_turn(model, tools, history, ledger, turn, cancel, max_requests):
    """One outer turn: request, run the calls, write results back, repeat."""
    tokens = 0
    for _ in range(max_requests):
        if cancel.requested:
            return {'terminal': 'cancelled', 'reason': 'user', 'tokens': tokens}
        try:
            reply = model(deepcopy(history))
        except Exception as exc:
            return {'terminal': 'failed', 'reason': 'provider_error: %s' % exc, 'tokens': tokens}
        tokens += reply.get('tokens', 0)
        calls = reply.get('calls', [])
        history.append({'role': 'assistant', 'content': reply.get('text', ''),
                        'tool_calls': calls})
        if not calls:
            return {'terminal': 'completed', 'reason': 'model_ended', 'tokens': tokens}
        for index, call in enumerate(calls):
            try:
                result = run_tool(tools, call)
            except ControlPlaneError as exc:
                for left in calls[index:]:  # keep history closed, then stop the turn
                    history.append({'role': 'tool', 'tool_call_id': left['id'],
                                    'status': 'not_started', 'content': '没有执行：%s' % exc})
                return {'terminal': 'failed', 'reason': 'control_plane: %s' % exc,
                        'tokens': tokens}
            history.append(result)
            # The runtime's own record of what happened. Claims are checked against this.
            ledger.append({'seq': len(ledger) + 1, 'id': call['id'], 'name': call['name'],
                           'turn': turn, 'status': result['status'],
                           'needs': result.get('needs'),
                           'side_effect': call['name'] == 'edit' and result['status'] == 'ok'})
    return {'terminal': 'stopped', 'reason': 'turns', 'tokens': tokens}


def unmet(goal, ledger):
    """Requirements the ledger cannot prove yet, each as a gap."""
    edits = [entry['seq'] for entry in ledger if entry['side_effect']]
    last_edit = edits[-1] if edits else 0
    gaps = []
    for name in goal['done_when']:
        runs = [entry for entry in ledger if entry['name'] == name]
        last = runs[-1] if runs else None
        if last is None or last['seq'] < last_edit:
            gaps.append({'fingerprint': name + '_not_run_after_edit', 'entry': last,
                         'summary': '最后一次修改之后没有运行 ' + name})
        elif last['status'] != 'ok':
            gaps.append({'fingerprint': name + '_failing', 'entry': last,
                         'summary': '最近一次 %s 没有通过' % name})
    return gaps


def ledger_verifier(goal, intent, ledger):
    """Deterministic stand-in for the judge. It believes the ledger, not the claim."""
    def not_achieved(gap):
        return {'outcome': 'not_achieved',
                'gap': {'fingerprint': gap['fingerprint'], 'summary': gap['summary']}}

    by_id = {entry['id']: entry for entry in ledger}
    cited = [by_id.get(item['target']) for item in intent['evidence']]
    if any(entry is None for entry in cited):
        return not_achieved({'fingerprint': 'evidence_not_in_ledger',
                             'summary': '证据指向的调用不在运行记录里'})
    gaps = unmet(goal, ledger)
    if intent['status'] == 'complete':
        if gaps:
            return not_achieved(gaps[0])
        proof = [[e for e in ledger if e['name'] == name][-1] for name in goal['done_when']]
        if any(entry not in cited for entry in proof):
            return not_achieved({'fingerprint': 'evidence_is_stale',
                                 'summary': '证据不是最近那次通过的运行'})
        return {'outcome': 'achieved', 'evidence': intent['evidence']}
    fixable = [gap for gap in gaps if not (gap['entry'] and gap['entry']['needs'])]
    if fixable:  # the model can still do something about it: not a blocker
        return not_achieved(fixable[0])
    if not gaps:
        return not_achieved({'fingerprint': 'nothing_is_blocking',
                             'summary': '运行记录里没有被外部条件卡住的要求'})
    return {'outcome': 'blocked', 'blocker': intent['blocker']}


def admit(goal, inbox, cancel):
    """Why the next outer turn may not start, or None."""
    if goal['state'] != 'active':
        return 'goal_not_active'
    if cancel.requested:
        return 'cancelled'
    if inbox:
        return 'user_input_queued'
    if goal['token_budget'] is not None and goal['tokens_used'] >= goal['token_budget']:
        return 'budget_exhausted'
    return None


def continuation_message(goal, trigger):
    lines = ['[Goal 第 %d 轮] 触发：%s' % (goal['outer_turns'], trigger),
             '<objective>%s</objective>' % goal['objective']]
    if goal['open_gap']:
        lines.append('上一轮没补上的缺口：%(fingerprint)s（%(summary)s）' % goal['open_gap'])
    lines.append('以当前文件和命令输出为准，逐条核对要求。做完了用 update_goal 提交证据；'
                 '不要因为这一轮要结束就宣布完成。')
    return {'role': 'system', 'kind': 'goal_continuation', 'trigger': trigger,
            'gap': goal['open_gap'] and goal['open_gap']['fingerprint'],
            'content': '\n'.join(lines)}


def run_goal(store, model, repo, verifier=ledger_verifier, history=None, ledger=None,
             inbox=None, cancel=None, max_requests=12):
    """Keep starting outer turns until the goal leaves `active`."""
    goal = store.goal
    history = [] if history is None else history
    ledger = [] if ledger is None else ledger
    inbox = [] if inbox is None else inbox
    cancel = cancel or Cancel()
    trigger = 'initial'

    def end():
        return dict(deepcopy(goal), history=history, ledger=ledger, journal=store.journal)

    while True:
        refusal = admit(goal, inbox, cancel)
        if refusal:
            store.record('goal.continuation.rejected', reason=refusal)
            if refusal == 'user_input_queued':  # the message is kept, the goal yields
                while inbox:
                    history.append({'role': 'user', 'content': inbox.pop(0)})
                store.transition('paused', 'user', '用户有新输入')
            elif refusal == 'cancelled':
                store.transition('paused', 'user', '用户中断')
            elif refusal == 'budget_exhausted':
                store.transition('budget_limited')
            return end()
        store.record('goal.continuation.admitted', trigger=trigger)

        goal['outer_turns'] += 1
        turn = goal['outer_turns']
        history.append(continuation_message(goal, trigger))
        ctx = {'store': store, 'pending': None}
        store.record('goal.turn.started', turn=turn)
        result = run_turn(model, make_tools(repo, ctx), history, ledger, turn, cancel,
                          max_requests)
        goal['tokens_used'] += result['tokens']  # charged once, however the turn ended
        store.record('goal.turn.finished', turn=turn, terminal=result['terminal'],
                     tokens=result['tokens'])

        if result['terminal'] == 'cancelled':
            store.transition('paused', 'user', '用户中断')
            return end()
        if result['terminal'] == 'failed':  # not progress, and never retried blindly
            store.transition('paused', 'infrastructure', result['reason'])
            return end()
        if goal['token_budget'] is not None and goal['tokens_used'] >= goal['token_budget']:
            store.transition('budget_limited')  # a pending claim is dropped, not honoured
            return end()
        stopped = result['terminal'] == 'stopped'
        goal['stops'] = goal['stops'] + 1 if stopped else 0
        if goal['stops'] >= MAX_CONSECUTIVE_STOPS:
            store.transition('paused', 'no_progress',
                             '连续 %d 轮撞上请求上限，仍未完成' % goal['stops'])
            return end()

        gap = None
        if ctx['pending']:
            verdict = verifier(goal, ctx['pending'], ledger)
            store.record('goal.verification.completed', outcome=verdict['outcome'],
                         gap=verdict.get('gap', {}).get('fingerprint'))
            if verdict['outcome'] == 'achieved':
                store.transition('complete', evidence=verdict['evidence'])
                return end()
            if verdict['outcome'] == 'blocked':
                store.transition('blocked', blocker=verdict['blocker'])
                return end()
            if verdict['outcome'] != 'not_achieved':
                store.transition('paused', 'infrastructure',
                                 verdict.get('message', '审核没有给出结论'))
                return end()
            gap = verdict['gap']

        progressed = any(entry['turn'] == turn and entry['side_effect'] for entry in ledger)
        if gap is None and not progressed:
            gap = NO_PROGRESS
        if progressed or gap is None:  # a real change clears the streak
            goal['last_gap'], goal['gap_streak'] = None, 0
        elif gap['fingerprint'] == goal['last_gap']:
            goal['gap_streak'] += 1
        else:
            goal['last_gap'], goal['gap_streak'] = gap['fingerprint'], 1
        goal['open_gap'] = gap
        if goal['gap_streak'] >= SAME_GAP_LIMIT:
            store.transition('paused', 'no_progress',
                             '同一个缺口连续 %d 轮没有补上：%s' % (goal['gap_streak'], gap['summary']))
            return end()
        trigger = 'budget_stop' if stopped else 'gap_feedback' if gap else 'progress'


def resume_goal(store):
    """/goal resume: a paused or blocked goal gets a fresh run. Complete stays complete."""
    goal = store.goal
    if goal['state'] in ('paused', 'blocked'):
        goal.update(last_gap=None, gap_streak=0, stops=0, open_gap=None)
        store.transition('active')
    return goal['state']


# ---- fixture: a tiny repo, fake tools and models that read history ----

OBJECTIVE = '修好 to_seconds：2m 应该返回 120，现在返回 2。测试要通过。'
RELEASE_OBJECTIVE = '修好 to_seconds 并发布 0.2.1。'
OLD, NEW = "int(text.removesuffix('m'))", "int(text.removesuffix('m')) * 60"


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


def make_tools(repo, ctx):
    def read_file(path):
        if path not in repo:
            return {'status': 'error', 'content': '文件不存在：' + path}
        return {'status': 'ok', 'content': repo[path]}

    def edit(path, old, new):
        source = repo.get(path)
        if source is None or source.count(old) != 1:
            return {'status': 'error', 'content': 'old 必须在文件里恰好出现一次'}
        repo[path] = source.replace(old, new)
        return {'status': 'ok', 'content': '已修改 ' + path}

    def run_tests():
        scope = {}
        try:
            exec(repo['src/convert.py'], scope)
            exec(repo['tests/test_convert.py'], scope)
        except AssertionError as exc:
            return {'status': 'error', 'content': 'exit 1\nAssertionError: %s' % exc}
        return {'status': 'ok', 'content': 'exit 0\n1 passed'}

    def publish():  # the tool itself reports that this failure is out of the model's hands
        return {'status': 'error', 'needs': 'missing_authority',
                'content': 'exit 1\n缺少发布凭据 PYPI_TOKEN'}

    return {'read_file': read_file, 'edit': edit, 'run_tests': run_tests, 'publish': publish,
            'update_goal': lambda **args: update_goal(ctx, **args)}


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 make_model(style='careful'):
    """A stand-in model. It reads history and picks the next step; `style`
    decides how honest it is about being done."""
    def model(history):
        start = max(i for i, item in enumerate(history) if item.get('kind') == 'goal_continuation')
        steer, done, this_turn = history[start], calls_with_results(history), \
            calls_with_results(history[start:])
        next_id = 'c%d' % (len(done) + 1)

        def reply(text, *calls):
            return {'text': text, 'tokens': 100, 'calls': [
                {'id': 'c%d' % (len(done) + 1 + i), 'name': name, 'args': args}
                for i, (name, args) in enumerate(calls)]}

        def claim(text, status, target, **extra):
            return reply(text, ('update_goal', dict(
                status=status, reason=text,
                evidence=[{'kind': 'command', 'target': target, 'summary': text}], **extra)))

        if this_turn and this_turn[-1][0]['name'] == 'update_goal':
            return reply('改好了。' if this_turn[-1][0]['args']['status'] == 'complete'
                         else '卡住了，等你处理。')
        if not done:
            return reply('先看实现和测试。', ('read_file', {'path': 'src/convert.py'}),
                         ('read_file', {'path': 'tests/test_convert.py'}))
        tests = [(call, result) for call, result in done if call['name'] == 'run_tests']
        edits = [call for call, result in done if call['name'] == 'edit' and result['status'] == 'ok']
        if not tests:
            return reply('跑一下测试。', ('run_tests', {}))
        last_test, last_result = tests[-1]
        if not edits:
            if style == 'release' and not any(c['name'] == 'update_goal' for c, _ in done):
                return claim('测试挂了，需要你确认预期。', 'blocked', last_test['id'],
                             blocker={'kind': 'user_decision', 'summary': '测试失败'})
            return reply('少乘了 60，改实现。',
                         ('edit', {'path': 'src/convert.py', 'old': OLD, 'new': NEW}))
        retested = done.index((last_test, last_result)) > max(
            i for i, (call, _) in enumerate(done) if call['name'] == 'edit')
        if not retested:
            if style == 'stubborn' or (style == 'hasty' and steer['trigger'] == 'initial'):
                return claim('改好了，测试跑过。', 'complete', last_test['id'])
            if style == 'silent' and steer['trigger'] == 'initial':
                return reply('改好了。')
            return reply('改完重跑测试。', ('run_tests', {}))
        if style == 'release':
            publishes = [call for call, _ in done if call['name'] == 'publish']
            if not publishes:
                return reply('测试过了，发布。', ('publish', {}))
            return claim('缺少发布凭据，我拿不到。', 'blocked', publishes[-1]['id'],
                         blocker={'kind': 'missing_authority', 'summary': '缺少 PYPI_TOKEN'})
        return claim('2m 现在返回 120，测试通过。', 'complete', last_test['id'])
    return model


SCENARIOS = [
    ('带证据宣布完成', {'style': 'careful'}),
    ('只说「改好了」，没有提交', {'style': 'silent'}),
    ('没重跑测试就宣布完成', {'style': 'hasty'}),
    ('一直拿旧证据宣布完成', {'style': 'stubborn'}),
    ('先喊受阻被驳回，最后真的受阻', {'style': 'release', 'objective': RELEASE_OBJECTIVE,
                                      'done_when': ('run_tests', 'publish')}),
    ('token 额度先到', {'style': 'careful', 'token_budget': 500}),
]


def run_demo(style='careful', objective=OBJECTIVE, done_when=('run_tests',), token_budget=None,
             **kwargs):
    store, repo = GoalStore(objective, done_when, token_budget), demo_repo()
    return run_goal(store, make_model(style), repo, **kwargs), store, repo


def main():
    for title, kwargs in SCENARIOS:
        result, store, _ = run_demo(**kwargs)
        state = result['state'] + ('(%s)' % result['pause_reason'] if result['pause_reason'] else '')
        print('== %s：%s，%d 轮，%d tokens %s' % (
            title, state, result['outer_turns'], result['tokens_used'], result['message']))
        for entry in store.journal:
            detail = ' '.join('%s=%s' % (key, value) for key, value in entry.items()
                              if key != 'event' and value not in (None, ''))
            print('   %-30s %s' % (entry['event'], detail))


if __name__ == '__main__':
    main()
