"""Offline evidence interpreter for ONE ordinary-text Chat Completions workload.

No probes are sent. Scope, observed_at, status, transport, response and events
are application-captured observation fields, not a proposed API429 response.
Scope endpoint is relative to base_url: /chat/completions. Mode is json or sse.
SSE events below are ALREADY PARSED synthetic data objects plus '[DONE]'; this
is not a wire parser. A production caller must parse framing separately.

A complete verdict is evidence only for this scope at the recorded time, not
an SLA, admission decision, future availability, retry or fallback permission.
Timeout/transport failure may follow a paid operation: unknown outcome does not
authorize replay. max_age grants no HTTP-cache retention/sharing permission.
All demo model IDs are fictional, not API429 availability promises.
"""
import math
from typing import NamedTuple


class Verdict(NamedTuple):
    state: str
    reason: str


SCOPE_KEYS = ('environment', 'base_url', 'credential_alias', 'credential_revision',
              'model', 'endpoint', 'mode')


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 _choice(response):
    if not isinstance(response, dict) or 'error' in response:
        return None
    choices = response.get('choices')
    if not isinstance(choices, list) or len(choices) != 1 or not isinstance(choices[0], dict):
        return None
    choice = choices[0]
    index = choice.get('index', 0)
    if type(index) is not int or index != 0:
        return None
    return choice


def _ordinary(payload):
    return (isinstance(payload, dict)
            and not any(key in payload for key in ('tool_calls', 'function_call', 'refusal')))


def _json_complete(response):
    choice = _choice(response)
    if choice is None or choice.get('finish_reason') != 'stop':
        return False
    message = choice.get('message')
    return (_ordinary(message) and message.get('role') == 'assistant'
            and _text(message.get('content')))


def _sse_complete(events):
    if not isinstance(events, list):
        return False
    text, terminal, done = '', False, False
    for event in events:
        if done:
            return False
        if event == '[DONE]':
            if not terminal:
                return False
            done = True
            continue
        if terminal:
            return False
        choice = _choice(event)
        if choice is None:
            return False
        delta = choice.get('delta')
        if not _ordinary(delta) or delta.get('role', 'assistant') != 'assistant':
            return False
        content = delta.get('content', '')
        if not isinstance(content, str):
            return False
        text += content
        finish = choice.get('finish_reason')
        if finish is not None:
            if finish != 'stop':
                return False
            terminal = True
    return bool(text.strip()) and terminal and done


def interpret_probe(observation, expected_scope, now, max_age):
    """Classify already-captured evidence, returning only generic safe reasons.

    Optional transport='timeout' or 'transport_error' records uncertain delivery
    or completion, including failures after headers. This conservative example
    has no 'not sent' inference. It never compares response.model to request
    scope: a provider may return a canonical/versioned model alias.
    """
    if not isinstance(observation, dict):
        return Verdict('invalid', 'invalid observation')
    scope = observation.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 Verdict('invalid', 'invalid scope')
    if scope != expected_scope:
        return Verdict('invalid', 'scope mismatch')
    if scope['endpoint'] != '/chat/completions' or scope['mode'] not in ('json', 'sse'):
        return Verdict('invalid', 'outside this ordinary-text contract')
    observed_at = observation.get('observed_at')
    if not all(_number(value) for value in (observed_at, now, max_age)) or max_age <= 0:
        return Verdict('invalid', 'invalid observation time')
    if now < observed_at or now - observed_at >= max_age:
        return Verdict('invalid', 'future or expired observation')
    if 'transport' in observation:
        if observation['transport'] in ('timeout', 'transport_error'):
            return Verdict('unknown_outcome', 'delivery or completion is uncertain')
        return Verdict('invalid', 'unknown transport observation')
    status = observation.get('status')
    if type(status) is not int or not 100 <= status <= 599:
        return Verdict('invalid', 'invalid HTTP status')
    if status in (401, 403):
        return Verdict('access_error', 'access failed for the observed scope')
    if status == 404:
        return Verdict('method_model_not_confirmed', 'this method/model was not confirmed')
    if status == 429:
        return Verdict('rate_limited', 'rate-limit response; no internal cause inferred')
    if 500 <= status <= 599:
        return Verdict('server_error', 'server-error response for the observed scope')
    if status != 200:
        return Verdict('unknown', 'no complete result established')
    complete = (_json_complete(observation.get('response')) if scope['mode'] == 'json'
                else _sse_complete(observation.get('events')))
    if complete:
        return Verdict('complete', 'complete ordinary-text result observed at the recorded time')
    return Verdict('incomplete', 'complete ordinary-text result not established')


def main():
    scope = dict(environment='demo', base_url='https://example.invalid/v1',
                 credential_alias='offline-fixture', credential_revision='r1',
                 model='demo-chat-primary', endpoint='/chat/completions', mode='json')
    observation = dict(scope=scope, observed_at=100, status=200, response={'choices': [
        {'message': {'role': 'assistant', 'content': 'Synthetic OK'}, 'finish_reason': 'stop'}]})
    print('Fictional complete observation:', interpret_probe(observation, scope, 110, 30))
    observation['transport'] = 'timeout'
    print('Fictional uncertain observation:', interpret_probe(observation, scope, 110, 30))


if __name__ == '__main__':
    main()
