import json
import subprocess
import sys
from pathlib import Path

from clarabot_nano_tests.testing.file import temp_path
from clarabot_nano_tests.testing.process import pypopen


def test_indexer_observer(tmpdir):
    root = Path(temp_path(tmpdir))
    root.mkdir(parents=True)
    with pypopen(
        ["clarabot_nano_tests.indexer.observer.measure", str(root), str(20), str(0.1)],
        out=subprocess.PIPE,
        err=subprocess.STDOUT,
    ) as p:
        o, _ = p.communicate()
        print(o.decode())
        assert p.wait(1) == 0
    result = json.loads((root / "_result.json").read_bytes())
    assert set(result.keys()) == {"first_delay", "unexpected", "delays", "missed", "duplicate"}
    assert result["first_delay"] and result["first_delay"] < 1.0, str(result)
    if sys.platform.startswith("win"):
        assert result["duplicate"] <= 10, str(result)
    else:
        assert result["duplicate"] == 0, str(result)
    assert result["unexpected"] == 0, str(result)
    assert len(result["delays"]) > 0, str(result)
    assert max(result["delays"]) < 0.2, str(result)
    assert sum(result["delays"]) / len(result["delays"]) < 0.1, str(result)
    assert len(result["missed"]) == 0, str(result)
