import asyncio
import time
from pathlib import Path

from clarabot_nano.utility.path.validate import normalize_absolute_path
from clarabot_nano.utility.serialize import msgpack_dumps
from clarabot_nano_tests.testing.file import temp_path
from clarabot_nano_tests.testing.gateway import start_nano_debug


async def run_nano_control_tester(
    tmpdir,
    testing_server_manager,
    user_app_dirs,
    nano_root_dir,
    tester_module_path,
    tester_input_args,
    core_args=(),
    timeout=20.0,
):
    d = Path(normalize_absolute_path(temp_path(tmpdir)))
    d.mkdir()
    (d / "init_args").write_bytes(msgpack_dumps(tester_input_args))
    async with start_nano_debug(
        testing_server_manager,
        user_app_dirs,
        nano_root_dir,
        core_args=[
            f"--control_args={arg}"
            for arg in ["--tester_module_path", tester_module_path, "--tester_communication_dir", str(d)]
        ]
        + list(core_args),
    ) as pm:
        finished_log = d / "test_log.done"
        t = time.perf_counter() + timeout
        while not finished_log.is_file():
            if time.perf_counter() > t:
                wip_log = d / "test_log"
                if wip_log.is_file():
                    wip_log = wip_log.read_text()
                assert False, f"control tester timeout; wip log:\n{wip_log}"
            await asyncio.sleep(0.1)
        await asyncio.sleep(0.5)
        return finished_log.read_text().split("\n")
