"""Send one GET with a Python HTTP client and print one JSON line.

Usage: python py_client.py LIBRARY URL
LIBRARY is one of: urllib, requests, httpx, httpx2, aiohttp.

The client reads proxy settings from the environment only (its default
behavior; aiohttp needs trust_env=True). The route decision is observed by
the lab proxy, not reported by this script.
"""

import json
import sys

TIMEOUT = 5


def short(exc):
    parts = []
    seen = 0
    while exc is not None and seen < 4:
        parts.append(f"{type(exc).__name__}: {exc}"[:160])
        exc = exc.__cause__ or exc.__context__
        seen += 1
    return " <- ".join(parts)


def marker(body):
    if "C08-PROXY" in body:
        return "proxy"
    if "C08-ORIGIN" in body:
        return "origin"
    return None


def run(lib, url):
    if lib == "urllib":
        import urllib.request

        with urllib.request.urlopen(url, timeout=TIMEOUT) as r:
            return r.status, r.read().decode("utf-8", "replace")
    if lib == "requests":
        import requests

        r = requests.get(url, timeout=TIMEOUT)
        return r.status_code, r.text
    if lib == "httpx":
        import httpx

        r = httpx.get(url, timeout=TIMEOUT)
        return r.status_code, r.text
    if lib == "httpx2":
        import httpx2

        r = httpx2.get(url, timeout=TIMEOUT)
        return r.status_code, r.text
    if lib == "aiohttp":
        import asyncio

        import aiohttp

        async def go():
            timeout = aiohttp.ClientTimeout(total=TIMEOUT)
            async with aiohttp.ClientSession(trust_env=True, timeout=timeout) as s:
                async with s.get(url) as r:
                    return r.status, await r.text()

        return asyncio.run(go())
    raise SystemExit(f"unknown library {lib}")


def version(lib):
    if lib == "urllib":
        return sys.version.split()[0]
    from importlib.metadata import version as v

    return v(lib)


def main():
    lib, url = sys.argv[1], sys.argv[2]
    if url == "--version":
        print(json.dumps({"library": lib, "version": version(lib), "python": sys.version.split()[0]}))
        return 0
    try:
        status, body = run(lib, url)
        print(json.dumps({"ok": True, "status": status, "marker": marker(body), "error": None}))
        return 0
    except Exception as exc:  # noqa: BLE001 - every failure is data here
        print(json.dumps({"ok": False, "status": None, "marker": None, "error": short(exc)}))
        return 1


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