#!/usr/bin/env python3
"""A local, standard-library Hugging Face chat-completion example.

Requires Python 3.10+, HF_TOKEN, and HF_MODEL. Select a currently supported
provider/model route before running. A real request may incur provider charges.
Never copy the token into this file or into a browser-delivered application.
The network timeout applies to socket operations, not a strict global deadline.
"""
from __future__ import annotations
import argparse
import json
import os
import socket
import sys
import urllib.error
import urllib.request

ENDPOINT = 'https://router.huggingface.co/v1/chat/completions'


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--prompt', default='Explain latency versus throughput in two sentences.')
    parser.add_argument('--max-tokens', type=int, default=128)
    parser.add_argument('--timeout', type=float, default=30.0)
    args = parser.parse_args()
    if not 1 <= args.max_tokens <= 4096:
        parser.error('--max-tokens must be between 1 and 4096 for this example')
    if not 0 < args.timeout <= 120:
        parser.error('--timeout must be greater than 0 and at most 120 seconds')
    if not args.prompt.strip() or len(args.prompt) > 8000:
        parser.error('--prompt must contain 1–8000 characters')
    token = os.environ.get('HF_TOKEN', '').strip()
    model = os.environ.get('HF_MODEL', '').strip()
    if not token or not model:
        print('Set HF_TOKEN and HF_MODEL in your local environment. No request sent.', file=sys.stderr)
        return 2
    payload = json.dumps({
        'model': model,
        'messages': [{'role': 'user', 'content': args.prompt}],
        'max_tokens': args.max_tokens,
        'stream': False,
    }).encode('utf-8')
    request = urllib.request.Request(
        ENDPOINT, data=payload, method='POST',
        headers={
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=args.timeout) as response:
            raw = response.read(2_000_001)
        if len(raw) > 2_000_000:
            raise ValueError('Response exceeds the example response limit')
        data = json.loads(raw)
        choices = data.get('choices') if isinstance(data, dict) else None
        if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
            raise ValueError('Missing response choices')
        message = choices[0].get('message')
        content = message.get('content') if isinstance(message, dict) else None
        if not isinstance(content, str) or not content.strip():
            raise ValueError('No usable text content returned')
        # This is generated text, not an instruction to execute automatically.
        print(content)
        if choices[0].get('finish_reason') != 'stop':
            print('Output did not finish with a normal stop. Review it as incomplete or exceptional.', file=sys.stderr)
            return 3
    except urllib.error.HTTPError as exc:
        print(f'HTTP {exc.code}. Check credentials, model access, provider support, and usage limits. No automatic retry.', file=sys.stderr)
        return 1
    except (urllib.error.URLError, TimeoutError, socket.timeout):
        print('Network failure or timeout. The upstream outcome may be uncertain; no automatic retry.', file=sys.stderr)
        return 1
    except (ValueError, TypeError, UnicodeDecodeError):
        print('Response failed validation. Inspect safely without logging credentials or private prompts.', file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
