"""Theme-aware color helpers for dark/light mode contrast.

Qt stylesheets that hardcode only a background OR only a text color break when
the user's theme is the opposite of what that color assumed (e.g. dark text on
a light card is invisible once the surrounding palette goes dark and the text
inherits a light palette color). These helpers read the *active* Qt palette --
so they track the theme QGIS is actually running on macOS and Windows alike --
and return colors that stay legible in both modes.

Call these at widget-construction time. EMDS dialogs are rebuilt each time they
are shown, so they naturally pick up the current theme; long-lived widgets (the
dock) are styled once at startup, which matches how QGIS itself behaves.
"""

from __future__ import annotations

from .qt_compat import QApplication, QPalette


def is_dark_mode() -> bool:
    """Return True when the active Qt theme is dark.

    A window background darker than mid-grey (lightness < 128) means dark mode.
    Falls back to light mode when no QApplication exists (e.g. headless tests).
    """
    app = QApplication.instance()
    if app is None:
        return False
    window = app.palette().color(QPalette.ColorRole.Window)
    return window.lightness() < 128


def info_panel_colors() -> dict:
    """Colors for a light-blue 'coaching/callout' card.

    Used by the onboarding hint panels and the dock's Next-Best-Action box.
    Returns background, border, text, and link colors so callers set text color
    explicitly instead of inheriting a palette color that clashes with the card.
    """
    if is_dark_mode():
        return {
            "background": "#243140",
            "border": "#3d5a80",
            "text": "#e8eef5",
            "link": "#7fb0e0",
        }
    return {
        "background": "#f6f9fc",
        "border": "#c7d8ea",
        "text": "#1c2733",
        "link": "#1a5fb4",
    }


def muted_text_color() -> str:
    """Low-emphasis secondary text (subtitles, hints) legible on either theme."""
    return "#a0a8b4" if is_dark_mode() else "#5f6b7a"


def success_text_color() -> str:
    """Green status text, brightened for dark backgrounds."""
    return "#7ee787" if is_dark_mode() else "#166534"


def error_text_color() -> str:
    """Red status text, brightened for dark backgrounds."""
    return "#ff7b72" if is_dark_mode() else "#b91c1c"
