def finish_key(interval: tuple[int, int]) -> tuple[int, int]:
    """Return finish and start coordinates for deterministic sorting.

    Args:
        interval: Start and finish coordinates of a request.

    Returns:
        The finish coordinate followed by the start coordinate.
    """
    start, finish = interval
    return finish, start


def select_requests(
    intervals: list[tuple[int, int]],
) -> list[tuple[int, int]]:
    """Select a maximum number of compatible positive-duration requests.

    Args:
        intervals: Half-open integer intervals with start below finish.

    Returns:
        Selected intervals in execution order, without changing the input.

    Raises:
        ValueError: If a request has zero or negative duration.
    """
    for start, finish in intervals:
        if start >= finish:
            raise ValueError("each request must start before it finishes")
    selected: list[tuple[int, int]] = []
    last_finish: int | None = None
    for start, finish in sorted(intervals, key=finish_key):
        if last_finish is None or start >= last_finish:
            selected.append((start, finish))
            last_finish = finish
    return selected


requests = [(5, 8), (0, 9), (1, 3), (3, 5), (6, 7), (7, 10)]
last_finish = None
print("request | previous finish | decision")
for request in sorted(requests, key=finish_key):
    start, finish = request
    accept = last_finish is None or start >= last_finish
    print(request, last_finish, "accept" if accept else "reject", sep=" | ")
    if accept:
        last_finish = finish
print("Selected requests:", select_requests(requests))
print("Original requests:", requests)

counterexample = [(0, 9), (1, 3), (3, 5), (5, 7)]
start_first: list[tuple[int, int]] = []
for start, finish in sorted(counterexample):
    if not start_first or start >= start_first[-1][1]:
        start_first.append((start, finish))
finish_first = select_requests(counterexample)
print("Earliest-start selection:", start_first)
print("Earliest-finish selection:", finish_first)
print("Selected counts:", len(start_first), len(finish_first))
assert len(start_first) < len(finish_first)

weighted_requests = [(0, 2, 1), (2, 4, 1), (0, 4, 5)]
intervals = [(start, finish) for start, finish, reward in weighted_requests]
rewards = {
    (start, finish): reward for start, finish, reward in weighted_requests
}
count_selection = select_requests(intervals)
count_reward = sum(rewards[request] for request in count_selection)
long_request_reward = rewards[(0, 4)]
print("Count-optimal selection:", count_selection)
print("Its total reward:", count_reward)
print("Reward from the long request:", long_request_reward)
assert count_reward < long_request_reward

assert select_requests([]) == []
assert select_requests([(2, 4)]) == [(2, 4)]
assert select_requests([(1, 3), (1, 3)]) == [(1, 3)]
assert select_requests([(0, 2), (2, 4)]) == [(0, 2), (2, 4)]
assert select_requests([(-5, -2), (-2, 0)]) == [(-5, -2), (-2, 0)]
assert select_requests([(0, 8), (2, 3), (4, 5)]) == [(2, 3), (4, 5)]
for invalid in ([(2, 2)], [(4, 1)]):
    try:
        select_requests(invalid)
    except ValueError as error:
        print(type(error).__name__, str(error))
    else:
        raise AssertionError("an invalid interval was accepted")
print("Empty, duplicate, touching, negative, and contained cases passed.")
