"""Application bootstrap for the PySide6 GUI."""

from __future__ import annotations

import sys
from pathlib import Path

from PySide6 import QtCore, QtGui, QtWidgets

from app.logic import DEFAULTS, LANGUAGE, RESET_EXCLUSIONS_ON_IMAGE_CHANGE
from .main_window import MainWindow


def create_application() -> QtWidgets.QApplication:
    """Create the Qt application instance with customised styling."""
    app = QtWidgets.QApplication.instance()
    if app is None:
        app = QtWidgets.QApplication(sys.argv)

    app.setOrganizationName("ICRA")
    app.setApplicationName("Interactive Color Range Analyzer")
    app.setApplicationDisplayName("ICRA")

    palette = QtGui.QPalette()
    palette.setColor(QtGui.QPalette.Window, QtGui.QColor("#111216"))
    palette.setColor(QtGui.QPalette.WindowText, QtGui.QColor("#f5f5f5"))
    palette.setColor(QtGui.QPalette.Base, QtGui.QColor("#1a1b21"))
    palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor("#20212a"))
    palette.setColor(QtGui.QPalette.Button, QtGui.QColor("#20212a"))
    palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor("#f5f5f5"))
    palette.setColor(QtGui.QPalette.Text, QtGui.QColor("#f5f5f5"))
    palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor("#5168ff"))
    palette.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor("#ffffff"))
    app.setPalette(palette)

    font = QtGui.QFont("Segoe UI", 10)
    app.setFont(font)

    logo_path = Path(__file__).resolve().parents[1] / "assets" / "logo.png"
    if logo_path.exists():
        app.setWindowIcon(QtGui.QIcon(str(logo_path)))

    return app


def run() -> int:
    """Run the PySide6 GUI."""
    app = create_application()
    from app.logic import OVERLAY_COLOR
    window = MainWindow(
        language=LANGUAGE,
        defaults=DEFAULTS.copy(),
        reset_exclusions=RESET_EXCLUSIONS_ON_IMAGE_CHANGE,
        overlay_color=OVERLAY_COLOR,
    )

    # Respect saved geometry from QSettings; fall back to maximised on first launch
    settings = QtCore.QSettings("ICRA", "MainWindow")
    if settings.value("geometry"):
        window.show()
    else:
        primary_screen = app.primaryScreen()
        if primary_screen is not None:
            window.setGeometry(primary_screen.availableGeometry())
        window.showMaximized()
    return app.exec()
