from pypos.core.utils.config_utils import read_config


# edited by glg
def _to_bool(value, default=True):
    if isinstance(value, bool):
        return value
    if value is None:
        return bool(default)
    text = str(value).strip().lower()
    if text in {"1", "true", "yes", "on"}:
        return True
    if text in {"0", "false", "no", "off"}:
        return False
    return bool(default)


# edited by glg
def _to_int(value, default):
    try:
        return int(value)
    except (TypeError, ValueError):
        return int(default)


# edited by glg
def _to_color(value, default):
    text = str(value or "").strip()
    if not text:
        return str(default)
    if text.startswith("#") and len(text) in {4, 7, 9}:
        return text
    return str(default)


# edited by glg
def build_button_wrapper_qss(config=None):
    cfg = config if isinstance(config, dict) else read_config()
    enabled = _to_bool(cfg.get("ui_button_wrapper_enabled"), default=True)
    if not enabled:
        return ""

    bg = _to_color(cfg.get("ui_button_wrapper_bg"), "#e9eef5")
    bg_hover = _to_color(cfg.get("ui_button_wrapper_bg_hover"), "#dde7f3")
    bg_pressed = _to_color(cfg.get("ui_button_wrapper_bg_pressed"), "#d2deec")
    border = _to_color(cfg.get("ui_button_wrapper_border"), "#95a8c2")
    border_hover = _to_color(cfg.get("ui_button_wrapper_border_hover"), "#7f96b5")
    text = _to_color(cfg.get("ui_button_wrapper_text"), "#1f2d3d")
    radius = max(2, _to_int(cfg.get("ui_button_wrapper_radius_px"), 4))
    pad_v = max(2, _to_int(cfg.get("ui_button_wrapper_padding_v_px"), 4))
    pad_h = max(8, _to_int(cfg.get("ui_button_wrapper_padding_h_px"), 12))

    return (
        "\n/* edited by glg: runtime button wrapper */\n"
        f"QPushButton {{ background-color: {bg}; color: {text}; border: 1px solid {border}; "
        f"border-radius: {radius}px; padding: {pad_v}px {pad_h}px; }}\n"
        "QPushButton[compactButton=\"true\"] { min-width: 1px; padding: 4px 8px; }\n"
        f"QPushButton:hover {{ background-color: {bg_hover}; border: 1px solid {border_hover}; }}\n"
        f"QPushButton:pressed {{ background-color: {bg_pressed}; border: 1px solid {border_hover}; "
        f"padding: {pad_v}px {pad_h}px; }}\n"
        "QPushButton:disabled { background-color: #f2f4f7; color: #9aa4b2; border: 1px solid #d0d7e2; }\n"
    )
