"""Tests for parallel (threaded) execution of reduce_file."""
import threading
import time
from delta_reduce.core import reduce_file


def test_parallel_reaches_same_result_as_sequential():
    """n_threads=4 should produce the same final file as n_threads=1."""
    lines = [f"line{i}\n" for i in range(20)]
    essential = "line19\n"

    def test_fn(candidate: list[str]) -> bool:
        return essential in candidate

    result_seq, _ = reduce_file(list(lines), test_fn, n_threads=1)
    result_par, _ = reduce_file(list(lines), test_fn, n_threads=4)

    assert result_seq == [essential]
    assert result_par == [essential]


def test_parallel_invokes_test_fn_concurrently():
    """Multiple threads must be running test_fn at the same time."""
    lines = [f"line{i}\n" for i in range(20)]
    essential = "line19\n"

    concurrent_count = 0
    peak_concurrent = 0
    lock = threading.Lock()

    def test_fn(candidate: list[str]) -> bool:
        nonlocal concurrent_count, peak_concurrent
        with lock:
            concurrent_count += 1
            if concurrent_count > peak_concurrent:
                peak_concurrent = concurrent_count
        time.sleep(0.01)  # hold long enough to overlap
        with lock:
            concurrent_count -= 1
        return essential in candidate

    reduce_file(list(lines), test_fn, n_threads=4)
    assert peak_concurrent > 1, f"Expected concurrent execution, peak was {peak_concurrent}"
