import asyncio
import os
import sys
from pathlib import Path

import pytest

from clarabot_nano_tests.testing.file import temp_path, change_yaml
from clarabot_nano_tests.testing.gateway import start_nano_wait_ready
from clarabot_nano_tests.testing.server.manager import DevServerManager


@pytest.mark.asyncio
async def test_core_hooks(
    tmpdir,
    reset_user_app_dirs,
    dev_nano_root_dir,
    testing_server_manager: DevServerManager,
):
    session = await testing_server_manager.session()

    async with start_nano_wait_ready(testing_server_manager, reset_user_app_dirs, dev_nano_root_dir):
        pass  # create new instance config

    reset_feedback_path = Path(str(temp_path(tmpdir)))
    reset_feedback_value = os.urandom(8)

    with change_yaml(Path(reset_user_app_dirs[0]) / "local.yml") as config:
        config["hook_reset"] = [
            sys.executable,
            "-c",
            f"from pathlib import Path;Path({reset_feedback_path.as_posix()!r}).write_bytes({reset_feedback_value!r})",
        ]

    async with start_nano_wait_ready(testing_server_manager, reset_user_app_dirs, dev_nano_root_dir) as (
        pm,
        debug_info,
    ):
        # check reset hook
        assert not reset_feedback_path.exists()
        result = await pm.assert_core_do_config_reset(session, debug_info["port"])
        assert result is True, str(result)
        for _ in range(5):
            if reset_feedback_path.is_file():
                assert reset_feedback_path.read_bytes() == reset_feedback_value
                break
            await asyncio.sleep(0.1)
        else:
            assert False, "feedback hook not found"
