"""Test one MantaProxy resource with Requests. Install: requests[socks]."""

import os
from getpass import getpass
from urllib.parse import quote

import requests


def build_proxies():
    required = ("MANTA_PROXY_HOST", "MANTA_PROXY_PORT", "MANTA_PROXY_USERNAME")
    missing = [name for name in required if not os.environ.get(name)]
    if missing:
        raise SystemExit("Set these variables first: " + ", ".join(missing))

    scheme = os.environ.get("MANTA_PROXY_SCHEME", "http").strip().lower()
    if scheme not in ("http", "socks5h"):
        raise SystemExit("MANTA_PROXY_SCHEME must be http or socks5h.")
    host = os.environ["MANTA_PROXY_HOST"].strip()
    if "://" in host or "/" in host or "@" in host:
        raise SystemExit("Use the host only, without a URL, port or credentials.")
    try:
        port = int(os.environ["MANTA_PROXY_PORT"])
        if not 1 <= port <= 65535:
            raise ValueError
    except ValueError:
        raise SystemExit("MANTA_PROXY_PORT must be a number from 1 to 65535.")

    username = os.environ["MANTA_PROXY_USERNAME"]
    password = os.environ.get("MANTA_PROXY_PASSWORD") or getpass("Proxy password: ")
    if not password:
        raise SystemExit("A proxy password is required.")
    if ":" in host and not host.startswith("["):
        host = "[" + host + "]"
    auth = quote(username, safe="") + ":" + quote(password, safe="")
    proxy_url = f"{scheme}://{auth}@{host}:{port}"
    return {"http": proxy_url, "https": proxy_url}


def main():
    proxies = build_proxies()
    with requests.Session() as session:
        session.trust_env = False
        try:
            response = session.get(
                "https://api.ipify.org?format=json",
                proxies=proxies,
                timeout=(10, 30),
            )
            response.raise_for_status()
            exit_ip = response.json()["ip"]
        except requests.exceptions.ProxyError:
            raise SystemExit("Proxy error: check host, port, protocol and credentials.")
        except requests.exceptions.Timeout:
            raise SystemExit("Timeout: check proxy reachability and the target site.")
        except requests.exceptions.SSLError:
            raise SystemExit("TLS error: check system time and trusted CA certificates.")
        except requests.exceptions.HTTPError as error:
            raise SystemExit(f"HTTP error: {error.response.status_code}")
        except requests.exceptions.RequestException:
            raise SystemExit("Request failed. Check the configuration and network.")
        except (ValueError, KeyError):
            raise SystemExit("The IP check did not return the expected JSON result.")
    print("Exit IP:", exit_ip)


if __name__ == "__main__":
    main()
