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


def _cfg():
    s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
    base = str(s.get("base_url") or "https://www.virustotal.com/api/v3").rstrip("/")
    headers = {"x-apikey": s.get("api_key", ""), "Accept": "application/json"}
    return base, headers


def _inputs():
    return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))


def run():
    base, headers = _cfg()
    url_value = str(_inputs().get("url", ""))
    # VirusTotal expects the URL submission as form-encoded data.
    data = urllib.parse.urlencode({"url": url_value}).encode("utf-8")
    h = dict(headers)
    h["Content-Type"] = "application/x-www-form-urlencoded"
    req = urllib.request.Request(base + "/urls", data=data, headers=h, method="POST")
    with urllib.request.urlopen(req, timeout=90) as r:
        raw = r.read()
        print(json.dumps(json.loads(raw) if raw else {}))


try:
    run()
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)
