import copy

import pytest
from clarabot_nano_common.utility.path.common import normalize_absolute_path

from clarabot_nano.indexer.config import IndexerConfig
from clarabot_nano.indexer.idxstatedb import IndexingStateDatabase
from clarabot_nano_tests.indexer.scheduler.utility import SchedulerTesterBase
from clarabot_nano_tests.testing.core.instance import CoreTestingNanoInstanceHandler
from clarabot_nano_tests.testing.file import temp_path
from clarabot_nano_tests.testing.solr import wait_solr_startup


@pytest.fixture
async def indexer_scheduler_args(tmpdir, reset_user_app_dirs, dev_nano_root_dir):
    async with CoreTestingNanoInstanceHandler(reset_user_app_dirs, dev_nano_root_dir).run() as (
        pm,
        session,
        children_spawns,
        dbg_config,
    ):
        ec_ = IndexerConfig(dbg_config)
        await wait_solr_startup(session, ec_.solr_port, ec_.solr_auth_header)

        async with IndexingStateDatabase.create(
            normalize_absolute_path(temp_path(tmpdir)), sqlite_timeout=10.0
        ) as index_state_db:
            yield session, copy.deepcopy(dbg_config), index_state_db


@pytest.fixture
async def indexer_scheduler_tester(indexer_scheduler_args):
    indexer_scheduler_args[1]["remote"]["indexed_languages"] = "all"  # init solr with all languages
    indexer_scheduler_args[1]["remote"]["indexer_sync_interval"] = 0.0001  # less than a second wait between cycles
    st = SchedulerTesterBase(*indexer_scheduler_args)
    await st.init_solr_core()
    return st
