import json
import os
import tempfile
from unittest.mock import patch

import pytest
from fastapi.testclient import TestClient

from mapping_provider import create_app
from mapping_provider.backends import brian, cache, correlator, inventory

from .common import load_test_data


@pytest.fixture
def dummy_config():
    return {
        'sentry': {
            'dsn': 'https://token@hostname.geant.org:1111/a/b',
            'environment': 'unit tests'
        },
        'inventory': 'https://inventory.bogus.domain',
        'reporting': 'http://reporting.another-bogus.domain',
        # no rmq param to skip correlator thread
        # 'rmq': {
        #     'brokers': [
        #         'test-noc-alarms01.geant.org',
        #         'test-noc-alarms02.geant.org',
        #         'test-noc-alarms03.geant.org'
        #     ],
        #     'username': 'guest',
        #     'password': 'guest',
        #     'vhost': '/'
        # },
        'brian': {
            'hostname': 'bogus hostname',
            'username': 'bogus username',
            'password': 'bogus password',
            'database': 'bogus database name',
            'measurement': 'bogus measurement'
        }
    }


@pytest.fixture
def dummy_config_filename(dummy_config):
    with tempfile.NamedTemporaryFile(delete=False) as f:
        f.write(json.dumps(dummy_config).encode('utf-8'))
        f.flush()
        yield f.name


@pytest.fixture
def client(dummy_config_filename):
    os.environ['SETTINGS_FILENAME'] = dummy_config_filename

    with tempfile.TemporaryDirectory() as tmp_dir:

        # there's no rmq in the test config data, so cache won't be initialized
        cache.init(tmp_dir)
        cache.set(inventory.REPORTING_SCID_CURRENT_CACHE_FILENAME, load_test_data('scid-current.json'))
        cache.set(inventory.INPROV_EQUIPMENT_CACHE_FILENAME, load_test_data('inprov-equipment.json'))
        cache.set(correlator.CACHED_CORRELATOR_STATE_FILENAME, load_test_data('correlator-state.json'))
        cache.set(brian.CACHED_BRIAN_SCID_RATES_FILENAME, load_test_data('brian-scid-rates.json'))
 
        with patch('sentry_sdk.init') as _mock_sentry_init:
            yield TestClient(create_app())


@pytest.fixture(autouse=True)
def run_around_tests():
    assert cache._cache_dir is None  # test env sanity check
    yield

    # make sure cache is set to unused before the next test
    cache._cache_dir = None