"""Explicit HTTPX client for an existing QuotaGuard subscription; never logs secrets."""
import ipaddress
import os
import re
from urllib.parse import urlsplit

class ConfigurationError(ValueError):
    pass

def connection():
    product = os.environ.get('QG_PRODUCT', 'static').lower()
    names = {'static': ('QUOTAGUARDSTATIC_URL', 'http', 9293),
             'shield': ('QUOTAGUARDSHIELD_URL', 'https', 9294)}
    if product not in names:
        raise ConfigurationError('QG_PRODUCT must be static or shield')
    key, scheme, port = names[product]
    raw = os.environ.get(key, '')
    try:
        u = urlsplit(raw)
        valid = (u.scheme == scheme and u.port == port and u.hostname
                 and u.username and u.password and u.path in ('', '/')
                 and not u.query and not u.fragment)
    except ValueError:
        valid = False
    if not valid:
        raise ConfigurationError('Missing or invalid dashboard proxy connection')
    return raw

def client():
    import httpx
    return httpx.Client(proxy=connection(), trust_env=False,
                        timeout=httpx.Timeout(30.0, connect=10.0),
                        follow_redirects=False)

def check_egress():
    pair = [x.strip() for x in os.environ.get('QG_EXPECTED_IPS', '').split(',') if x.strip()]
    try:
        if len(pair) != 2 or len(set(pair)) != 2:
            raise ValueError()
        pair = {str(ipaddress.IPv4Address(x)) for x in pair}
    except ValueError:
        raise ConfigurationError('Set QG_EXPECTED_IPS to the two dashboard IPv4 addresses') from None
    with client() as c:
        r = c.get('https://ip.quotaguard.com')
        r.raise_for_status()
        if r.status_code != 200:
            raise RuntimeError('IP check did not return HTTP 200')
        observed = str(ipaddress.IPv4Address(r.json()['ip']))
    if observed not in pair:
        raise RuntimeError('Observed egress is outside the dashboard pair')
    return {'verified': True, 'route': 'this HTTPX client', 'matches_dashboard_pair': True}

def partner_status():
    url = os.environ.get('PARTNER_STATUS_URL', '')
    u = urlsplit(url)
    if u.scheme != 'https' or not u.hostname or u.username or u.password or u.fragment or u.query:
        raise ConfigurationError('Set a fixed HTTPS PARTNER_STATUS_URL without credentials or query')
    if u.hostname.lower() == 'ip.quotaguard.com':
        raise ConfigurationError('Use check_egress for the public IP check; do not send a partner token there')
    token = os.environ.get('PARTNER_API_TOKEN', '')
    if not re.fullmatch(r'[A-Za-z0-9._~+/-]+=*', token):
        raise ConfigurationError('Set the partner API bearer token securely')
    with client() as c:
        r = c.get(url, headers={'Authorization': 'Bearer ' + token})
        r.raise_for_status()
    # Do not expose response bodies, URLs, tokens or proxy connection details to the model.
    return {'ok': True, 'http_status': r.status_code}

if __name__ == '__main__':
    try:
        print(check_egress())
    except Exception:
        raise SystemExit('Egress check failed; review configuration and the troubleshooting table') from None
