"""PySide6 application entry point for Meeting Helper GUI."""

from __future__ import annotations

import sys
from typing import TYPE_CHECKING

from PySide6.QtGui import QColor, QFont, QIcon, QPainter, QPixmap
from PySide6.QtWidgets import QApplication

from meeting_helper.gui.main_window import MainWindow
from meeting_helper.gui.menubar import MenuBarIcon

if TYPE_CHECKING:
    from meeting_helper.config import Config


def _build_app_icon() -> QIcon:
    """Build a teal rounded-square 'MH' icon for dock and window."""
    size = 512
    pixmap = QPixmap(size, size)
    pixmap.fill(QColor(0, 0, 0, 0))
    painter = QPainter(pixmap)
    painter.setRenderHint(QPainter.Antialiasing)
    painter.setRenderHint(QPainter.TextAntialiasing)

    # Teal rounded square background — macOS standard: ~85% fill with squircle corners
    margin = 55
    radius = int((size - margin * 2) * 0.22)
    painter.setBrush(QColor("#4ec9b0"))
    painter.setPen(QColor(0, 0, 0, 0))
    painter.drawRoundedRect(margin, margin, size - margin * 2, size - margin * 2, radius, radius)

    # "MH" text
    font = QFont("SF Pro Display", 165, QFont.Bold)
    painter.setFont(font)
    painter.setPen(QColor("#ffffff"))
    painter.drawText(0, 0, size, size, 0x0084, "MH")  # AlignHCenter | AlignVCenter

    painter.end()
    return QIcon(pixmap)


def run_gui(config: "Config") -> None:
    """Launch the main GUI application."""
    app = QApplication(sys.argv)
    app.setApplicationName("Meeting Helper")
    app.setApplicationDisplayName("Meeting Helper")
    app.setOrganizationName("Meeting Helper")
    app.setQuitOnLastWindowClosed(False)

    # Fix macOS dock/tray showing "Python" instead of "Meeting Helper"
    try:
        from Foundation import NSProcessInfo, NSBundle
        NSProcessInfo.processInfo().setProcessName_("Meeting Helper")
        # Patch bundle info so Dock shows the right name
        info = NSBundle.mainBundle().infoDictionary()
        if info is not None:
            info["CFBundleName"] = "Meeting Helper"
            info["CFBundleDisplayName"] = "Meeting Helper"
            info["CFBundleExecutable"] = "Meeting Helper"
    except Exception:
        pass

    # Rename the process at OS level (changes what Activity Monitor + Dock show)
    try:
        import ctypes, ctypes.util
        libc = ctypes.CDLL(ctypes.util.find_library("c"))
        libc.pthread_setname_np.argtypes = [ctypes.c_char_p]
        libc.pthread_setname_np(b"Meeting Helper")
    except Exception:
        pass

    # Build app icon (teal rounded square with "MH")
    icon = _build_app_icon()
    app.setWindowIcon(icon)

    # Set dock icon via AppKit for macOS
    try:
        from AppKit import NSApplication, NSImage
        from Foundation import NSData
        import io
        buf = io.BytesIO()
        icon.pixmap(512, 512).save(buf := io.BytesIO(), "PNG")  # type: ignore
        # Use QPixmap -> bytes -> NSImage
        pm = icon.pixmap(512, 512)
        ba = pm.toImage()
        ba.save(tmp := str(__import__("pathlib").Path.home() / ".meeting-helper-icon.png"))
        ns_img = NSImage.alloc().initWithContentsOfFile_(tmp)
        if ns_img:
            NSApplication.sharedApplication().setApplicationIconImage_(ns_img)
    except Exception:
        pass

    window = MainWindow(config=config)
    tray = MenuBarIcon(window, port=config.port)
    window.set_tray_icon(tray)

    tray.show()
    window.showMaximized()

    sys.exit(app.exec())
