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


def main():
    secrets = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    base = secrets.get("base_url", "https://api.shodan.io").rstrip("/")
    key = secrets.get("api_key", "")

    ips = str(inputs.get("ips", "")).strip()
    if not ips:
        print(json.dumps({"error": "ips is required"}))
        sys.exit(1)

    # Shodan's POST /shodan/scan expects an application/x-www-form-urlencoded body.
    form = {"ips": ips}
    if inputs.get("service"):
        form["service"] = str(inputs["service"])

    url = base + "/shodan/scan?" + urllib.parse.urlencode({"key": key})
    data = urllib.parse.urlencode(form).encode("utf-8")
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/json",
    }
    req = urllib.request.Request(url, data=data, headers=headers, method="POST")
    with urllib.request.urlopen(req, timeout=30) as resp:
        raw = resp.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)
