"""
Marine Compass Display
----------------------
python main.py                  # normal run (reads config.py ports)
python main.py --sim            # built-in NMEA simulator (no hardware needed)
python main.py --port COM3      # Windows override
python main.py --port /dev/ttyUSB0 --baud 38400
python main.py --kiosk          # RPi fullscreen, cursor hidden, no screensaver
"""
import sys
import argparse
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore    import Qt


def main():
    parser = argparse.ArgumentParser(description='Marine Compass Display')
    parser.add_argument('--sim',   action='store_true', help='Run with NMEA simulator')
    parser.add_argument('--port',  default=None,        help='Serial port override')
    parser.add_argument('--baud',  type=int, default=4800)
    parser.add_argument('--kiosk', action='store_true', help='Kiosk mode (RPi): hide cursor, disable screensaver')
    args = parser.parse_args()

    if args.sim:
        from simulator.nmea_simulator import start_simulator
        start_simulator()

    if args.port:
        import config
        config.SERIAL_PORTS = [{'port': args.port, 'baud': args.baud, 'name': 'CLI'}]

    if args.kiosk:
        _setup_kiosk()

    # Must be set BEFORE QApplication is created
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

    app = QApplication(sys.argv)

    if args.kiosk:
        app.setOverrideCursor(Qt.BlankCursor)

    try:
        from ui.main_window import MainWindow
        win = MainWindow()
        win.show()
        win.activateWindow()
        win.raise_()
        sys.exit(app.exec_())
    except Exception as e:
        import traceback
        from PyQt5.QtWidgets import QMessageBox
        QMessageBox.critical(None, 'Error al iniciar', traceback.format_exc())
        sys.exit(1)


def _setup_kiosk():
    """Disable screensaver and DPMS on Linux/RPi."""
    import platform
    if platform.system() != 'Linux':
        return
    import subprocess
    for cmd in [
        ['xset', 's', 'off'],
        ['xset', '-dpms'],
        ['xset', 's', 'noblank'],
    ]:
        try:
            subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except FileNotFoundError:
            pass


if __name__ == '__main__':
    main()
