from datetime import datetime

def _dt(s):
    if not s: return None
    return datetime.fromisoformat(s.replace('Z','+00:00'))

def evaluate(c, now='2026-09-16T08:00:00Z'):
    now_dt=_dt(now); retrieved=_dt(c.get('evidence_retrieved_at'))
    age_days=((now_dt-retrieved).total_seconds()/86400) if retrieved else 9999
    evidence_fresh=age_days <= 90
    provenance_complete=bool(c.get('provenance_ref'))
    identity_safe=bool(c.get('publish_transaction_id') and c.get('publish_intent_id') and c.get('target_account') and c.get('operation'))
    payload_binding_valid=bool(c.get('payload_hash')) and bool(c.get('key_payload_consistent'))
    rb=c.get('read_back_snapshot') or {}
    target_verified=bool(rb) and rb.get('target_account')==c.get('target_account')
    payload_verified=bool(rb) and rb.get('payload_hash')==c.get('payload_hash')
    verification_complete=target_verified and payload_verified and bool(c.get('provider_resource_id'))
    budget_remaining=max(int(c.get('execution_budget') or 0)-int(c.get('attempt_no') or 0),0)

    if not provenance_complete:
        state='UNKNOWN'; retry='BLOCKED'; reason='PROVENANCE_MISSING'
    elif not evidence_fresh:
        state='STALE_EVIDENCE'; retry='BLOCKED'; reason='DECISIVE_EVIDENCE_STALE'
    elif not identity_safe:
        state='UNVERIFIED'; retry='BLOCKED'; reason='TRANSACTION_IDENTITY_INCOMPLETE'
    elif not payload_binding_valid:
        state='DUPLICATE_BLOCKED'; retry='BLOCKED'; reason='REQUEST_ID_REUSED_FOR_DIFFERENT_PAYLOAD'
    elif c.get('response_status') in (200,201,202) and rb and not target_verified:
        state='FAILED'; retry='BLOCKED'; reason='READ_BACK_TARGET_MISMATCH'
    elif verification_complete:
        state='VERIFIED'; retry='NO_RETRY'; reason='READ_BACK_MATCHES_INTENT'
    elif c.get('response_status')=='TIMEOUT' and c.get('idempotency_support')=='NONE':
        state='AMBIGUOUS'; retry='HOLD_AND_INVESTIGATE'; reason='TIMEOUT_WITHOUT_SAFE_IDENTITY_OR_DUPLICATE_CHECK'
    elif int(c.get('attempt_no') or 0) >= int(c.get('execution_budget') or 0):
        state='UNVERIFIED'; retry='DEFERRED'; reason='EXECUTION_BUDGET_EXHAUSTED'
    else:
        state='UNVERIFIED'; retry='BOUNDED_RETRY_OR_VERIFY'; reason='FINAL_EFFECT_NOT_YET_VERIFIED'
    return {'publish_state':state,'retry_decision':retry,'identity_safe':identity_safe,'payload_binding_valid':payload_binding_valid,'target_verified':target_verified,'verification_complete':verification_complete,'evidence_fresh':evidence_fresh,'control_reason':reason}
