"""Python 3.11+, standard library only; deterministic harness, NOT an LLM.
No network, secrets, shell, production writes or random sampling.
Run: python3 agent-book-harness.py
"""
from dataclasses import dataclass, field

@dataclass
class Harness:
    tenant: str = 'A'
    service: str = 'checkout'
    remaining: int = 4
    events: list = field(default_factory=list)
    results: dict = field(default_factory=dict)

    def call(self, operation_id, tool, tenant, service, *, timeout=False):
        # Authorization precedes result lookup: cached data is not public.
        if tenant != self.tenant or service != self.service:
            raise PermissionError('scope')
        if tool not in {'metrics', 'changes'}:
            raise PermissionError('capability')
        identity = (tool, tenant, service)
        if operation_id in self.results:
            previous_identity, result = self.results[operation_id]
            if previous_identity != identity:
                raise ValueError('operation ID reused for different arguments')
            return result
        if self.remaining == 0:
            raise RuntimeError('budget')
        self.remaining -= 1
        if timeout:
            result = {'status': 'timeout', 'evidence': None}
        else:
            result = {'status': 'ok', 'evidence':
                      {'id': 'metric-1', 'p95_ms': 420} if tool == 'metrics'
                      else {'id': 'change-1', 'revision': 'r17'}}
        self.events.append((operation_id, identity, result))
        self.results[operation_id] = (identity, result)
        return result


def scripted_investigation(h, timeout=False):
    # A model adapter would propose these actions; the gate must stay outside it.
    metrics = h.call('op-m', 'metrics', 'A', 'checkout', timeout=timeout)
    changes = h.call('op-c', 'changes', 'A', 'checkout')
    if any(x['status'] != 'ok' for x in (metrics, changes)):
        return {'status': 'incomplete', 'evidence': []}
    return {'status': 'observed', 'evidence': [metrics['evidence'], changes['evidence']],
            'conclusion': 'Revision and latency observed; causation not established.'}


def raises(error, action):
    try:
        action()
    except error:
        return
    raise AssertionError(f'expected {error.__name__}')


def main():
    h = Harness()
    answer = scripted_investigation(h)
    assert answer['status'] == 'observed' and len(h.events) == 2
    # Replay returns recorded result without consuming another budget unit.
    h.call('op-m', 'metrics', 'A', 'checkout')
    assert h.remaining == 2 and len(h.events) == 2
    raises(PermissionError, lambda: h.call('op-m', 'metrics', 'B', 'checkout'))
    raises(PermissionError, lambda: h.call('op-write', 'restart', 'A', 'checkout'))
    raises(ValueError, lambda: h.call('op-m', 'changes', 'A', 'checkout'))
    raises(RuntimeError, lambda: Harness(remaining=0).call('x', 'metrics', 'A', 'checkout'))
    assert scripted_investigation(Harness(), timeout=True)['status'] == 'incomplete'
    kv = 2 * 32 * 1 * 8192 * 8 * 128 * 2
    assert kv == 1024**3
    environments = 2 * 30
    memory_gib = environments * 0.5
    assert environments == 60 and memory_gib == 30
    assert 6 * 4000 - 5 * 3000 == 9000
    print('scope=passed replay=passed budget=passed timeout=incomplete')
    print(f'kv_gib={kv / 1024**3:.1f} environments={environments} memory_gib={memory_gib:.1f}')
    print('Synthetic control checks only; no model-quality or sandbox benchmark.')

if __name__ == '__main__':
    main()
