"""Tests for src/pygui/backend/controllers/batch_export_controller.py."""
from unittest.mock import MagicMock, patch

import pytest

from pygui.backend.controllers.batch_export_controller import BatchExportController
from pygui.backend.wafer.batch_export import BatchExportResult

pytestmark = pytest.mark.usefixtures("qapp")


@pytest.fixture
def controller():
    return BatchExportController()


def test_start_spawns_thread_and_sets_busy(controller):
    with patch("threading.Thread") as mock_thread:
        controller.start(["a.csv", "b.csv"], "/tmp/out")
        mock_thread.assert_called_once()
        assert controller.busy is True


def test_start_ignores_call_while_already_busy(controller):
    with patch("threading.Thread") as mock_thread:
        controller.start(["a.csv"], "/tmp/out")
        controller.start(["b.csv"], "/tmp/out")
        mock_thread.assert_called_once()


def test_handle_batch_finished_reports_all_succeeded(controller):
    finished = MagicMock()
    controller.exportFinished.connect(finished)
    controller._busy = True

    results = [
        BatchExportResult("a.csv", "a.png", True),
        BatchExportResult("b.csv", "b.png", True),
        BatchExportResult("c.csv", "c.png", True),
    ]
    controller._handle_batch_finished(results)

    finished.assert_called_once_with("Exported 3/3")
    assert controller.busy is False


def test_handle_batch_finished_reports_failures(controller):
    finished = MagicMock()
    controller.exportFinished.connect(finished)
    controller._busy = True

    results = [
        BatchExportResult("a.csv", "a.png", True),
        BatchExportResult("b.csv", "b.png", False, "parse error"),
    ]
    controller._handle_batch_finished(results)

    finished.assert_called_once_with("Exported 1/2 — 1 failed")
    assert controller.busy is False
