"""Pure, offline model selection from a synthetic application observation.

The wrapper's scope and observed_at are application metadata, not API fields.
Only id and capabilities are used from the authenticated model-list response.
All demo IDs are fictional, not usable API429 model promises. A selected ID is
membership/capability evidence, never proof that execution will succeed.

max_age is an application observation-age choice. It grants no permission to
retain/share an HTTP response: actual cache directives and authenticated-cache
restrictions must be honored outside this pure function. No response is retained.
"""
import math
from typing import NamedTuple, Optional


class Choice(NamedTuple):
    model_id: Optional[str]
    reason: str


SCOPE_KEYS = ('environment', 'base_url', 'credential_alias', 'credential_revision')


def _text(value):
    return isinstance(value, str) and bool(value.strip())


def _number(value):
    try:
        return type(value) in (int, float) and math.isfinite(value) and value >= 0
    except OverflowError:
        return False


def select_model(snapshot, expected_scope, approved_ids, required_capability, now, max_age):
    """Return immutable selection evidence; invalid/unknown input selects no ID.

    approved_ids is an application-owned ordered list, including any explicitly
    approved alternatives. Missing capability evidence means unqualified here,
    not a claim that a feature is categorically unsupported.
    Times are finite nonnegative Unix seconds; exact expiry is already stale.
    Error reasons deliberately exclude observations and credential metadata.
    """
    if not isinstance(snapshot, dict):
        return Choice(None, 'invalid observation')
    scope = snapshot.get('scope')
    for candidate in (scope, expected_scope):
        if (not isinstance(candidate, dict) or set(candidate) != set(SCOPE_KEYS)
                or any(not _text(candidate[key]) for key in SCOPE_KEYS)):
            return Choice(None, 'invalid scope')
    if scope != expected_scope:
        return Choice(None, 'scope mismatch')
    observed_at = snapshot.get('observed_at')
    if not all(_number(value) for value in (observed_at, now, max_age)) or max_age <= 0:
        return Choice(None, 'invalid observation time')
    if now < observed_at or now - observed_at >= max_age:
        return Choice(None, 'future or expired observation')
    if (not isinstance(approved_ids, (list, tuple)) or not approved_ids
            or any(not _text(value) for value in approved_ids)
            or len(set(approved_ids)) != len(approved_ids) or not _text(required_capability)):
        return Choice(None, 'invalid application selection policy')
    response = snapshot.get('response')
    if (not isinstance(response, dict) or 'error' in response
            or not isinstance(response.get('data'), list)):
        return Choice(None, 'invalid catalog')
    catalog = {}
    for item in response['data']:
        if not isinstance(item, dict):
            return Choice(None, 'invalid catalog')
        model_id, capabilities = item.get('id'), item.get('capabilities')
        if (not _text(model_id) or model_id in catalog
                or not isinstance(capabilities, list)
                or any(not _text(value) for value in capabilities)):
            return Choice(None, 'invalid catalog')
        catalog[model_id] = capabilities
    for position, model_id in enumerate(approved_ids):
        if model_id in catalog and required_capability in catalog[model_id]:
            role = 'primary' if position == 0 else 'approved alternative'
            return Choice(model_id, role + ': observed membership and capability only')
    return Choice(None, 'no approved candidate has the required evidence')


def main():
    scope = dict(environment='demo', base_url='https://example.invalid/v1',
                 credential_alias='offline-fixture', credential_revision='r1')
    snapshot = dict(scope=scope, observed_at=100, response={'data': [
        {'id': 'demo-chat-primary', 'capabilities': ['image']},
        {'id': 'demo-chat-secondary', 'capabilities': ['chat']}]})
    choice = select_model(snapshot, scope, ['demo-chat-primary', 'demo-chat-secondary'],
                          'chat', now=110, max_age=30)
    print('Fictional offline selection:', choice.model_id, '|', choice.reason)


if __name__ == '__main__':
    main()
