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-16T09:00:00Z'):
    retrieved=_dt(c.get('evidence_retrieved_at')); now_dt=_dt(now)
    age_days=((now_dt-retrieved).total_seconds()/86400) if retrieved else 9999
    provenance_complete=bool(c.get('provenance_ref')) and bool(c.get('evidence_locator'))
    evidence_fresh=age_days <= 30
    version_match=(c.get('api_version')==c.get('documented_api_version'))
    documented_operation=bool(c.get('operation_documented')) and bool(c.get('endpoint_or_method')) and version_match
    auth_ready=(not c.get('auth_scope_required')) or bool(c.get('auth_scope_granted'))
    account_ready=(c.get('account_prerequisite_state')=='MET')
    constraints_ready=(c.get('input_constraints_state')=='MET')
    quota_ready=(c.get('quota_relevance') in ('KNOWN','NONE'))
    explicit=c.get('explicit_support','UNKNOWN')
    if not provenance_complete:
        state='UNKNOWN'; fallback='EVIDENCE_REQUIRED'; decision='BLOCKED_EVIDENCE'; reason='PROVENANCE_OR_LOCATOR_MISSING'
    elif not evidence_fresh or not version_match:
        state='STALE_EVIDENCE'; fallback='REVERIFY_VERSION'; decision='DEFER_RECHECK'; reason='EVIDENCE_STALE_OR_VERSION_MISMATCH'
    elif explicit=='UNSUPPORTED':
        state='UNSUPPORTED'; fallback='ALT_MEDIA_OR_MANUAL'; decision='REJECT_AUTOMATION'; reason='EXPLICIT_PROVIDER_CONSTRAINT_UNSUPPORTED'
    elif not c.get('operation_documented'):
        state='UNKNOWN'; fallback='EVIDENCE_REQUIRED'; decision='BLOCKED_EVIDENCE'; reason='UI_OR_GENERIC_FEATURE_WITHOUT_OPERATION_EVIDENCE'
    elif not auth_ready:
        state='CONDITIONAL'; fallback='REAUTH_REQUIRED'; decision='DEFER_SCOPE_REPAIR'; reason='AUTH_SCOPE_NOT_GRANTED'
    elif not account_ready:
        state='CONDITIONAL'; fallback='ACCOUNT_REVIEW'; decision='DEFER_ACCOUNT_REVIEW'; reason='ACCOUNT_PREREQUISITE_OPEN'
    elif not constraints_ready:
        state='UNSUPPORTED'; fallback='ALT_MEDIA_OR_MANUAL'; decision='REJECT_AUTOMATION'; reason='INPUT_CONSTRAINT_VIOLATED'
    elif not quota_ready:
        state='CONDITIONAL'; fallback='QUOTA_REVIEW'; decision='DEFER_QUOTA_REVIEW'; reason='QUOTA_RELEVANCE_UNRESOLVED'
    elif explicit=='SUPPORTED' and documented_operation:
        state='SUPPORTED'; fallback='NONE'; decision='EXECUTE_SHADOW'; reason='DOCUMENTED_CAPABILITY_EVIDENCE_COMPLETE'
    else:
        state='UNKNOWN'; fallback='EVIDENCE_REQUIRED'; decision='BLOCKED_EVIDENCE'; reason='CAPABILITY_EVIDENCE_INCOMPLETE'
    return {'availability_state':state,'fallback_state':fallback,'next_decision':decision,'operation_evidence_valid':documented_operation,'auth_ready':auth_ready,'quota_ready':quota_ready,'provenance_complete':provenance_complete,'control_reason':reason}
