import json, os, sys, urllib.request, urllib.parse, urllib.error

SECRETS = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
INPUTS = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
BASE = SECRETS.get("base_url", "https://api.ipinfo.io").rstrip("/")


def main():
    token = SECRETS.get("token", "")
    ips = [x.strip() for x in str(INPUTS.get("ips", "")).split(",") if x.strip()]
    if not ips:
        print(json.dumps({"error": "ips is required"}))
        sys.exit(1)

    # IPinfo's POST /batch expects a raw JSON array of IPs / lookup paths.
    url = BASE + "/batch?" + urllib.parse.urlencode({"token": token})
    data = json.dumps(ips).encode("utf-8")
    headers = {"Content-Type": "application/json", "Accept": "application/json"}
    req = urllib.request.Request(url, data=data, headers=headers, method="POST")
    with urllib.request.urlopen(req, timeout=30) as r:
        raw = r.read()
        print(json.dumps(json.loads(raw) if raw else {}))


try:
    main()
except urllib.error.HTTPError as e:
    print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
    sys.exit(1)
except Exception as e:
    print(json.dumps({"error": str(e)}))
    sys.exit(1)
