import os
import shutil
from pathlib import Path
from unittest.mock import patch

import pytest

from dopt_sensor_anomalies.constants import MODEL_FOLDER_NAME


@pytest.fixture(scope="session", autouse=True)
def setup_temp_dir(tmp_path_factory):
    tmp_dir = tmp_path_factory.mktemp("root")
    folder_structure = "lib/folder"
    pth = tmp_dir / folder_structure
    pth.mkdir(parents=True, exist_ok=True)
    # models
    pth_models = tmp_dir / MODEL_FOLDER_NAME
    pth_models.mkdir(parents=True, exist_ok=True)
    _root_imgs = (Path(__file__).parent / "_models").glob("*.pth")
    for model in _root_imgs:
        dst = pth_models / model.name
        shutil.copy(model, dst)
    # images
    pth_img = tmp_dir / "images"
    pth_img.mkdir(parents=True, exist_ok=True)
    _root_imgs = (Path(__file__).parent / "_img").glob("**/*.bmp")
    for img in _root_imgs:
        dst = pth_img / img.name
        shutil.copy(img, dst)

    with patch("dopt_sensor_anomalies._find_paths.LIB_ROOT_PATH", pth):
        yield tmp_dir


@pytest.fixture(scope="session", autouse=True)
def results_folder(setup_temp_dir) -> Path:
    if os.getenv("DOPT_WRITE_RESULTS", False):
        results_base = Path(__file__).parent
    else:
        results_base = setup_temp_dir
    results = results_base / "_results"
    if not results.exists():
        results.mkdir()

    return results


@pytest.fixture(scope="session")
def path_img_with_failure_ElectrodeCount(setup_temp_dir) -> Path:
    filename = "window_15_fail_electrode.bmp"
    pth_img = setup_temp_dir / f"images/{filename}"
    assert pth_img.exists(), "failure image not existing"
    return pth_img


@pytest.fixture(scope="session")
def path_img_with_failure_TrainedModel(setup_temp_dir) -> Path:
    filename = "window_19_fail_model.bmp"
    pth_img = setup_temp_dir / f"images/{filename}"
    assert pth_img.exists(), "failure image not existing"
    return pth_img
