from pathlib import Path

import pytest

from lang_main import search

FILE_SEARCH = 'test.txt'


@pytest.fixture(scope='module')
def base_folder(tmp_path_factory) -> Path:
    folder_structure = 'path/to/base/folder/'
    pth = tmp_path_factory.mktemp('search')
    pth = pth / folder_structure
    pth.mkdir(parents=True, exist_ok=True)

    return pth


@pytest.fixture(scope='module')
def target_file_pth(base_folder) -> Path:
    # place in folder 'path' of TMP path
    target_folder = base_folder.parents[2]
    target_file = target_folder / FILE_SEARCH
    with open(target_file, 'w') as file:
        file.write('TEST')

    return target_file


def test_search_base_path(base_folder):
    stop_folder = '123'  # should not exist
    found = search.search_base_path(base_folder, stop_folder_name=stop_folder)
    assert found is None
    stop_folder = 'to'
    found = search.search_base_path(base_folder, stop_folder_name=stop_folder)
    assert found is not None
    assert found.name == 'path'


@pytest.mark.parametrize('stop_folder_name', ['to', 'base', None])
def test_search_iterative(base_folder, target_file_pth, stop_folder_name):
    # target in parent of 'to': 'path'
    ret = search.search_iterative(base_folder, FILE_SEARCH, stop_folder_name)
    if stop_folder_name == 'to' or stop_folder_name is None:
        assert ret is not None
        assert ret.name == FILE_SEARCH
        assert ret == target_file_pth
    elif stop_folder_name == 'base':
        assert ret is None


def test_search_cwd(monkeypatch, base_folder, target_file_pth):
    monkeypatch.setattr(Path, 'cwd', lambda: base_folder)
    assert Path.cwd() == base_folder
    ret = search.search_cwd(FILE_SEARCH)
    assert ret is None

    target_folder = target_file_pth.parent
    monkeypatch.setattr(Path, 'cwd', lambda: target_folder)
    assert Path.cwd() == target_folder
    ret = search.search_cwd(FILE_SEARCH)
    assert ret is not None
    assert ret == target_file_pth
