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"):
    now_dt=_dt(now); retrieved=_dt(c.get("retrieved_at")); due=_dt(c.get("review_due"))
    provenance_complete=bool(c.get("provenance_ref")) and bool(c.get("policy_locator"))
    version_pinned=(c.get("api_version")==c.get("documented_api_version")) and ((not c.get("version_header_required")) or bool(c.get("version_header_present")))
    permission_ready=(not c.get("permission_scope_required")) or bool(c.get("permission_scope_granted"))
    schema_ready=bool(c.get("request_schema_ref")) and bool(c.get("response_schema_ref"))
    policy_current=bool(retrieved and due and retrieved <= now_dt <= due and c.get("policy_snapshot_id") and c.get("policy_locator"))
    deprecation_ready=(c.get("sunset_state") not in ("SUNSET","REMOVED"))
    if not provenance_complete:
        state="UNKNOWN"; decision="BLOCKED_EVIDENCE"; reason="PROVENANCE_OR_POLICY_LOCATOR_MISSING"
    elif not policy_current:
        state="STALE_EVIDENCE"; decision="POLICY_RECHECK"; reason="POLICY_SNAPSHOT_STALE_OR_INCOMPLETE"
    elif c.get("sunset_state") in ("SUNSET","REMOVED"):
        state="UNSUPPORTED"; decision="MIGRATE_VERSION"; reason="VERSION_OUTSIDE_SUPPORTED_SURFACE"
    elif not version_pinned:
        state="CONDITIONAL"; decision="PIN_VERSION_AND_RECHECK"; reason="VERSION_HEADER_OR_VERSION_PIN_INCOMPLETE"
    elif not schema_ready:
        state="UNKNOWN"; decision="BLOCKED_EVIDENCE"; reason="SCHEMA_SNAPSHOT_MISSING"
    elif not permission_ready:
        state="CONDITIONAL"; decision="REAUTH_REQUIRED"; reason="REQUIRED_PERMISSION_SCOPE_NOT_GRANTED"
    elif c.get("deprecated"):
        state="CONDITIONAL"; decision="REVIEW_DEPRECATION"; reason="ACTIVE_DEPRECATION_REQUIRES_MIGRATION_PLAN"
    else:
        state="SUPPORTED"; decision="REGISTER_CAPABILITY"; reason="CURRENT_VERSION_POLICY_PERMISSION_SCHEMA_PROVENANCE"
    return {"support_status":state,"next_decision":decision,"version_pinned":version_pinned,"permission_ready":permission_ready,"policy_current":policy_current,"deprecation_ready":deprecation_ready,"provenance_complete":provenance_complete,"control_reason":reason}
