"""Smallest complete Lace interlace with two memory-backed Python participants."""

from pathlib import Path

from lace import Complete, Lace, PolicyAuthoringSource, Record, bounded_interlace, list_records, store

TAI = "0000000001:000000000"
POLICY_PATH = Path(__file__).resolve().parent.parent / "policy" / "items.interlang"
UNRELATED_POLICY = (
    "converge {\n"
    "  Item in //first-interlace//demo/item//unrelated/{*} => include Item\n"
    "}"
)


def item(name: str, data: bytes) -> Record:
    return Record.create(
        group="first-interlace",
        app="demo/item",
        name=name,
        tai=TAI,
        data=data,
    )


first = item("selected/one", b"first selected record")
second = item("selected/two", b"second selected record")
unrelated = item("unrelated/not-selected", b"this record must stay at the source")

with Lace.memory() as source, Lace.memory() as destination:
    stored = store(source, [first, second, unrelated])
    assert isinstance(stored.terminal, Complete)
    print(f"source stored: {len(stored.records)}")

    policy = PolicyAuthoringSource.interlang(POLICY_PATH.read_text().strip())

    outcome = bounded_interlace(source, destination, policy)
    assert isinstance(outcome.terminal, Complete)
    print("interlace outcome: complete")

    selected = list_records(destination, policy)
    selected_names = sorted(record.name for record in selected.records)
    assert selected_names == ["selected/one", "selected/two"]
    print(f"destination selected: {', '.join(selected_names)}")

    unrelated_policy = PolicyAuthoringSource.interlang(UNRELATED_POLICY)
    unrelated_list = list_records(destination, unrelated_policy)
    assert isinstance(unrelated_list.terminal, Complete)
    assert not unrelated_list.records
    print(f"destination unrelated: {len(unrelated_list.records)}")
