#!/usr/bin/env python3
"""Execute one implementation against selected and bounded complete traces."""
import argparse
import gzip
import itertools
import json
from pathlib import Path
import time

from debounce import ALPHABET, run
from oracle import expected_flags


def write_json(path, data):
    path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--implementation", required=True,
                        choices=("baseline", "corrected", "off_by_one", "unknown_pauses"))
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    started = time.perf_counter()
    args.output.mkdir(parents=True, exist_ok=False)
    selected = json.loads(Path(__file__).with_name("selected-traces.json").read_text())
    results = []
    for row in selected:
        if expected_flags(row["samples"]) != row["expected"]:
            raise RuntimeError("literal selected expectation disagrees with window oracle")
        actual = run(row["samples"], args.implementation)
        results.append({**row, "actual": actual, "pass": actual == row["expected"],
                        "mismatch_sample_indexes_zero_based": [
                            i for i, (a, e) in enumerate(zip(actual, row["expected"])) if a != e]})
    failed_selected = [r["id"] for r in results if not r["pass"]]
    write_json(args.output / "selected-results.json", {
        "implementation": args.implementation, "unit": "whole selected trace",
        "traces": len(results), "passed": len(results) - len(failed_selected),
        "failed": len(failed_selected), "failed_trace_ids": failed_selected,
        "observations": results})
    total = passed = sample_positions = 0
    counterexamples = []
    with (args.output / "enumeration-observations.jsonl.gz").open("wb") as raw:
        with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as stream:
            for length in range(7):
                for symbols in itertools.product(ALPHABET, repeat=length):
                    trace = list(symbols)
                    expected = expected_flags(trace)
                    actual = run(trace, args.implementation)
                    ok = actual == expected
                    total += 1
                    passed += int(ok)
                    sample_positions += length
                    row = {"id": f"E{total:04d}", "samples": trace,
                           "expected": expected, "actual": actual, "pass": ok}
                    stream.write((json.dumps(row, separators=(",", ":")) + "\n").encode())
                    if not ok and len(counterexamples) < 4:
                        counterexamples.append(row)
    summary = {"implementation": args.implementation, "unit": "whole independent trace",
               "alphabet_in_enumeration_order": list(ALPHABET),
               "length_min_inclusive": 0, "length_max_inclusive": 6,
               "traces": total, "passed": passed, "failed": total - passed,
               "sample_positions": sample_positions,
               "first_counterexamples": counterexamples,
               "full_observations": "enumeration-observations.jsonl.gz",
               "scope": "All 1093 traces over this alphabet of lengths 0 through 6, each with fresh state. Selected traces overlap and are not additional unique coverage."}
    write_json(args.output / "enumeration-summary.json", summary)
    print(json.dumps({"implementation": args.implementation,
                      "selected": {"traces": len(results), "passed": len(results) - len(failed_selected),
                                   "failed": len(failed_selected), "failed_trace_ids": failed_selected},
                      "enumeration": {"traces": total, "passed": passed, "failed": total - passed},
                      "elapsed_seconds": round(time.perf_counter() - started, 6)}))
    return 1 if failed_selected or total != passed else 0


if __name__ == "__main__":
    raise SystemExit(main())
