#!/usr/bin/env python3
"""A deterministic teaching example, not an AI or RSI benchmark.

Python 3.9+, standard library only. Run: python3 search-plateau.py > report.json
No network, models, randomness, or subprocesses. Writes JSON to stdout only.
The deliberately constructed six-bit objective rewards two different peaks.
"""

import hashlib
import itertools
import json
import platform
from pathlib import Path


def score(bits):
    ones = bits.count("1")
    return 6 if ones == 6 else 5 - ones


def search(start, budget):
    """Evaluate complete neighborhoods; first left-to-right maximum wins ties."""
    if len(start) != 6 or set(start) - {"0", "1"} or budget < 1:
        raise ValueError("Expected six binary digits and a positive budget")
    current = start
    value = score(current)
    evaluations = 1
    accepted = [{"bits": current, "score": value}]
    rounds = []
    reason = "insufficient_budget_for_full_neighborhood"
    while evaluations + 6 <= budget:
        neighbors = []
        for index in range(6):
            candidate = current[:index] + ("1" if current[index] == "0" else "0") + current[index + 1:]
            neighbors.append({"bits": candidate, "score": score(candidate)})
        evaluations += 6  # Count every call, including revisits; no score cache.
        best = max(neighbors, key=lambda item: item["score"])
        improved = best["score"] > value
        rounds.append({"parent": current, "candidates": neighbors, "accepted": best["bits"] if improved else None})
        if not improved:
            reason = "no_strictly_better_one_bit_neighbor"
            break
        current, value = best["bits"], best["score"]
        accepted.append(dict(best))
    return {"start": start, "evaluation_budget": budget, "evaluations_used": evaluations,
            "final_bits": current, "final_score": value, "stop_reason": reason,
            "accepted_path": accepted, "rounds": rounds}


def main():
    runs = [search("110000", 25), search("110000", 49), search("111110", 25)]
    # Separate exhaustive diagnostic; these 64 calls are NOT in any search budget.
    landscape = [{"bits": "".join(bits), "score": score("".join(bits))}
                 for bits in itertools.product("01", repeat=6)]
    assert [run["final_score"] for run in runs] == [5, 5, 6]
    assert [run["evaluations_used"] for run in runs] == [19, 19, 13]
    report = {
        "purpose": "Constructed local-search counterexample, not measured AI capability or an OpenEvolve reproduction",
        "python": platform.python_version(),
        "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        "objective": "6 if all six bits are 1; otherwise 5 minus the number of 1 bits; maximize",
        "policy": "Try every one-bit flip left to right; accept the first highest score only if strictly better; stop on a full non-improving neighborhood or insufficient budget",
        "inputs": {"starts": ["110000", "110000", "111110"], "budgets": [25, 49, 25], "selection": "hand-chosen explanatory cases"},
        "runs": runs,
        "exhaustive_diagnostic": {"evaluations": 64, "best": max(landscape, key=lambda item: item["score"]), "landscape": landscape},
    }
    report["inputs_sha256"] = hashlib.sha256(json.dumps(report["inputs"], sort_keys=True).encode()).hexdigest()
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()
