"""One diagnostic GET; proxy credentials never become origin Authorization."""
import asyncio
import os
import ssl
import sys
from urllib.parse import quote, urlsplit, urlunsplit

import aiohttp


async def main():
    endpoint = urlsplit(os.environ["PROXY_URL"])
    if endpoint.scheme not in ("http", "https") or not endpoint.hostname:
        raise ValueError("Use an HTTP or HTTPS proxy endpoint")
    if endpoint.username is not None or endpoint.path not in ("", "/") or endpoint.query or endpoint.fragment:
        raise ValueError("PROXY_URL must contain only the scheme, host and port")
    user = quote(os.environ["PROXY_USER"], safe="")
    password = quote(os.environ["PROXY_PASSWORD"], safe="")
    proxy = urlunsplit((endpoint.scheme, f"{user}:{password}@{endpoint.netloc}", "", "", ""))
    tls = ssl.create_default_context(cafile=os.environ.get("SSL_CERT_FILE"))
    connector = aiohttp.TCPConnector(limit=2, limit_per_host=2, ssl=tls)
    timeout = aiohttp.ClientTimeout(total=30, connect=10, sock_read=20)
    async with aiohttp.ClientSession(
        connector=connector, timeout=timeout, trust_env=False,
        cookie_jar=aiohttp.DummyCookieJar(),
    ) as session:
        async with session.get(
            os.environ.get("TARGET_URL", "https://example.com/"),
            proxy=proxy, allow_redirects=False,
        ) as response:
            print(f"HTTP {response.status}")
            response.raise_for_status()
            body = await response.read()
            print(f"Received {len(body)} bytes")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as error:
        print(f"Request failed: {type(error).__name__}", file=sys.stderr)
        sys.exit(1)
