"""A small, deterministic model of causal versions in offline note edits.

This is an educational model, not an implementation of Riak or a sync service.
"""

from dataclasses import dataclass
from typing import Dict


Clock = Dict[str, int]


@dataclass(frozen=True)
class Version:
    clock: Clock
    text: str | None  # None is a deletion marker, not an absent version.


def keep_maximal(versions: list[Version]) -> list[Version]:
    """Keep every branch that is not an ancestor of another branch."""
    return [candidate for candidate in versions if not any(
        candidate is not other
        and relation(candidate.clock, other.clock) == "before"
        for other in versions
    )]


def apply_once(base: Version, actor: str, operation_id: str,
               seen: dict[str, tuple[Clock, str | None, Version]],
               text: str | None) -> Version:
    """An operation ID makes a repeated delivery return its first result."""
    if operation_id in seen:
        original_clock, original_text, result = seen[operation_id]
        if original_clock != base.clock or original_text != text:
            raise ValueError("same operation ID with different input")
        return result
    result = Version(tick(base.clock, actor), text)
    seen[operation_id] = (dict(base.clock), text, result)
    return result


def tick(clock: Clock, actor: str) -> Clock:
    next_clock = dict(clock)
    next_clock[actor] = next_clock.get(actor, 0) + 1
    return next_clock


def merge(left: Clock, right: Clock) -> Clock:
    return {actor: max(left.get(actor, 0), right.get(actor, 0))
            for actor in sorted(left.keys() | right.keys())}


def relation(left: Clock, right: Clock) -> str:
    actors = left.keys() | right.keys()
    left_le_right = all(left.get(a, 0) <= right.get(a, 0) for a in actors)
    right_le_left = all(right.get(a, 0) <= left.get(a, 0) for a in actors)
    if left_le_right and right_le_left:
        return "same"
    if left_le_right:
        return "before"
    if right_le_left:
        return "after"
    return "concurrent"


def main() -> None:
    base = {"phone": 1}
    phone_edit = tick(base, "phone")
    laptop_edit = tick(base, "laptop")
    print("phone:", phone_edit)
    print("laptop:", laptop_edit)
    print("offline edits:", relation(phone_edit, laptop_edit))
    assert relation(phone_edit, laptop_edit) == "concurrent"

    reconciled = tick(merge(phone_edit, laptop_edit), "phone")
    print("reconciled:", reconciled)
    print("phone -> reconciled:", relation(phone_edit, reconciled))
    print("laptop -> reconciled:", relation(laptop_edit, reconciled))
    assert relation(phone_edit, reconciled) == "before"
    assert relation(laptop_edit, reconciled) == "before"

    deleted_on_phone = tick(base, "phone")
    edited_on_laptop = tick(base, "laptop")
    print("delete vs edit:", relation(deleted_on_phone, edited_on_laptop))
    assert relation(deleted_on_phone, edited_on_laptop) == "concurrent"

    # The laptop did read the base, but its write forgot that causal context.
    contextless_edit = tick({}, "laptop")
    print("base vs contextless child:", relation(base, contextless_edit))
    assert relation(base, contextless_edit) == "concurrent"

    # Two independent writers must not reuse one actor ID and counter history.
    first_writer = tick(base, "phone")
    second_writer = tick(base, "phone")
    print("two writers sharing actor ID:", relation(first_writer, second_writer))
    assert relation(first_writer, second_writer) == "same"

    # The delete is a causal descendant of the old value. A surviving old
    # replica cannot restore it while the deletion marker remains available.
    old = Version(base, "old note")
    tombstone = Version(tick(base, "phone"), None)
    with_marker = keep_maximal([old, tombstone])
    after_purge = keep_maximal([old])
    print("old replica with tombstone:", [v.text for v in with_marker])
    print("old replica after premature purge:", [v.text for v in after_purge])
    assert with_marker == [tombstone]
    assert after_purge == [old]

    # A concurrent edit must coexist with the deletion until application
    # policy resolves it; causal metadata alone cannot decide the winner.
    concurrent_edit = Version(tick(base, "laptop"), "new text")
    delete_vs_edit = keep_maximal([tombstone, concurrent_edit])
    print("delete vs concurrent edit:", [v.text for v in delete_vs_edit])
    assert delete_vs_edit == [tombstone, concurrent_edit]

    seen: dict[str, tuple[Clock, str | None, Version]] = {}
    first = apply_once(old, "phone", "edit-42", seen, "new text")
    retried = apply_once(old, "phone", "edit-42", seen, "new text")
    print("retry of one operation:", first.clock, retried.clock)
    assert first is retried and len(seen) == 1
    try:
        apply_once(old, "phone", "edit-42", seen, "different text")
    except ValueError:
        print("same operation ID, different body: rejected")
    else:
        raise AssertionError("a changed retry must be rejected")


if __name__ == "__main__":
    main()
