"""Python 3.10+, standard library only. Run with X1_API_KEY in the environment."""
import json
import os
import sys
from urllib.request import Request, urlopen
from urllib.error import HTTPError


def fetch_markets(key, opener=urlopen):
    if not key:
        raise ValueError('Set X1_API_KEY to an active key from x1.ninja/developers/keys')
    request = Request('https://api.x1.ninja/pools?limit=5&sortBy=volume24h&sortDir=desc', headers={'X-API-Key': key})
    try:
        with opener(request, timeout=8) as response:
            data = json.load(response)
    except HTTPError as error:
        messages = {401: 'Check whether your API key is active.', 403: 'Check your plan and account status.', 429: 'Rate limit reached; respect Retry-After before retrying.'}
        raise RuntimeError(f'API request failed ({error.code}). {messages.get(error.code, "Check x1.ninja/status.")}') from None
    if not isinstance(data.get('pools'), list):
        raise ValueError('Unexpected response: pools array missing')
    return data


if __name__ == '__main__':
    try:
        print(json.dumps(fetch_markets(os.environ.get('X1_API_KEY')), indent=2))
    except Exception as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
