"""Python 3.11+ standard-library example; importing makes no request.
Source: https://docs.mistral.ai/api/endpoint/chat; checked 2026-10-12.
Run: python mistral-chat.py [text|json|image|stream] [public HTTPS image URL]
"""
import json, os, sys, urllib.request, urllib.error, urllib.parse

def body(mode='text', image_url=None):
    content = 'Explain safe retries in three sentences.'
    result = {'model': 'mistral-large-4', 'max_tokens': 1024, 'stream': mode == 'stream'}
    if mode == 'image':
        image = urllib.parse.urlparse(image_url or '')
        if image.scheme != 'https' or not image.hostname or image.username or image.password:
            raise ValueError('Use a public HTTPS image URL')
        content = [{'type': 'text', 'text': 'Describe visible labels; mark unreadable text.'}, {'type': 'image_url', 'image_url': image_url}]
    if mode == 'json':
        content = 'Return JSON with a string summary and an array of string checks for safe retries.'
        result['response_format'] = {'type': 'json_schema', 'json_schema': {'name': 'retry_summary', 'strict': True, 'schema': {'type': 'object', 'properties': {'summary': {'type': 'string'}, 'checks': {'type': 'array', 'items': {'type': 'string'}}}, 'required': ['summary', 'checks'], 'additionalProperties': False}}}
    result['messages'] = [{'role': 'user', 'content': content}]
    return result

def validate_summary(text):
    value = json.loads(text)
    if not isinstance(value, dict) or set(value) != {'summary', 'checks'} or not isinstance(value['summary'], str) or not isinstance(value['checks'], list) or not all(isinstance(item, str) for item in value['checks']):
        raise ValueError('JSON did not match the requested schema')
    return value

def chat(key, mode='text', image_url=None, opener=urllib.request.urlopen):
    if not key:
        raise ValueError('Set MISTRAL_API_KEY on the server')
    request = urllib.request.Request('https://api.mistral.ai/v1/chat/completions', data=json.dumps(body(mode, image_url)).encode(), headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
    try:
        with opener(request, timeout=35) as response:
            if mode != 'stream':
                result = json.load(response); choices = result.get('choices') or []
                if not choices or not isinstance(choices[0].get('message', {}).get('content'), str):
                    raise ValueError('Provider returned no text choice')
                if choices[0].get('finish_reason') == 'length':
                    raise ValueError('Output reached its token limit')
                text = choices[0]['message']['content']
                return validate_summary(text) if mode == 'json' else text
            text = ''; data = []; done = False; limited = False
            for line in response:
                line = line.decode().rstrip('\r\n')
                if line.startswith('data:'):
                    data.append(line[5:].lstrip())
                if line == '' and data:
                    payload = '\n'.join(data); data = []
                    if payload == '[DONE]':
                        done = True; break
                    event = json.loads(payload)
                    if event.get('error'):
                        raise ValueError('Provider interrupted the response')
                    for choice in event.get('choices', []):
                        limited |= choice.get('finish_reason') == 'length'
                        delta = choice.get('delta', {}).get('content')
                        if isinstance(delta, str):
                            text += delta
            if not done:
                raise ValueError('Stream interrupted; partial text is not a completed answer')
            if limited or not text:
                raise ValueError('Output was limited or empty')
            return text
    except urllib.error.HTTPError as error:
        # Do not print provider bodies, prompts or credentials.
        if error.code == 429:
            raise RuntimeError('Provider rate limit; Retry-After: ' + (error.headers.get('Retry-After') or 'unspecified')) from None
        raise RuntimeError('Provider request failed (' + str(error.code) + ')') from None

if __name__ == '__main__':
    try:
        mode = sys.argv[1] if len(sys.argv) > 1 else 'text'
        if mode not in {'text', 'json', 'image', 'stream'}:
            raise ValueError('Choose text, json, image or stream')
        result = chat(os.environ.get('MISTRAL_API_KEY', ''), mode, sys.argv[2] if len(sys.argv) > 2 else None)
        print(json.dumps(result, ensure_ascii=False) if isinstance(result, dict) else result)
    except (ValueError, RuntimeError, TimeoutError, urllib.error.URLError, KeyboardInterrupt):
        print('Request did not complete. Check settings, connectivity and rate limits; no automatic retry.', file=sys.stderr)
        sys.exit(1)
