from __future__ import annotations

from pathlib import Path
from typing import Callable

from PySide6.QtCore import QObject, Qt
from PySide6.QtWidgets import QMainWindow

from benchmarks.gp_regressor_widget import GPRegressorWidget


class BenchmarkGP(QObject):
    """Middle-layer interface between app.py and the GP benchmark UI."""

    def __init__(
        self,
        *,
        package_root: Path,
        workspace_provider: Callable[[], Path | None],
        owner: QMainWindow | None = None,
    ) -> None:
        super().__init__(owner)
        self._package_root = package_root
        self._workspace_provider = workspace_provider
        self._widget: GPRegressorWidget | None = None

    def show(self) -> None:
        if self._widget is None:
            self._widget = GPRegressorWidget(
                workspace_provider=self._workspace_provider,
                package_root=self._package_root,
                parent=None,
            )
            self._widget.setWindowFlag(Qt.Window, True)
            self._widget.destroyed.connect(self._clear_widget)

        self._widget.refresh_workspace_state()
        self._widget.show()
        self._widget.raise_()
        self._widget.activateWindow()

    def refresh_workspace_state(self) -> None:
        if self._widget is not None:
            self._widget.refresh_workspace_state()

    def _clear_widget(self, *_args) -> None:
        self._widget = None
