REQUIRED=['order_id', 'state_model_version', 'payment_state', 'fulfillment_state', 'commercial_state', 'exception_state', 'source_system', 'source_status', 'canonical_event', 'from_state', 'to_state', 'transition_guard', 'invariant_set', 'event_id', 'event_time', 'processing_time', 'idempotency_key', 'late_event_policy', 'terminal_state', 'reopen_authority', 'transition_result', 'owner', 'evidence_ref']

def _missing(c):
    return [k for k in REQUIRED if k not in c or c[k] in (None,'')]

def evaluate(c):
    if _missing(c): return 'HOLD_UNKNOWN_EVIDENCE'
    axes=c.get('mapping_axes',[])
    if c.get('canonical_event') in ('UNKNOWN','') or len(axes)!=1 or c.get('affected_axis') not in axes:
        return 'HOLD_PROVIDER_MAPPING'
    if c.get('event_seen_before'):
        return 'NOOP_DUPLICATE'
    if str(c.get('transition_guard')).upper()!='TRUE':
        return 'HOLD_GUARD_FAILED'
    if not c.get('invariants_pass',True):
        return 'HOLD_INVARIANT_FAILED'
    if c.get('event_is_older_than_current') and c.get('would_regress_terminal'):
        return 'HOLD_RECONCILE_LATE_EVENT'
    if c.get('reopen_requested') and c.get('reopen_authority') in ('MISSING','UNKNOWN','DENIED',None,''):
        return 'HOLD_REOPEN_AUTHORITY_REQUIRED'
    return 'APPLY_TRANSITION'

def controls(c):
    d=evaluate(c)
    axes=c.get('mapping_axes',[])
    mapping_bad=(c.get('canonical_event') in ('UNKNOWN','') or len(axes)!=1 or c.get('affected_axis') not in axes)
    return {
      'dimension_contract': all(k in c for k in REQUIRED),
      'axis_mapping_isolated': (d=='HOLD_PROVIDER_MAPPING') if mapping_bad else (len(axes)==1 and c.get('affected_axis') in axes),
      'guard_and_invariant_enforced': (d in ('HOLD_GUARD_FAILED','HOLD_INVARIANT_FAILED')) if (str(c.get('transition_guard')).upper()!='TRUE' or not c.get('invariants_pass',True)) and not mapping_bad and not c.get('event_seen_before') else True,
      'idempotency_enforced': (d=='NOOP_DUPLICATE') if c.get('event_seen_before') and not mapping_bad else True,
      'temporal_terminal_reopen_enforced': (d in ('HOLD_RECONCILE_LATE_EVENT','HOLD_REOPEN_AUTHORITY_REQUIRED')) if ((c.get('event_is_older_than_current') and c.get('would_regress_terminal')) or (c.get('reopen_requested') and c.get('reopen_authority') in ('MISSING','UNKNOWN','DENIED',None,''))) and not mapping_bad and not c.get('event_seen_before') and str(c.get('transition_guard')).upper()=='TRUE' else True,
      'expected_decision': d==c.get('expected_decision')
    }
