# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Verify portable fixtures and reject representative broken ports."""

import sys
from math import nextafter
from pathlib import Path
from types import SimpleNamespace

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


def verify(mutants):
    stored = check_port.load_cases()
    generated = make_cases.generate()
    assert {key: value for key, value in stored.items() if key != "cases"} == {
        key: value for key, value in generated.items() if key != "cases"
    }
    for saved, actual in zip(stored["cases"], generated["cases"], strict=True):
        assert {key: value for key, value in saved.items() if key != "expected"} == {
            key: value for key, value in actual.items() if key != "expected"
        }
        assert check_port.agrees(actual["expected"], saved["expected"], saved["tol"]), saved["name"]
    assert check_port.run_checks(hanawalt, out=lambda *_: None) == 0
    print(f"PASS {len(stored['cases'])} portable cases regenerate and accept the reference")

    by_name = {case["name"]: case for case in stored["cases"]}
    operations = {case["operation"] for case in stored["cases"]}
    reference = {operation: getattr(hanawalt, operation) for operation in operations}
    for case_name, change, broken in mutants:
        case = by_name[case_name]
        result = broken(*case["args"])
        assert not check_port.agrees(result, case["expected"], case["tol"]), change
        adapter = SimpleNamespace(**(reference | {case["operation"]: broken}))
        lines = []
        assert check_port.run_checks(adapter, out=lines.append) > 0
        assert f"FAIL {case_name}" in lines, change
        print(f"PASS rejects {change}")


def ignore_observed_prime(observed, references, tolerance):
    candidates = []
    for name, peaks in references.items():
        strongest_reference = max(peaks, key=lambda line: (line[1], line[0]))
        for d, _ in observed:
            if abs(d - strongest_reference[0]) <= tolerance:
                altered = [[x, i if x != d else 2 * max(p[1] for p in observed)] for x, i in observed]
                candidates.extend(hanawalt.search_match(altered, {name: peaks}, tolerance))
                break
    return candidates


def search_with_match(matcher, observed, references, tolerance):
    original_match = hanawalt._match
    try:
        hanawalt._match = matcher
        return hanawalt.search_match(observed, references, tolerance)
    finally:
        hanawalt._match = original_match


def allow_reused_peaks(observed, references, tolerance):
    original_match = hanawalt._match

    def reuse(measured, reference, width):
        return [pair for line in reference for pair in original_match(measured, [line], width)]

    return search_with_match(reuse, observed, references, tolerance)


def reuse_confirmed_anchors(observed, references, tolerance):
    original_match = hanawalt._match
    available = [tuple(peak) for peak in observed]
    candidates = []
    for name, peaks in references.items():
        calls = 0

        def reuse_on_confirmation(measured, reference, width):
            nonlocal calls
            calls += 1
            return original_match(measured if calls == 1 else available, reference, width)

        candidates.extend(search_with_match(reuse_on_confirmation, observed, {name: peaks}, tolerance))
    return sorted(candidates, key=lambda candidate: (-candidate["score"], candidate["phase"]))


def strict_tolerance(observed, references, tolerance):
    return hanawalt.search_match(observed, references, nextafter(tolerance, 0.0))


def choose_nearest_peak(observed, references, tolerance):
    def nearest(measured, reference, width):
        unused = list(measured)
        pairs = []
        for expected in sorted(reference):
            eligible = [peak for peak in unused if abs(peak[0] - expected[0]) <= width]
            if eligible:
                best = min(eligible, key=lambda peak: abs(peak[0] - expected[0]))
                unused.remove(best)
                pairs.append((best, expected))
        return pairs

    return search_with_match(nearest, observed, references, tolerance)


def omit_observed_coverage(observed, references, tolerance):
    candidates = hanawalt.search_match(observed, references, tolerance)
    return [dict(candidate, score=candidate["reference_coverage"]) for candidate in candidates]


verify([
    ("observed prime gates the phase", "reversed lookup direction", ignore_observed_prime),
    ("close anchors cannot reuse the same measured peak", "reuse of one measured peak", allow_reused_peaks),
    ("confirmation cannot reuse the prime", "reusing anchors during confirmation", reuse_confirmed_anchors),
    ("the spacing tolerance includes exact binary boundaries", "strict spacing tolerance", strict_tolerance),
    ("both measured and reference intensities matter", "reference-only score", omit_observed_coverage),
    ("confirmation uses the first eligible line in spacing order", "nearest instead of first eligible line", choose_nearest_peak),
    ("gain-independent ordering and phase-id tie break", "reversed tie order",
     lambda *args: list(reversed(hanawalt.search_match(*args)))),
])
