# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check a two-pass source example and mathematical properties of lookup."""

from math import isclose
import sys
from pathlib import Path

root = Path(__file__).parents[1]
sys.path.insert(0, str(root / "reference"))
sys.path.insert(0, str(root / "examples"))
from hanawalt import search_match
from strong_lines import after_yttria, observed, references

# Hanawalt (1986), Fig. 2: the yttria pass leaves residual intensity at 2.259 Å.
first = search_match(observed, references, 0.01)
assert [c["phase"] for c in first] == ["Y2O3"]
assert first[0]["matched"] == 5
remaining = after_yttria()
second = search_match(remaining, references, 0.01)
assert [c["phase"] for c in second] == ["As2O3"]
assert second[0]["matched"] == 5
deleted_shared = [peak for peak in remaining if peak[0] != 2.259]
assert search_match(deleted_shared, references, 0.01)[0]["matched"] == 4

rescaled = search_match([[d, i * 7] for d, i in observed], references, 0.01)
assert isclose(first[0]["score"], rescaled[0]["score"], rel_tol=0, abs_tol=1e-12)
assert 0 < first[0]["observed_coverage"] < 1

# The single observed line at 3.02 Å is in range of both reference anchors.
assert not search_match([[4, 100], [3.02, 40], [1, 10]],
                        {"overlap": [[4, 100], [3, 60], [3.04, 70]]}, 0.025)

print("PASS Hanawalt Fig. 2 reduced two-pass lookup, gain invariance and distinct peak assignment")
