"""Sentrial synthetic regression tutorial; Python 3.9+, stdlib, no network.

Run: python3 agent-regression-workbench.py --candidate repaired
The baseline intentionally fails (exit 1); repaired passes these fixtures (exit 0).
This tests a deterministic response adapter, NOT an LLM or any vendor product.
Fixtures are fixed, trusted records on a shared synthetic clock. Receipt
provenance, parsing, conflicting events and real model variability are out of scope.
"""
import argparse
import json
import sys


def cases():
    request = dict(action='cancel', target_id='order-7', operation_id='op-4')
    receipt = dict(**request, state='completed', observed_at=18)
    rows = [
        ('confirmed', receipt, 'completed'),
        ('queued', {**receipt, 'state': 'pending'}, 'pending'),
        ('rejected', {**receipt, 'state': 'rejected'}, 'rejected'),
        ('wrong-target', {**receipt, 'target_id': 'order-8'}, 'unverified'),
        ('wrong-operation', {**receipt, 'operation_id': 'op-5'}, 'unverified'),
        ('wrong-action', {**receipt, 'action': 'refund'}, 'unverified'),
        ('missing', None, 'unverified'),
        ('late-receipt', {**receipt, 'observed_at': 25}, 'unverified'),
        ('timeout-then-readback', {**receipt, 'observed_at': 19}, 'completed'),
        ('unknown-state', {**receipt, 'state': 'unknown'}, 'unverified'),
    ]
    return [dict(id=name, request=dict(request), receipt=r, response_at=20,
                 expected_status=expected) for name, r, expected in rows]


MESSAGES = {
    'completed': 'Cancellation confirmed.',
    'pending': 'Cancellation is pending; it is not confirmed yet.',
    'rejected': 'Cancellation was rejected.',
    'unverified': 'I cannot verify the cancellation from the available evidence.',
}


def respond(case, candidate):
    receipt = case['receipt']
    if candidate == 'baseline':
        # Bug: any tool result is treated as confirmation of the requested action.
        status = 'completed' if receipt is not None else 'unverified'
    else:
        matches = receipt is not None and all(
            receipt.get(k) == case['request'][k]
            for k in ('action', 'target_id', 'operation_id'))
        known = matches and receipt.get('observed_at', float('inf')) <= case['response_at']
        status = receipt.get('state') if known else 'unverified'
        if status not in ('completed', 'pending', 'rejected'):
            status = 'unverified'
    return dict(status=status, text=MESSAGES[status])


def evaluate(candidate):
    rows = []
    for case in cases():
        response = respond(case, candidate)
        rows.append(dict(**case, candidate=candidate, response=response,
                         passed=response['status'] == case['expected_status']))
    return rows


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--candidate', choices=['baseline', 'repaired'], default='repaired')
    parser.add_argument('--json', action='store_true', help='Print full evidence as JSON to stdout')
    args = parser.parse_args()
    rows = evaluate(args.candidate)
    passed = sum(r['passed'] for r in rows)
    if args.json:
        print(json.dumps(dict(synthetic=True, candidate=args.candidate, passed=passed,
                              total=len(rows), cases=rows), indent=2))
    else:
        for r in rows:
            print(f"{'PASS' if r['passed'] else 'FAIL'} {r['id']}: "
                  f"expected={r['expected_status']} actual={r['response']['status']}")
        print(f'{args.candidate}: {passed}/{len(rows)} synthetic cases passed')
        print('No model calls, production traffic, or vendor benchmark results.')
    return 0 if passed == len(rows) else 1


if __name__ == '__main__':
    sys.exit(main())
