"""Shared helpers for Helixor Decision Runtime reproduction benchmarks."""
import os
import platform
import subprocess
import sys

PAYLOADS = [
    "Normal business inquiry regarding Q3 vendor service invoice #49280.",
    "Security incident report: SSN 123-45-6789 detected on host 192.168.1.104.",
    "Payment tokenization: card 4111-1111-1111-1111 for user test@company.org.",
    "Clinical triage notes: Patient ID MRN-948201 admitted with chest pain.",
    "Contact update requested via telephone (415) 555-0199 or email user@domain.com.",
]


def _sysctl(name: str) -> str:
    try:
        return subprocess.check_output(["sysctl", "-n", name], text=True).strip()
    except Exception:
        return "n/a"


def environment() -> str:
    mem = _sysctl("hw.memsize")
    mem_gb = f"{int(mem) / 2**30:.0f} GB" if mem.isdigit() else mem
    return (
        f"cpu={_sysctl('machdep.cpu.brand_string')} cores={os.cpu_count()} ram={mem_gb} "
        f"os={platform.platform()} python={sys.version.split()[0]}"
    )


def pct(sorted_vals: list, p: float) -> float:
    """Nearest-rank percentile on an already-sorted list."""
    idx = min(len(sorted_vals) - 1, max(0, int(round(p / 100.0 * len(sorted_vals))) - 1))
    return sorted_vals[idx]


def summarize(label: str, ns: list[int], unit: str = "us") -> None:
    div = 1_000 if unit == "us" else 1_000_000
    s = sorted(ns)
    total_s = sum(ns) / 1e9
    print(
        f"{label}: n={len(s)} p50={pct(s, 50) / div:.2f}{unit} p90={pct(s, 90) / div:.2f}{unit} "
        f"p99={pct(s, 99) / div:.2f}{unit} max={s[-1] / div:.2f}{unit} "
        f"mean={total_s / len(s) * 1e9 / div:.2f}{unit} ops/s={len(s) / total_s:,.0f}"
    )
