# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Generate portable cases from fixed inputs and the reference."""

import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parents[1] / "reference"))
import hanawalt


def generate():
    clean = [[4, 100], [3, 60], [2, 40], [1, 20]]
    cases = [
        ("observed prime gates the phase",
         [clean, {"correct": clean, "secondary": [[3, 100], [2, 60], [1, 40]]}, 0.01]),
        ("close anchors cannot reuse the same measured peak",
         [[[4, 100], [3.02, 40], [1, 10]], {"duplicate-hit": [[4, 100], [3, 70], [3.04, 50]]}, 0.025]),
        ("confirmation cannot reuse the prime",
         [clean, {"overlap": [[4, 100], [3, 60], [2, 40], [4.03125, 20]]}, 0.0625]),
        ("the spacing tolerance includes exact binary boundaries",
         [clean, {"boundary": [[4.125, 100], [2.875, 60], [2.125, 40], [0.875, 20]]}, 0.125]),
        ("both measured and reference intensities matter",
         [[[4, 100], [3, 70], [3.4, 60], [2, 50], [1, 10]],
          {"closer": [[4.001, 100], [3, 70], [2, 50], [1, 10]], "partial": [[4, 100], [3, 70], [2, 50], [1.2, 40]]}, 0.01]),
        ("confirmation uses the first eligible line in spacing order",
         [[[4, 100], [3, 70], [2, 60], [1, 8], [1.03, 24]],
          {"candidate": [[4, 100], [3, 70], [2, 60], [1.025, 20]]}, 0.03]),
        ("gain-independent ordering and phase-id tie break",
         [clean, {"z": clean, "a": [[d, i * 10] for d, i in clean]}, 0.01]),
        ("equal intensity uses the larger prime spacing",
         [[[3, 100], [4, 100], [2, 20]], {"prime-four": [[4, 100], [3, 25], [2, 20]]}, 0.01]),
        ("no candidates with only two measured lines",
         [[[4, 100], [3, 60]], {"candidate": clean}, 0.01]),
    ]
    return {
        "format": 1,
        "method": "hanawalt-xrd-search-match",
        "version": "0.1.0",
        "interface": (
            "search_match(observed, references, tolerance) -> ranked list of records with phase, score, "
            "observed_coverage, reference_coverage, and matched. A list of peaks contains [d in angstroms, "
            "positive intensity] pairs. references maps phase identifiers to peak lists. The position "
            "tolerance is absolute and in angstroms. Count each measured and reference line at most "
            "once. Compare the returned order and labels exactly and floats within tol."
        ),
        "cases": [
            {"name": name, "operation": "search_match", "args": args,
             "expected": hanawalt.search_match(*args), "tol": 1e-12}
            for name, args in cases
        ],
    }


if __name__ == "__main__":
    print(json.dumps(generate(), indent=2))
