import sys
from pathlib import Path

from PySide6.QtCore import QResource
from PySide6.QtGui import QFontDatabase, QFont
from PySide6.QtWidgets import QApplication

# Ne pas supprimer ! Enregistre les ressources Qt
import resources # noqa: F401 - required to register Qt resources

from ui.main_window import MainWindow
from constants import RESOURCES_FONT

# ---------------------------------------------------------------------------
# Bundle path resolution
# ---------------------------------------------------------------------------

if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
    bundle_dir = Path(sys._MEIPASS)
else:
    bundle_dir = Path(__file__).resolve().parent.parent

QResource.registerResource(f"{bundle_dir}/resources.py")


# ---------------------------------------------------------------------------
# Font helper
# ---------------------------------------------------------------------------

def load_custom_font() -> str:
    font_id = QFontDatabase.addApplicationFont(RESOURCES_FONT)
    if font_id == -1:
        raise RuntimeError("Failed to load font from resources.")
    font_families = QFontDatabase.applicationFontFamilies(font_id)
    if not font_families:
        raise RuntimeError("No font families found in the loaded font.")
    return font_families[0]


# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    app = QApplication(sys.argv)

    # Chargement des styles de l'application
    with open(f"{bundle_dir}/styles/styles.qss", 'r') as f:
        app.setStyleSheet(f.read())

    # Application de la font custom sur toute l'application'
    app.setFont(QFont(load_custom_font(), 16))

    window = MainWindow(bundle_dir)
    sys.exit(app.exec())
