"""Иконка в системном трее — свернуть вместо закрытия."""

from __future__ import annotations

import logging
import threading
from pathlib import Path
from typing import TYPE_CHECKING

from panel_state import set_panel_hidden
from paths import get_icon_ico_path, get_tray_icon_path

logger = logging.getLogger(__name__)

if TYPE_CHECKING:
    import webview

_tray_icon = None
_quitting = False
_restore_lock = threading.Lock()
_restoring = False


def is_quitting() -> bool:
    return _quitting


_hiding_to_tray = False


def is_hiding_to_tray() -> bool:
    return _hiding_to_tray


def restore_panel_ui(window: "webview.Window") -> None:
    """Показать панель из трея / toast. Только WinForms — без evaluate_js."""
    global _restoring
    if _quitting or _hiding_to_tray:
        return
    with _restore_lock:
        if _restoring:
            return
        _restoring = True
    try:
        set_panel_hidden(False)
        from window_state import show_window_from_tray

        show_window_from_tray(window)
    except Exception as e:
        logger.warning("restore panel: %s", e)
        try:
            window.show()
        except Exception:
            pass
    finally:
        with _restore_lock:
            _restoring = False


def _load_tray_image():
    from PIL import Image

    ico = get_icon_ico_path()
    if ico.exists():
        try:
            img = Image.open(ico)
            for i in range(32):
                try:
                    img.seek(i)
                except EOFError:
                    break
                if img.size == (32, 32):
                    return img.convert("RGBA").copy()
            img.seek(0)
            return img.convert("RGBA").resize((32, 32), Image.Resampling.LANCZOS)
        except Exception:
            pass
    icon_png = get_tray_icon_path()
    image = Image.open(icon_png).convert("RGBA")
    if max(image.size) != 32:
        image = image.resize((32, 32), Image.Resampling.LANCZOS)
    return image


def start(window: "webview.Window", icon_png: Path | None = None) -> None:
    global _tray_icon

    icon_png = icon_png or get_tray_icon_path()
    if not icon_png.exists():
        logger.warning("Tray icon not found: %s", icon_png)
        return

    def _run() -> None:
        global _tray_icon
        try:
            import pystray
            from PIL import Image

            image = _load_tray_image()
            menu = pystray.Menu(
                pystray.MenuItem("Открыть", lambda *_: restore_panel_ui(window), default=True),
                pystray.MenuItem("Выход", lambda *_: quit_app(window)),
            )
            _tray_icon = pystray.Icon("axon_dump_radar", image, "AXON Dump Radar", menu)
            _tray_icon.run()
        except Exception as e:
            logger.warning("Tray unavailable: %s", e)

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


def show_window(window: "webview.Window") -> None:
    restore_panel_ui(window)


def hide_to_tray(window: "webview.Window") -> None:
    from window_state import post_on_ui

    post_on_ui(window, lambda: _hide_to_tray_ui(window))


def _hide_to_tray_ui(window: "webview.Window") -> None:
    """Только UI-поток WinForms."""
    global _hiding_to_tray
    _hiding_to_tray = True
    try:
        from window_state import cancel_pending_timers, hide_window_to_tray_form, snapshot_window

        cancel_pending_timers()
        snapshot_window(window)
        set_panel_hidden(True)
        hide_window_to_tray_form(window)
    except Exception as e:
        logger.warning("hide to tray ui: %s", e)
    finally:
        _hiding_to_tray = False


def quit_app(window: "webview.Window") -> None:
    global _quitting, _tray_icon
    _quitting = True
    try:
        from window_state import mark_shutting_down

        mark_shutting_down()
    except Exception:
        pass
    icon = _tray_icon
    _tray_icon = None
    if icon:
        try:
            icon.stop()
        except Exception:
            pass
    try:
        window.destroy()
    except Exception as e:
        logger.warning("window.destroy: %s", e)
