#!/usr/bin/env python3
"""Reproduce SoftwareInspect's synthetic CRM field-ownership example.

Python standard library only. No CRM, network, credentials, personal data, or
production writes. Source revisions here are invented per-field ordered integers,
not API guarantees. Run: python3 replay.py > results.json
"""
import copy
import json
from collections import Counter

POLICY = {
    'job_title': {'source': 'crm', 'mode': 'replace', 'clear': False},
    'direct_phone': {'source': 'crm', 'mode': 'replace', 'clear': True},
    'deal_stage': {'source': 'crm', 'mode': 'replace', 'clear': False},
    'billing_status': {'source': 'billing', 'mode': 'replace', 'clear': False},
    'company_size': {'source': 'enrichment', 'mode': 'fill_empty', 'clear': False},
}
INITIAL = {
    'job_title': {'value': 'Analyst', 'revision': 4},
    'direct_phone': {'value': '+47 555 0100', 'revision': 8},
    'deal_stage': {'value': 'Discovery', 'revision': 10},
    'billing_status': {'value': 'current', 'revision': 20},
    'company_size': {'value': None, 'revision': 1},
}
EVENTS = [
    {'id': 'E01', 'source': 'enrichment', 'field': 'job_title', 'revision': 99, 'op': 'set', 'value': 'VP'},
    {'id': 'E02', 'source': 'crm', 'field': 'job_title', 'revision': 5, 'op': 'set', 'value': 'Director'},
    {'id': 'E03', 'source': 'crm', 'field': 'direct_phone', 'revision': 9, 'op': 'omit'},
    {'id': 'E04', 'source': 'crm', 'field': 'direct_phone', 'revision': 10, 'op': 'set', 'value': ''},
    {'id': 'E05', 'source': 'crm', 'field': 'direct_phone', 'revision': 11, 'op': 'clear'},
    {'id': 'E06', 'source': 'crm', 'field': 'job_title', 'revision': 3, 'op': 'set', 'value': 'Manager'},
    {'id': 'E07', 'source': 'crm', 'field': 'deal_stage', 'revision': 11, 'op': 'set', 'value': 'Proposal'},
    {'id': 'E07', 'source': 'crm', 'field': 'deal_stage', 'revision': 11, 'op': 'set', 'value': 'Proposal'},
    {'id': 'E08', 'source': 'enrichment', 'field': 'deal_stage', 'revision': 100, 'op': 'set', 'value': 'Prospect'},
    {'id': 'E09', 'source': 'billing', 'field': 'billing_status', 'revision': 21, 'op': 'set', 'value': 'overdue'},
    {'id': 'E10', 'source': 'billing', 'field': 'billing_status', 'revision': 19, 'op': 'set', 'value': 'paid'},
    {'id': 'E11', 'source': 'enrichment', 'field': 'company_size', 'revision': 2, 'op': 'set', 'value': '51-200'},
    {'id': 'E12', 'source': 'enrichment', 'field': 'company_size', 'revision': 3, 'op': 'set', 'value': '201-500'},
]


def replay():
    naive = {field: row['value'] for field, row in INITIAL.items()}
    guarded = copy.deepcopy(INITIAL)
    seen = set()
    decisions = []
    for event in EVENTS:
        field = event['field']
        rule = POLICY[field]
        # Baseline: last delivered present value wins; omission leaves unchanged.
        if event['op'] != 'omit':
            naive[field] = None if event['op'] == 'clear' else event['value']
        key = (event['source'], event['id'])
        before = guarded[field]['value']
        if key in seen:
            decision = 'duplicate'
        elif event['source'] != rule['source']:
            decision = 'wrong_source'
        elif event['op'] == 'omit' or (event['op'] == 'set' and event['value'] in ('', None)):
            decision = 'no_value'
        elif event['revision'] <= guarded[field]['revision']:
            decision = 'stale'
        elif event['op'] == 'clear' and not rule['clear']:
            decision = 'clear_forbidden'
        elif rule['mode'] == 'fill_empty' and before not in ('', None):
            decision = 'fill_blocked'
        else:
            decision = 'write'
            guarded[field] = {'value': None if event['op'] == 'clear' else event['value'], 'revision': event['revision']}
        seen.add(key)
        decisions.append({'event': event, 'decision': decision, 'before': before, 'after': guarded[field]['value']})
    final = {field: row['value'] for field, row in guarded.items()}
    return {
        'method': 'Synthetic single-record sequential replay; field authority, explicit clear, source revision, event dedupe, fill-only enrichment.',
        'limitations': 'Chosen exceptions, not a representative sample or vendor test. No API calls, clocks, concurrency, identity matching, authorization, persistence, retries after failed writes, or production reliability measured. Event IDs and per-field revisions are assumed valid. Clear permission is a fixture policy, not authenticated approval.',
        'policy': POLICY, 'initial': INITIAL, 'deliveries': decisions,
        'summary': {'delivered_events': len(EVENTS), 'unique_events': len(seen), 'decisions': dict(Counter(row['decision'] for row in decisions)), 'different_final_fields': [field for field in final if final[field] != naive[field]]},
        'delivery_order_final': naive, 'ownership_policy_final': final,
    }


if __name__ == '__main__':
    print(json.dumps(replay(), indent=2) + '\n', end='')
