from __future__ import annotations

import threading
from typing import Any, Callable

from PySide6.QtCore import QObject, Signal

# 单行输入框统一尺寸：宽 450、高 32（与 mac 演示对齐）
INPUT_FIELD_QSS = """
QLineEdit, QComboBox {
    min-height: 32px;
    max-height: 32px;
    min-width: 450px;
    max-width: 450px;
}
"""


def run_async(fn: Callable[[], Any], done: Callable[[Any], None]) -> None:
    class _AsyncBridge(QObject):
        finished = Signal(object, object)

        def __init__(self) -> None:
            super().__init__()
            self.finished.connect(self._deliver)

        def _deliver(self, cb: object, payload: object) -> None:
            cb(payload)

    # Keep a single bridge living on the GUI/main thread.
    global _ASYNC_BRIDGE
    try:
        bridge = _ASYNC_BRIDGE
    except NameError:
        _ASYNC_BRIDGE = _AsyncBridge()
        bridge = _ASYNC_BRIDGE

    def work() -> None:
        try:
            result = fn()
            bridge.finished.emit(done, result)
        except Exception as exc:
            bridge.finished.emit(done, exc)

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