"""MusicGridStudio entry point."""

from __future__ import annotations

import sys


def _dependency_error(exc: ModuleNotFoundError) -> int:
    package = exc.name or "a required package"
    message = (
        f"{package} was not found.\n\n"
        "Run this command first:\n"
        "  py -m pip install -r requirements.txt\n\n"
        "Then start the player with:\n"
        "  py app.py"
    )
    try:
        import tkinter
        from tkinter import messagebox

        root = tkinter.Tk()
        root.withdraw()
        messagebox.showerror("MusicGridStudio", message)
        root.destroy()
    except Exception:
        print(message, file=sys.stderr)
    return 1


def main() -> int:
    try:
        from PySide6.QtCore import QCoreApplication, QSettings, Qt
        from PySide6.QtWidgets import QApplication
        from musicgridstudio import __version__
        from musicgridstudio.edition import is_trial_edition, product_name
        from musicgridstudio.main_window import MainWindow
        from musicgridstudio.resources import application_icon
        from musicgridstudio.style import APP_STYLE
    except ModuleNotFoundError as exc:
        return _dependency_error(exc)

    QCoreApplication.setOrganizationName("LeLien Consulting")
    QCoreApplication.setApplicationName(product_name())
    QCoreApplication.setApplicationVersion(__version__)

    if not is_trial_edition():
        # Carry forward preferences from releases published under the old name.
        current_settings = QSettings()
        legacy_settings_sources = (
            QSettings("tauyori", "MusicGridStudio"),
            QSettings("Harmonia", "Harmonia Player"),
        )
        for legacy_settings in legacy_settings_sources:
            for key in legacy_settings.allKeys():
                if not current_settings.contains(key):
                    current_settings.setValue(key, legacy_settings.value(key))
        current_settings.sync()

    QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps)
    app = QApplication(sys.argv)
    app.setStyle("Fusion")
    app.setStyleSheet(APP_STYLE)
    app.setWindowIcon(application_icon())

    window = MainWindow()
    window.show()
    return app.exec()


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