#!/usr/bin/env python3
"""One text-only chat-completion request. No third-party Python dependencies."""
import getpass
import ipaddress
import json
import os
import socket
import sys
from urllib.parse import urlsplit
from urllib.request import Request, build_opener, HTTPRedirectHandler
from urllib.error import HTTPError, URLError

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

def main():
    base = (os.getenv('UI_TARS_BASE_URL') or input('Base URL from your deployment: ')).strip()
    model = (os.getenv('UI_TARS_MODEL') or input('Exact model/deployment name: ')).strip()
    try:
        parts = urlsplit(base)
        host = parts.hostname or ''
        try:
            loopback = ipaddress.ip_address(host).is_loopback
        except ValueError:
            loopback = host == 'localhost'
        if (not host or parts.username or parts.password or parts.query or parts.fragment
            or not (parts.scheme == 'https' or (parts.scheme == 'http' and loopback))
            or parts.path.rstrip('/').endswith(('/chat/completions', '/responses'))):
            raise ValueError()
        parts.port  # validate a malformed port before prompting for a credential
        if not model:
            raise ValueError()
    except ValueError:
        print('Invalid settings: use an HTTPS API base URL (HTTP only for loopback), no credentials/query, and a model name. Do not include /chat/completions or /responses in the base.')
        return 2
    key = (os.getenv('UI_TARS_API_KEY') or getpass.getpass('API key (hidden; not saved): ')).strip()
    if not key or '\n' in key or '\r' in key:
        print('Missing or invalid API key.'); return 2
    body = json.dumps({'model': model, 'messages': [{'role': 'user', 'content': 'Reply with only the result of 1+1.'}], 'stream': False}).encode()
    req = Request(base.rstrip('/') + '/chat/completions', data=body,
                  headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + key}, method='POST')
    try:
        with build_opener(NoRedirect).open(req, timeout=15) as response:
            data = json.loads(response.read(1024*1024))
            if not isinstance(data,dict) or not (data.get('id') or data.get('choices')):
                print('HTTP 200: unexpected response shape. Compare the endpoint API with chat completions.'); return 1
            print('HTTP 200: chat-completion response received. Verify image input and an operator task separately.')
            return 0
    except HTTPError as error:
        guidance = {401:'Check the key and endpoint access.',403:'Check deployment permissions and provider policy.',404:'Compare the API base path and exact model identifier.',429:'Check quota, capacity and provider retry guidance.'}
        print('HTTP '+str(error.code)+': '+guidance.get(error.code,'Check provider diagnostics. Redirects are not followed.'))
        return 1
    except (URLError, TimeoutError, socket.timeout):
        print('Connection failed: check network, TLS trust and endpoint availability.'); return 1
    except (ValueError, OSError):
        print('Response could not be read as chat-completion JSON. Check the endpoint API.'); return 1

if __name__ == '__main__':
    try:
        sys.exit(main())
    except (EOFError, KeyboardInterrupt):
        print('\nCheck cancelled; no settings saved.'); sys.exit(2)
