#!/usr/bin/env python3
"""Live smoke for the dashboard machine-intelligence tools (not run by default pytest).

Runs every run_host_diagnostics domain and every inspect_system_activity focus
against the REAL machine — no mocks — and asserts each returns a usable report.
The unit suite (tests/test_host_diagnostics.py, tests/test_dashboard_system_inspect.py)
covers verdict logic with fixtures; this script exists to catch the other bug class:
drift in real command output (a macOS update renaming a system_profiler key,
pmset format changes, a Mac with no battery / two GPUs / no printers).

A "broken" verdict (e.g. network down, AirPods disconnected) still PASSES —
we assert structure, not machine health.

Usage:
    python3 scripts/host_diagnostics_smoke.py            # everything
    python3 scripts/host_diagnostics_smoke.py power audio # selected cases only

Exits 0 when every case produced a verdict/report; 1 otherwise.
"""
from __future__ import annotations

import sys
import time

# Substrings that mean the collector could not understand the machine's output.
_DRIFT_MARKERS = (
    "Unknown domain",
    "Could not read",
    "returned no",
)


def main(argv: list[str]) -> int:
    import os

    repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    if repo_root not in sys.path:
        sys.path.insert(0, repo_root)

    from dashboard_bundled import host_diagnostics as hd
    from dashboard_bundled import system_inspect as si
    from dashboard_bundled.system_vitals import SystemVitalsCollector

    cases: dict[str, callable] = {
        # run_host_diagnostics domains (network last among diagnostics: slowest, live pings)
        "power": lambda: hd.diagnose("power"),
        "bluetooth": lambda: hd.diagnose("bluetooth"),
        "audio": lambda: hd.diagnose("audio"),
        "displays": lambda: hd.diagnose("displays"),
        "storage": lambda: hd.diagnose("storage"),
        "printing": lambda: hd.diagnose("printing"),
        "app": lambda: hd.diagnose("app", target="Finder"),
        "network": lambda: hd.diagnose("network"),
        # inspect_system_activity focuses
        "inspect-cpu": lambda: si.inspect("cpu"),
        "inspect-memory": lambda: si.inspect("memory"),
        "inspect-disk": lambda: si.inspect("disk"),
        "inspect-network": lambda: si.inspect("network"),
        # header-strip vitals sample
        "vitals": lambda: str(SystemVitalsCollector().sample()),
    }

    selected = [a for a in argv if not a.startswith("-")]
    unknown = [s for s in selected if s not in cases]
    if unknown:
        print(f"unknown case(s): {', '.join(unknown)}; available: {', '.join(cases)}", file=sys.stderr)
        return 1
    to_run = {k: v for k, v in cases.items() if not selected or k in selected}

    failures = 0
    for name, fn in to_run.items():
        start = time.monotonic()
        try:
            out = fn()
        except Exception as exc:
            print(f"FAIL {name}: raised {type(exc).__name__}: {exc}", file=sys.stderr)
            failures += 1
            continue
        elapsed = time.monotonic() - start
        text = out if isinstance(out, str) else str(out)
        problem = ""
        if not text.strip():
            problem = "empty output"
        elif name in ("power", "bluetooth", "audio", "displays", "storage", "printing", "app", "network") and "Verdict:" not in text:
            problem = "no Verdict line"
        else:
            hit = next((m for m in _DRIFT_MARKERS if m in text), "")
            if hit:
                problem = f'output drift marker: "{hit}"'
        if problem:
            print(f"FAIL {name} ({elapsed:.1f}s): {problem}", file=sys.stderr)
            first = text.strip().splitlines()[0] if text.strip() else "(empty)"
            print(f"     first line: {first}", file=sys.stderr)
            failures += 1
        else:
            verdict = next((ln for ln in text.splitlines() if ln.startswith("Verdict:")), "")
            print(f"ok   {name} ({elapsed:.1f}s)" + (f"  {verdict[:100]}" if verdict else ""))

    if failures:
        print(f"\nhost diagnostics smoke: {failures} failure(s)", file=sys.stderr)
        return 1
    print(f"\nhost diagnostics smoke ok ({len(to_run)} case(s))")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
