"""Frozen PP-281 core queries; records raw streams, exits and elapsed time."""

import json
import os
import pathlib
import subprocess
import time


ROOT = pathlib.Path("/home/graklink-ops/.cache/practicalpicks/pp281")
OUT = ROOT / "smoke-results.json"
CASES = [
    ("A", "a.pp281.test."),
    ("MX", "pp281.test."),
    ("TXT", "pp281.test."),
    ("CAA", "pp281.test."),
    ("NXDOMAIN", "missing.pp281.test."),
    ("TIMEOUT", "blackhole.pp281.test."),
]
KNOT_LIB = str(ROOT / "usr/lib/x86_64-linux-gnu")


def command(tool, kind, name):
    qtype = "A" if kind in ("NXDOMAIN", "TIMEOUT") else kind
    if tool == "dig":
        return ["/usr/bin/dig", "@127.0.0.1", "-p", "15381", name, qtype,
                "+time=1", "+tries=1", "+nosearch"]
    if tool == "kdig":
        return [str(ROOT / "usr/bin/kdig"), "@127.0.0.1", "-p", "15381",
                name, qtype, "+timeout=1", "+retry=0"]
    return [str(ROOT / "bin/doggo"), name, qtype,
            "@127.0.0.1:15381", "--timeout=1s", "--search=false",
            "--color=false", "--strategy=first"]


rows = []
for tool in ("dig", "kdig", "doggo"):
    for kind, name in CASES:
        cmd = command(tool, kind, name)
        env = dict(os.environ)
        if tool == "kdig":
            env["LD_LIBRARY_PATH"] = KNOT_LIB
        start = time.monotonic()
        try:
            proc = subprocess.run(cmd, capture_output=True, text=True,
                                  timeout=4, env=env, check=False)
            row = dict(tool=tool, case=kind, command=cmd,
                       exit=proc.returncode, stdout=proc.stdout,
                       stderr=proc.stderr,
                       elapsed_s=round(time.monotonic() - start, 3))
        except subprocess.TimeoutExpired as exc:
            row = dict(tool=tool, case=kind, command=cmd,
                       exit="harness timeout", stdout=str(exc.stdout or ""),
                       stderr=str(exc.stderr or ""),
                       elapsed_s=round(time.monotonic() - start, 3))
        rows.append(row)
OUT.write_text(json.dumps(rows, indent=2) + "\n")
print(OUT)
