#!/usr/bin/env python3
"""Send one direct, non-streaming request to your Antigravity Manager gateway."""
import getpass
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 main():
    root = input("Gateway origin [http://127.0.0.1:8045]: ").strip()
    root = (root or "http://127.0.0.1:8045").rstrip("/")
    try:
        parts = urllib.parse.urlsplit(root)
        valid = (
            parts.scheme in ("http", "https") and parts.hostname
            and not (parts.path or parts.query or parts.fragment)
            and parts.username is None and parts.password is None
            and parts.port != 0
            and not any(c.isspace() or ord(c) < 32 for c in root)
            and "?" not in root and "#" not in root
            and root.isascii() and "\\" not in root
        )
    except ValueError:
        valid = False
    if not valid:
        raise SystemExit("Use an origin such as http://127.0.0.1:8045, without /v1 or credentials.")
    key = getpass.getpass("Gateway API key (hidden): ").strip()
    if not key or any(ord(c) < 33 or ord(c) > 126 for c in key):
        raise SystemExit("Enter a non-empty API key without spaces or control characters.")
    model = input("Model ID from API Proxy: ").strip()
    if not model:
        raise SystemExit("Enter a model ID offered by your gateway.")
    body = json.dumps({
        "model": model, "stream": False,
        "messages": [{"role": "user", "content": "Reply with Hello."}],
    }).encode()
    request = urllib.request.Request(
        root + "/v1/chat/completions", data=body,
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
    )
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
    try:
        with opener.open(request, timeout=60) as response:
            status = response.status
            raw = response.read(1048577)
    except urllib.error.HTTPError as error:
        print("HTTP", error.code)
        print(error.read(65536).decode("utf-8", errors="replace").replace(key, "[redacted]"))
        if 300 <= error.code < 400:
            print("Redirect blocked. Verify the gateway's final origin before retrying.")
        return 1
    except (urllib.error.URLError, OSError, ValueError) as error:
        print("Connection failed:", str(error).replace(key, "[redacted]"))
        return 1
    print("HTTP", status)
    if len(raw) > 1048576:
        print("Response exceeds 1 MiB. Inspect the gateway logs.")
        return 1
    text = raw.decode("utf-8", errors="replace")
    print(text.replace(key, "[redacted]"))
    try:
        data = json.loads(text)
        if not isinstance(data, dict) or data.get("error"):
            raise ValueError()
        content = data["choices"][0]["message"]["content"]
        if not isinstance(content, str) or not content.strip():
            raise ValueError()
    except (ValueError, KeyError, IndexError, TypeError):
        print("No text answer found. Use the response body to choose the next check.")
        return 1
    print("Read the answer above: does it reply to the Hello request?")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (KeyboardInterrupt, EOFError):
        raise SystemExit("Cancelled.")
