"""Observe the resource independently; no host or model is simulated here."""
import json
import tempfile
from pathlib import Path
import store

with tempfile.TemporaryDirectory() as directory:
    db = Path(directory) / 'resource.db'
    old, new = 'a' * 64, 'b' * 64  # Test identities; production uses trusted caller bindings.
    store.initialize(db, {'task': {'report': 'count and total'}, 'documents': {'report': {}}})
    store.assign_work(db, 'report', None, old, 0)
    args = {'document': 'report', 'expected_version': 0, 'value': {'total': 10}}
    first = store.execute(db, 'old-write', 'replace', args, old)
    assert first == {'status': 'committed', 'version': 1}
    store.assign_work(db, 'report', 0, new, 0)
    fresh = store.execute(db, 'old-reread', 'snapshot', {'document': 'report'}, old)
    before = store.inspect(db)
    refused = store.execute(db, 'old-fresh-write', 'replace', {
        'document': 'report', 'expected_version': fresh['version'], 'value': {'total': 999},
    }, old)
    assert refused == {'status': 'superseded', 'assignment_generation': 1}
    after = store.inspect(db)
    assert before['documents'] == after['documents']
    assert before['mutations'] == after['mutations']
    assert store.execute(db, 'old-write', 'replace', args, old) == first
    replacement = store.execute(db, 'new-write', 'replace', {
        'document': 'report', 'expected_version': fresh['version'], 'value': {'total': 10, 'reviewed': True},
    }, new)
    assert replacement == {'status': 'committed', 'version': 2}
    try:
        store.execute(db, 'old-write', 'replace', args, new)
    except ValueError as error:
        assert str(error) == 'operation identity conflict'
    else:
        raise AssertionError('Changed caller reused an operation')
    print(json.dumps({'stale_write': refused, 'replacement': replacement,
                      'mutations': len(store.inspect(db)['mutations']),
                      'original_result_replayed': True}, indent=2))
