import json, os, sys, base64, ipaddress, 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 _b64url(u):
    return base64.urlsafe_b64encode(u.encode()).decode().strip("=")


def _resource_path(resource, rtype):
    rtype = str(rtype or "").strip().lower()
    if not rtype:
        try:
            ipaddress.ip_address(resource)
            rtype = "ip"
        except ValueError:
            h = resource.strip()
            if len(h) in (32, 40, 64) and all(c in "0123456789abcdefABCDEF" for c in h):
                rtype = "file"
            elif "://" in resource:
                rtype = "url"
            else:
                rtype = "domain"
    coll = {"ip": "ip_addresses", "domain": "domains", "file": "files", "hash": "files", "url": "urls"}.get(rtype, "files")
    rid = _b64url(resource) if coll == "urls" else urllib.parse.quote(resource, safe="")
    return coll + "/" + rid


def request(method, path, body=None):
    base, headers = _cfg()
    h = dict(headers)
    data = None
    if body is not None:
        data = json.dumps(body).encode("utf-8")
        h["Content-Type"] = "application/json"
    req = urllib.request.Request(base + "/" + path.lstrip("/"), data=data, headers=h, method=method)
    with urllib.request.urlopen(req, timeout=90) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


def run():
    inp = _inputs()
    path = _resource_path(str(inp.get("resource", "")), inp.get("resource_type"))
    body = {"data": {"type": "comment", "attributes": {"text": inp.get("comment", "")}}}
    print(json.dumps(request("POST", path + "/comments", body=body)))


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)
