#!/usr/bin/env python3
"""Offline teaching fixture: stateful validation, not the paper's PEC benchmark."""
import json
import sys


def replay(calls, stock=1):
    """Replay a fictional read-before-reserve API; invalid calls have no effects."""
    if type(stock) is not int or stock < 0:
        raise ValueError('stock must be a nonnegative integer')
    if not isinstance(calls, list):
        raise ValueError('calls must be a list')
    observed = False
    reserved = False
    errors = []
    valid = 0
    for position, call in enumerate(calls, 1):
        error = None
        if not isinstance(call, dict) or set(call) != {'tool', 'item'}:
            error = 'schema: require exactly tool and item'
        elif call['item'] != 'fixture-item':
            error = 'unknown item'
        elif call['tool'] == 'check_stock':
            observed = True
        elif call['tool'] == 'reserve':
            if not observed:
                error = 'precondition: check stock first'
            elif reserved:
                error = 'precondition: already reserved'
            elif stock < 1:
                error = 'precondition: insufficient stock'
            else:
                stock -= 1
                reserved = True
        else:
            error = 'unknown tool'
        if error:
            errors.append({'call': position, 'reason': error})
        else:
            valid += 1
    return {
        'call_count': len(calls),
        'valid_calls': valid,
        'first_error_call': errors[0]['call'] if errors else None,
        'initial_executable_prefix_length': errors[0]['call'] - 1 if errors else len(calls),
        'target_reached': reserved,
        'clean_completion': reserved and not errors,
        'completion_with_errors': reserved and bool(errors),
        'stock_remaining': stock,
        'errors': errors,
    }


if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python3 replay-tool-trace.py tool-trace-examples.json')
    with open(sys.argv[1], encoding='utf-8') as stream:
        cases = json.load(stream)
    print(json.dumps({case['id']: replay(case['calls'], case['initial_stock']) for case in cases}, indent=2))
