#!/usr/bin/env python3
"""Minimal btcnodes.io authenticated API client example.

Set BITNODES_API_KEY to include an Authorization header. Public local
deployments can also use this script without a key for unauthenticated requests.
"""

import json
import os
import sys
import urllib.request


BASE_URL = os.environ.get("BITNODES_API_BASE", "https://btcnodes.io")
API_KEY = os.environ.get("BITNODES_API_KEY", "")


def get_json(path):
    url = f"{BASE_URL.rstrip('/')}{path}"
    headers = {"Accept": "application/json; indent=4"}
    if API_KEY:
        headers["Authorization"] = f"Token {API_KEY}"
    request = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(request, timeout=30) as response:
        remaining = response.headers.get("ratelimit-remaining", "unknown")
        payload = json.load(response)
    return remaining, payload


def main():
    path = sys.argv[1] if len(sys.argv) > 1 else "/api/v1/snapshots/"
    remaining, payload = get_json(path)
    print(f"ratelimit-remaining: {remaining}", file=sys.stderr)
    print(json.dumps(payload, indent=4, sort_keys=True))


if __name__ == "__main__":
    main()
