"""Punto de entrada: arranca la QApplication y la ventana principal."""

from __future__ import annotations

import sys

from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QApplication, QMessageBox

from .config import load_config
from .paths import app_icon_path, config_file, data_root
from .ui.main_window import MainWindow
from .ui.theme import apply_theme


def main() -> int:
    app = QApplication(sys.argv)
    app.setApplicationName("jlauncher")
    icon_path = app_icon_path()
    if icon_path is not None:
        app.setWindowIcon(QIcon(str(icon_path)))
    # Tema del sistema para el posible diálogo de error previo a la ventana;
    # MainWindow re-aplica el modo guardado (system/light/dark) y vigila los cambios.
    apply_theme(app)

    cfg_path = config_file()
    try:
        config = load_config(cfg_path)
    except Exception as exc:  # noqa: BLE001 - mostrar cualquier error de carga al usuario
        QMessageBox.critical(
            None,
            "Error carregant games.toml",
            f"No s'ha pogut llegir la configuració a:\n{cfg_path}\n\n{exc}",
        )
        return 1

    window = MainWindow(config, data_root(config.data_dir))
    window.show()
    return app.exec()


if __name__ == "__main__":
    raise SystemExit(main())
