"""Check an OpenAI-compatible HTTP boundary. No tunnel is started automatically."""
import base64
import ipaddress
import json
import urllib.error
import urllib.parse
import urllib.request

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

def basic_header(username,password):
    if not username or ':' in username or not password or any(c in username+password for c in '\r\n'):
        raise ValueError('nonempty credentials; no colon in username or newline')
    return 'Basic '+base64.b64encode(f'{username}:{password}'.encode()).decode()

def endpoint(base):
    parsed=urllib.parse.urlsplit(base)
    if parsed.username or parsed.password or parsed.query or parsed.fragment:
        raise ValueError('credentials/query/fragment do not belong in base URL')
    if not parsed.hostname or parsed.scheme not in ('https','http'):
        raise ValueError('HTTP(S) base URL required')
    local=parsed.hostname=='localhost'
    try: local=local or ipaddress.ip_address(parsed.hostname).is_loopback
    except ValueError: pass
    if parsed.scheme!='https' and not local:
        raise ValueError('plain HTTP is allowed only on loopback')
    return base.rstrip('/')+'/v1/chat/completions'

def request_chat(base,model,authorization=None,timeout=3):
    if not isinstance(model,str) or not model.strip(): raise ValueError('model ID required')
    headers={'Content-Type':'application/json'}
    if authorization:
        if '\r' in authorization or '\n' in authorization: raise ValueError('invalid header')
        headers['Authorization']=authorization
    payload=json.dumps({'model':model,'messages':[{'role':'user','content':'Reply with OK.'}],
                        'max_tokens':8,'stream':False}).encode()
    req=urllib.request.Request(endpoint(base),data=payload,headers=headers)
    opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect())
    try:
        with opener.open(req,timeout=timeout) as response:
            raw=response.read(65537)
            if len(raw)>65536: raise ValueError('response exceeds preflight limit')
            data=json.loads(raw)
            content=data['choices'][0]['message']['content']
            if not isinstance(content,str): raise ValueError('content is not a string')
            return response.status,content
    except urllib.error.HTTPError as error:
        # Do not expose error bodies or secret headers in logs.
        status=error.code; error.close(); return status,None

def check(base,model,authorization):
    denied,_=request_chat(base,model)
    if denied!=401: raise RuntimeError(f'expected unauthenticated 401, got {denied}')
    accepted,content=request_chat(base,model,authorization)
    if accepted!=200: raise RuntimeError(f'authenticated request returned {accepted}')
    return {'unauthenticated':denied,'authenticated':accepted,'response_shape':'chat content string'}

if __name__=='__main__':
    import os
    print(json.dumps(check(os.environ['LLM_BASE_URL'],os.environ['LLM_MODEL'],
                           basic_header(os.environ['EDGE_USER'],os.environ['EDGE_PASSWORD']))))
