
import sys
import os
import platform
from PyQt6.QtWidgets import QApplication
from PyQt6.QtGui import QIcon, QImageReader
from teletext.ui import MainWindow

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

def main():
    # Fix for Windows Taskbar Icon
    if platform.system() == 'Windows':
        import ctypes
        myappid = 'ddybing.teletexteditor.1.0' # arbitrary string
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

    QApplication.setDesktopFileName("no.ddybing.TeletextEditor") # Helps Linux DEs group windows
    app = QApplication(sys.argv)
    app.setApplicationName("TeletextEditor")
    app.setOrganizationName("DanielDybing")
    
    # Debug Image Formats
    supported_formats = [str(fmt, 'utf-8') for fmt in QImageReader.supportedImageFormats()]
    print(f"DEBUG: Supported Image Formats: {supported_formats}")

    # Set App Icon
    icon_path = resource_path("app_icon.png")
    print(f"DEBUG: Looking for icon at: {icon_path}")
    
    if os.path.exists(icon_path):
        print("DEBUG: Icon file found.")
        app_icon = QIcon(icon_path)
        app.setWindowIcon(app_icon)
        
        # Verify icon loaded
        if app_icon.isNull():
             print("DEBUG: QIcon is null (failed to load image data)")
        else:
             print(f"DEBUG: QIcon loaded. Available sizes: {app_icon.availableSizes()}")

    else:
        print("DEBUG: Icon file NOT found.")
        
    window = MainWindow()
    # Ensure window inherits the icon
    if os.path.exists(icon_path):
        window.setWindowIcon(QIcon(icon_path))
        
    window.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()
