import shutil
from unittest.mock import patch

import pytest

from dopt_sensor_anomalies import _csharp_interface, constants, errors


@patch("dopt_sensor_anomalies._find_paths.STOP_FOLDER_NAME", "lib")
def test_sensor_anomalies_detection_FailImagePath(setup_temp_dir):
    img_path = str(setup_temp_dir / "not-existing.bmp")
    pixels_per_metric_X: float = 0.251
    pixels_per_metric_Y: float = 0.251

    MESSAGE = "The provided path seems not to exist"

    with pytest.raises(FileNotFoundError, match=MESSAGE):
        _csharp_interface.sensor_anomalies_detection(
            img_path, pixels_per_metric_X, pixels_per_metric_Y
        )


@patch("dopt_sensor_anomalies._find_paths.STOP_FOLDER_NAME", "lib")
def test_sensor_anomalies_detection_FailElectrodeCount(path_img_with_failure_ElectrodeCount):
    img_path = str(path_img_with_failure_ElectrodeCount)
    pixels_per_metric_X: float = 0.251
    pixels_per_metric_Y: float = 0.251

    MESSAGE = "Number of counted electrodes does not match the"

    with pytest.raises(errors.InvalidElectrodeCount, match=MESSAGE):
        _csharp_interface.sensor_anomalies_detection(
            img_path, pixels_per_metric_X, pixels_per_metric_Y
        )


@patch("dopt_sensor_anomalies._find_paths.STOP_FOLDER_NAME", "lib")
def test_sensor_anomalies_detection_Success(
    results_folder, path_img_with_failure_TrainedModel
):
    # paths: check files for existence and delete because of other tests
    root_img = path_img_with_failure_TrainedModel.parent
    file_stem = path_img_with_failure_TrainedModel.stem
    csv_file = root_img / f"{file_stem}.csv"
    heatmap_file = root_img / f"{file_stem}{constants.HEATMAP_FILENAME_SUFFIX}.png"
    if csv_file.exists():
        csv_file.unlink()
    if heatmap_file.exists():
        heatmap_file.unlink()

    img_path = str(path_img_with_failure_TrainedModel)
    pixels_per_metric_X: float = 0.251
    pixels_per_metric_Y: float = 0.251

    _csharp_interface.sensor_anomalies_detection(
        img_path, pixels_per_metric_X, pixels_per_metric_Y
    )

    assert csv_file.exists()
    assert heatmap_file.exists()
    target_folder = results_folder / "csharp_interface"
    target_folder.mkdir(exist_ok=True)
    shutil.copy(csv_file, (target_folder / csv_file.name))
    shutil.copy(heatmap_file, (target_folder / heatmap_file.name))
