"""Score the blind faults once against the committed refresh checks. The faults module is data, read from its stored text."""
import argparse
import importlib.util
import json
from pathlib import Path
import sys

STUDY = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(STUDY / "src"))

import walk_checks as checks  # noqa: E402


def load_faults(path):
    spec = importlib.util.spec_from_loader("blind_faults", loader=None)
    module = importlib.util.module_from_spec(spec)
    exec(compile(Path(path).read_text(encoding="utf-8"), str(path), "exec"), module.__dict__)  # read before it was first run
    return [getattr(module, f"fault_{k}") for k in range(1, 9)]


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--faults", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    context = checks.Context(STUDY)
    stored = json.loads((STUDY / "data/walk-network-checks/refresh-checks.json").read_text(encoding="utf-8"))
    rows = []
    for fault in load_faults(args.faults):
        row = checks.run_fault(fault, context, stored["reference"], stored["sentinels"])
        row["what_went_wrong"] = fault.__doc__.strip()
        rows.append(row)
        print(row["fault"], row["caught"], row["failed_checks"], row["pipeline_error"], flush=True)
    missed = [row for row in rows if not row["caught"]]
    output = {"total": len(rows), "caught": len(rows) - len(missed), "rows": rows,
              "missed_summary": "; ".join(row["what_went_wrong"].rstrip(".").lower() for row in missed)}
    with args.output.open("x", encoding="utf-8") as handle:
        json.dump(output, handle, indent=1, sort_keys=True)
        handle.write("\n")
    print(f"VERDICT: blind faults caught {output['caught']} of {output['total']}")
