#!/usr/bin/env python3
"""Choose requests or httpx. Trusted endpoint and auth come from operator env."""
import os
import sys
from urllib.parse import urlsplit


def main():
    try:
        target, proxy = os.environ["QG_TARGET_URL"], os.environ["QUOTAGUARDSTATIC_URL"]
        t, p = urlsplit(target), urlsplit(proxy)
        if t.scheme != "https" or t.username or t.password or not t.hostname:
            raise ValueError()
        if p.scheme not in ("http", "https") or not p.hostname or not p.username or not p.password:
            raise ValueError()
        token = os.environ.get("DESTINATION_API_TOKEN", "")
        if any(ord(c) < 32 or ord(c) == 127 for c in target + proxy + token):
            raise ValueError()
        if token and t.hostname == "ip.quotaguard.com":
            raise ValueError()
        headers = {"Authorization": "Bearer " + token} if token else {}
        mode = sys.argv[1] if len(sys.argv) == 2 else "requests"
        if mode == "requests":
            import requests
            with requests.Session() as client:
                client.trust_env = False
                response = client.get(target, proxies={"http": proxy, "https": proxy},
                                      headers=headers, timeout=(10, 30), allow_redirects=False)
        elif mode == "httpx":
            import httpx
            with httpx.Client(proxy=proxy, trust_env=False, follow_redirects=False, timeout=30) as client:
                response = client.get(target, headers=headers)
        else:
            raise ValueError()
        if not 200 <= response.status_code < 300:
            raise RuntimeError()
        print("PASS: destination returned a successful HTTP status")
    except Exception:
        print("Request failed; check configuration and the guide.", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
