"""Test that concurrent experience pool writes don't corrupt the file."""
import json
import threading
import pytest
from pathlib import Path


def test_concurrent_writes_dont_corrupt(tmp_path):
    """Many threads logging to the same pool — every line must be valid JSON.

    Writes 1000 entries (10 threads × 100 writes) to EXERCISE the old
    cap-at-500 truncation path, which corrupted interleaved JSONL writes
    on the old code. After Task 10 removes the truncation and adds fcntl
    locking, all 1000 writes must be valid JSON."""
    from recoil.core.critic import CriticLoop, CriticResult, Outcome

    pool_dir = tmp_path / "exp"

    class _NoOpCritic(CriticLoop):
        def evaluate(self, art, ctx):
            return []

    def worker(i):
        critic = _NoOpCritic(name=f"crit_{i}", experience_pool_dir=pool_dir, shot_id=f"SH_{i}")
        for _ in range(100):
            critic._log_experience(CriticResult(critic_name=f"crit_{i}", outcome=Outcome.PASS))

    threads = [threading.Thread(target=worker, args=(i,)) for i in range(10)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()

    pool_file = pool_dir / "experience_pool.jsonl"
    assert pool_file.exists()
    lines = pool_file.read_text().strip().splitlines()
    # 10 threads × 100 writes = 1000 lines, all valid JSON (no truncation, no corruption)
    assert len(lines) == 1000, f"Expected 1000 lines, got {len(lines)}"
    for line in lines:
        json.loads(line)  # raises if any line is corrupted
