"""PySide6 application entry point."""

import argparse
import os
import platform
import sys
from pathlib import Path

from PySide6.QtWidgets import QApplication
from PySide6.QtCore import Qt
from PySide6.QtGui import QIcon

from .. import __version__, log
from ..config import Config
from .main_window import MainWindow


class InterpreterApp:
    """Main application."""

    def __init__(self, config: Config):
        self._config = config
        self._app: QApplication = None
        self._window: MainWindow = None

    def setup(self):
        """Set up the application."""
        # Enable high DPI scaling
        QApplication.setHighDpiScaleFactorRoundingPolicy(
            Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
        )

        # Set desktop filename before creating QApplication (required for Wayland app_id)
        if platform.system() == "Linux":
            QApplication.setDesktopFileName("interpreter-v2")

        self._app = QApplication(sys.argv)
        self._app.setApplicationName("Interpreter")

        # Set application icon
        icon_path = self._get_icon_path()
        icon = None
        if icon_path.exists():
            icon = QIcon(str(icon_path))
            self._app.setWindowIcon(icon)

        # Create main window
        self._window = MainWindow(self._config)

        # Also set icon on main window (needed for Linux taskbar)
        if icon:
            self._window.setWindowIcon(icon)

        # Handle app quit
        self._app.aboutToQuit.connect(self._on_quit)

    def _get_icon_path(self) -> Path:
        """Get platform-appropriate icon path."""
        resources = Path(__file__).parent.parent / "resources" / "icons"
        system = platform.system()
        if system == "Darwin":
            return resources / "icon.icns"
        elif system == "Windows":
            return resources / "icon.ico"
        else:
            return resources / "icon.png"

    def _on_quit(self):
        """Handle application quit."""
        # Save config
        self._config.save()

        # Clean up window resources
        if self._window:
            self._window.cleanup()

    def run(self) -> int:
        """Run the application.

        Returns:
            Exit code.
        """
        self._window.show()
        return self._app.exec()


def run():
    """Main entry point for GUI application."""
    # Parse command-line arguments
    parser = argparse.ArgumentParser(description="Interpreter - Screen translator for Japanese games")
    parser.add_argument("--debug", action="store_true", help="Enable debug logging")
    args = parser.parse_args()

    # Setup GPU libraries early (before any CUDA-dependent imports)
    from ..gpu import setup as setup_gpu
    setup_gpu()

    # Configure logging
    log.configure(level="DEBUG" if args.debug else "INFO")
    logger = log.get_logger()
    logger.info(f"interpreter v{__version__}")

    # Suppress harmless warnings
    os.environ["PYTHONWARNINGS"] = "ignore::UserWarning:multiprocessing.resource_tracker"
    os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
    os.environ["HF_HUB_VERBOSITY"] = "error"  # Suppress unauthenticated request warnings

    # Load config
    config = Config.load()

    # Create and run app
    app = InterpreterApp(config)
    app.setup()
    sys.exit(app.run())
