#!/usr/bin/env python3

# -*- coding: utf-8 -*-

"""AXON Dump Radar — панель на HTML-дизайне (pywebview)."""



from __future__ import annotations



import os

import sys

import threading



import webview



from aumid_setup import setup_app_notifications

from desktop_notify import ensure_notify_protocol, set_window_show_callback

from notify_ipc import pop_notify_action, queue_notify_action

from paths import get_assets_dir, get_icon_ico_path, get_panel_runtime_dir

from tray_service import hide_to_tray, is_quitting, quit_app, restore_panel_ui, start as start_tray

from winforms_icon_fix import patch_pywebview_taskbar_icon

from window_state import bind_window_state

from webview_api import PanelBridge



PANEL_DIR = get_panel_runtime_dir()

UI_HTML = PANEL_DIR / "ui" / "index.html"

ICON_ICO = get_icon_ico_path()
ICON_PNG = get_assets_dir() / "axon.png"





def main():

    ensure_notify_protocol()



    if not UI_HTML.exists():

        msg = f"Не найден UI: {UI_HTML}"

        if getattr(sys, "frozen", False):

            import ctypes



            ctypes.windll.user32.MessageBoxW(0, msg, "AXON Dump Radar", 0x10)

        else:

            print(msg)

        sys.exit(1)



    os.chdir(PANEL_DIR)

    if str(PANEL_DIR) not in sys.path:

        sys.path.insert(0, str(PANEL_DIR))



    bridge = PanelBridge()

    icon_path = str(ICON_ICO if ICON_ICO.exists() else "")



    window = webview.create_window(

        "AXON Dump Radar",

        url="ui/index.html",

        js_api=bridge,

        width=1100,

        height=720,

        min_size=(960, 640),

        background_color="#0A0A0A",

        text_select=True,

    )



    set_window_show_callback(lambda: restore_panel_ui(window))



    def on_loaded():

        bind_window_state(window)
        start_tray(window)



        def poll_notify_actions():

            import time



            def handle_toast_action(action: str) -> None:

                if not action or is_quitting():

                    return

                queue_notify_action(action)

                try:

                    restore_panel_ui(window)

                except Exception:

                    try:

                        window.show()

                    except Exception:

                        pass



            pending = pop_notify_action()

            if pending:

                handle_toast_action(pending)



            while not is_quitting():

                action = pop_notify_action()

                if action:

                    handle_toast_action(action)

                time.sleep(0.35)



        threading.Thread(target=poll_notify_actions, daemon=True).start()



    def on_closing():

        if is_quitting():

            return True

        from tray_service import _hide_to_tray_ui



        try:

            from window_state import post_on_ui



            post_on_ui(window, lambda: _hide_to_tray_ui(window))

        except Exception:

            threading.Timer(0.05, lambda: hide_to_tray(window)).start()

        return False



    window.events.loaded += on_loaded

    window.events.closing += on_closing



    def _setup_notifications_bg() -> None:

        try:

            setup_app_notifications()

        except Exception:

            pass

        try:

            import autostart

            autostart.sync_on_launch()

        except Exception:

            pass



    threading.Thread(target=_setup_notifications_bg, daemon=True).start()

    if icon_path:
        patch_pywebview_taskbar_icon(icon_path)

    webview.start(debug=False, icon=icon_path or None)





if __name__ == "__main__":

    main()

