#!/usr/bin/env python3
"""Real Hypothesis implementation tests, observable counts, and explicit replay."""
import argparse
from collections import Counter
import gzip
import json
from pathlib import Path
import time

import hypothesis
from hypothesis import given, Phase, seed, settings, strategies as st, Verbosity
from sorting import drop_duplicates, empty_output, stable_sort, unstable_sort

SEED = 20261028
MAX_EXAMPLES = 200
IMPLEMENTATIONS = {"baseline": drop_duplicates, "corrected": stable_sort,
                   "empty": empty_output, "unstable": unstable_sort}
FULL_GATE = ("ordered", "multiplicity", "stable_equal_keys", "input_unchanged",
             "repeat_deterministic", "idempotent")
WEAK_GATE = ("ordered", "input_unchanged", "repeat_deterministic", "idempotent")
RECORDS = st.lists(st.tuples(st.integers(-2, 2), st.sampled_from(("a", "b", "c"))),
                   min_size=0, max_size=8, unique=False).map(tuple)


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


def freeze(records):
    return tuple(tuple(r) for r in records)


def evaluate(records, implementation, sequence, label):
    snapshot = tuple(tuple(r) for r in records)
    function = IMPLEMENTATIONS[implementation]
    calls = []

    def call(value, purpose):
        result = function(value)
        calls.append({"purpose": purpose, "input": value, "output": result})
        return result

    output = call(records, "primary")
    repeated = call(records, "repeat_same_input")
    sorted_again = call(output, "idempotence_on_primary_output")
    preserved = Counter(output) == Counter(records)
    stable = (all(tuple(r for r in output if r[0] == key)
                  == tuple(r for r in records if r[0] == key)
                  for key in range(-2, 3)) if preserved else None)
    checks = {
        "ordered": all(a[0] <= b[0] for a, b in zip(output, output[1:])),
        "multiplicity": preserved, "stable_equal_keys": stable,
        "input_unchanged": records == snapshot,
        "repeat_deterministic": output == repeated,
        "idempotent": sorted_again == output,
        "set_preserved_diagnostic_only": set(output) == set(records)}
    return {"sequence": sequence, "label": label, "implementation": implementation,
            "input": records, "output": output,
            "expected_output": tuple(sorted(records, key=lambda r: r[0])),
            "checks": checks,
            "full_gate_pass": all(checks[x] is True for x in FULL_GATE),
            "weak_gate_pass": all(checks[x] is True for x in WEAK_GATE),
            "implementation_calls": calls}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--job", required=True, choices=("weak-baseline", "weak-empty",
                        "search-baseline", "search-unstable", "corrected-campaign", "regression-replay"))
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--capture-root", type=Path)
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=False)
    started = time.perf_counter()
    evaluations = []
    failure = None
    counterexample = None
    regression = []
    search = args.job.startswith("search-")
    config = {"hypothesis": hypothesis.__version__, "max_examples": MAX_EXAMPLES,
              "seed": SEED, "database": None, "deadline": None,
              "phases": ["generate", "shrink"] if search else ["generate"],
              "verbosity": "debug" if search else "normal", "derandomize": False,
              "report_multiple_bugs": False, "print_blob": True,
              "strategy": "lists(tuples(integers(-2,2),sampled_from(('a','b','c'))),min_size=0,max_size=8,unique=False).map(tuple)",
              "filter_or_assume": False}
    if args.job == "regression-replay":
        if args.capture_root is None:
            parser.error("regression replay requires --capture-root")
        rows = json.loads(Path(__file__).with_name("selected-records.json").read_text())
        for previous in ("search-baseline", "search-unstable"):
            found = json.loads((args.capture_root / previous / "counterexample.json").read_text())
            rows.append({"id": previous + "-replay", "purpose": "explicit replay of retained generated/shrunk input",
                         "records": found["final_counterexample"]["input"]})
        for row in rows:
            for implementation in IMPLEMENTATIONS:
                result = evaluate(freeze(row["records"]), implementation,
                                  len(evaluations) + 1, row["id"])
                evaluations.append(result)
                if row["id"].endswith("-replay"):
                    regression.append(result)
        write_json(args.output / "counterexample-regression.json", {
            "scope": "Two explicit retained inputs replayed against four implementations; not a new generated campaign.",
            "observations": regression})
        expected_contrast = (all(r["full_gate_pass"] for r in evaluations if r["implementation"] == "corrected")
            and any(not r["full_gate_pass"] for r in evaluations if r["implementation"] == "baseline")
            and any(not r["full_gate_pass"] for r in evaluations if r["implementation"] == "empty")
            and any(not r["full_gate_pass"] for r in evaluations if r["implementation"] == "unstable"))
        child_exit = 0 if expected_contrast else 2
        config = {"hypothesis": hypothesis.__version__, "mode": "explicit replay only", "selected_cases": 8,
                  "retained_generated_inputs": 2, "implementations_per_input": 4}
    else:
        implementation = ("baseline" if "baseline" in args.job else
                          "empty" if "empty" in args.job else
                          "unstable" if "unstable" in args.job else "corrected")
        target = "multiplicity" if args.job == "search-baseline" else "stable_equal_keys"
        config["asserted_gate"] = target if search else list(WEAK_GATE if args.job.startswith("weak-") else FULL_GATE)

        @seed(SEED)
        @settings(max_examples=MAX_EXAMPLES, database=None, deadline=None,
                  phases=(Phase.generate, Phase.shrink) if search else (Phase.generate,),
                  verbosity=Verbosity.debug if search else Verbosity.normal,
                  derandomize=False, report_multiple_bugs=False, print_blob=True)
        @given(records=RECORDS)
        def check(records):
            result = evaluate(records, implementation, len(evaluations) + 1, args.job)
            evaluations.append(result)
            if search:
                assert result["checks"][target] is True, f"required {target} violated"
            else:
                gate = "weak_gate_pass" if args.job.startswith("weak-") else "full_gate_pass"
                assert result[gate], f"required {gate} violated"

        try:
            check()
        except AssertionError as error:
            failure = {"exception": type(error).__name__, "message": str(error),
                       "hypothesis_notes": list(getattr(error, "__notes__", []))}
        if search:
            failed = [x for x in evaluations if x["checks"][target] is False]
            if failure is not None and failed and evaluations[-1]["checks"][target] is False:
                first, final = failed[0], evaluations[-1]
                counterexample = {"target_property": target, "first_observed_failure": first,
                                  "final_counterexample": final,
                                  "first_and_final_inputs_differ": first["input"] != final["input"],
                                  "first_input_length": len(first["input"]),
                                  "final_input_length": len(final["input"]),
                                  "claim": "Hypothesis returned this shrunk failing input under the recorded strategy, version and settings; no global-minimum claim.",
                                  "failure": failure}
                write_json(args.output / "counterexample.json", counterexample)
                child_exit = 1
            else:
                child_exit = 2
        else:
            child_exit = 1 if failure is not None else 0
    with (args.output / "evaluations.jsonl.gz").open("wb") as raw:
        with gzip.GzipFile(filename="", fileobj=raw, mode="wb", mtime=0) as stream:
            for row in evaluations:
                stream.write((json.dumps(row, separators=(",", ":")) + "\n").encode())
    counts = {}
    for row in evaluations:
        for name, verdict in row["checks"].items():
            counts.setdefault(name, {"pass": 0, "fail": 0, "not_assessed": 0})
            counts[name]["not_assessed" if verdict is None else "pass" if verdict else "fail"] += 1
    summary = {"job": args.job, "configuration": config,
               "harness_evaluations": len(evaluations),
               "distinct_primary_inputs": len({json.dumps(x["input"]) for x in evaluations}),
               "implementation_calls": sum(len(x["implementation_calls"]) for x in evaluations),
               "property_verdict_counts": counts,
               "property_boolean_evaluations": sum(v["pass"] + v["fail"] for v in counts.values()),
               "property_not_assessed": sum(v["not_assessed"] for v in counts.values()),
               "full_gate_pass_evaluations": sum(x["full_gate_pass"] for x in evaluations),
               "weak_gate_pass_evaluations": sum(x["weak_gate_pass"] for x in evaluations),
               "by_implementation": {name: {
                   "harness_evaluations": sum(x["implementation"] == name for x in evaluations),
                   "full_gate_pass_evaluations": sum(x["implementation"] == name and x["full_gate_pass"] for x in evaluations)}
                   for name in IMPLEMENTATIONS if any(x["implementation"] == name for x in evaluations)},
               "failure": failure, "child_exit_code": child_exit,
               "elapsed_seconds": round(time.perf_counter() - started, 6),
               "counting_scope": "Harness body evaluations, including generation/shrinking/repetition where enabled, are counted from observed entries. Each evaluation calls the selected implementation three times. Distinct primary inputs are counted per job; repeated inputs and jobs overlap. No phase-specific internal draw count is inferred."}
    write_json(args.output / "summary.json", summary)
    print(json.dumps({k: summary[k] for k in ("job", "harness_evaluations", "distinct_primary_inputs", "implementation_calls", "child_exit_code")}))
    return child_exit


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