import asyncio
import json
import os
import tempfile

import pytest

from clarabot_nano.utility import parse_environment_flag
from clarabot_nano_tests.testing.core.instance import RequestTestingNanoInstanceHandler


@pytest.mark.skipif(not parse_environment_flag("CBNANO_RUN_DBG_INSTANCE"), reason="not running for debug")
@pytest.mark.asyncio
async def test_run_debug(reset_user_app_dirs, dev_nano_root_dir, testing_server_manager, testing_client_manager):
    """
    Run the whole nano instance for debugging and development of depending components.
    """
    config = os.environ.get("CLARABOT_TESTING_NANO_CONFIG_PATH")
    if not config:
        config = os.path.join(tempfile.gettempdir(), "__clarabot_running_debug_nano_config.json")
    print("Bootstrapping new Nano instance...")
    # try to load config of nano
    with open(config, "r") as f:
        config = json.load(f)
    async with RequestTestingNanoInstanceHandler(
        reset_user_app_dirs,
        dev_nano_root_dir,
        testing_server_manager,
        config["user"],
        testing_client_manager,
        config["drives"],
        config.get("clear_slots", True),
    ).run() as (pm, debug_info, gateway_port, gateway_key, session_id, remote_yaml, nano_id, u0wsc):
        print("Nano ready!")
        try:
            while True:
                await asyncio.sleep(5)
        finally:
            print("Cleaning up...")
