"""Provides the application entry point for the single-day registration viewer GUI."""

from __future__ import annotations

import sys
from typing import TYPE_CHECKING

from PySide6.QtWidgets import QApplication

from .viewer import PCViewer, BinaryPlayer
from .context_data import RegistrationViewerData

if TYPE_CHECKING:
    from pathlib import Path


def run_registration_viewer(recording_path: Path) -> None:
    """Launches the standalone single-day registration viewer.

    Creates a QApplication, shows the BinaryPlayer and PCViewer windows, and enters the event
    loop. Both viewers load registration data from the provided directory on startup and share the
    same data model for synchronized plane switching.

    Args:
        recording_path: Path to a cindra output directory containing registration results.
    """
    # Reuses the existing QApplication if one is already running (e.g. when embedded in a larger GUI),
    # otherwise creates a new one.
    application = QApplication.instance()
    owns_application = application is None
    if owns_application:
        application = QApplication(sys.argv)

    # Loads recording data upfront so both viewer windows share the same data model. This ensures
    # plane switches in the binary player are reflected in the PC viewer without reloading from disk.
    data = RegistrationViewerData.from_recording(root_path=recording_path)

    # Creates both viewer windows with the shared data model.
    binary_player = BinaryPlayer(data=data)
    pc_viewer = PCViewer(data=data)

    # When the user switches planes in the binary player, the shared data model is mutated in place
    # (via switch_plane). This signal connection triggers the PC viewer to re-read PC images and
    # metrics from the updated data model so both windows stay synchronized.
    binary_player.plane_changed.connect(lambda _index: pc_viewer.load_data(data=binary_player.data))

    binary_player.show()
    pc_viewer.show()

    # Only enters the event loop if this function created the QApplication. When embedded in a
    # larger GUI, the caller is responsible for running the event loop.
    if owns_application:
        sys.exit(application.exec())
