"""俱乐部假单开关 + 押金过滤门槛（config_json）。"""
import logging
from decimal import Decimal, InvalidOperation

logger = logging.getLogger(__name__)

CONFIG_KEY = 'fake_grab_order_enabled'
YAJIN_THRESHOLD_KEY = 'fake_grab_yajin_hide_threshold'
DEFAULT_YAJIN_HIDE_THRESHOLD = Decimal('10')


def is_club_fake_grab_enabled(club_id: str) -> bool:
    """某俱乐部是否对打手侧开启假单池。默认关闭。"""
    cid = (club_id or '').strip()
    if not cid:
        return False
    try:
        from django.conf import settings
        if not getattr(settings, 'FAKE_GRAB_ORDER_POOL_ENABLED', True):
            return False
    except Exception:
        pass
    try:
        from jituan.models import Club
        club = Club.query.filter(club_id=cid).first()
        if not club and cid != cid.lower():
            club = Club.query.filter(club_id=cid.lower()).first()
        if not club:
            return False
        cfg = club.config_json or {}
        raw = cfg.get(CONFIG_KEY)
        if isinstance(raw, str):
            return raw.strip().lower() in ('1', 'true', 'yes', 'on')
        return bool(raw)
    except Exception:
        logger.exception('read fake_grab_order_enabled failed club=%s', cid)
        return False


def get_fake_yajin_hide_threshold(club_id: str) -> Decimal:
    """
    押金 ≥ 该值时过滤假单（只看真单）。
    后台可配，默认 10。
    """
    cid = (club_id or '').strip()
    if not cid:
        return DEFAULT_YAJIN_HIDE_THRESHOLD
    try:
        from jituan.models import Club
        club = Club.query.filter(club_id=cid).first()
        if not club:
            return DEFAULT_YAJIN_HIDE_THRESHOLD
        cfg = club.config_json or {}
        raw = cfg.get(YAJIN_THRESHOLD_KEY, DEFAULT_YAJIN_HIDE_THRESHOLD)
        try:
            val = Decimal(str(raw))
        except (InvalidOperation, TypeError, ValueError):
            return DEFAULT_YAJIN_HIDE_THRESHOLD
        if val < 0:
            return DEFAULT_YAJIN_HIDE_THRESHOLD
        return val
    except Exception:
        logger.exception('read fake_grab_yajin_hide_threshold failed club=%s', cid)
        return DEFAULT_YAJIN_HIDE_THRESHOLD


def set_club_fake_grab_enabled(club, enabled: bool) -> None:
    """写入 club.config_json，调用方负责 save。"""
    cfg = dict(getattr(club, 'config_json', None) or {})
    cfg[CONFIG_KEY] = bool(enabled)
    club.config_json = cfg


def set_fake_yajin_hide_threshold(club, threshold) -> Decimal:
    """写入押金过滤门槛，调用方负责 save。返回规范化后的值。"""
    try:
        val = Decimal(str(threshold))
    except (InvalidOperation, TypeError, ValueError):
        val = DEFAULT_YAJIN_HIDE_THRESHOLD
    if val < 0:
        val = DEFAULT_YAJIN_HIDE_THRESHOLD
    cfg = dict(getattr(club, 'config_json', None) or {})
    # 存成可 JSON 序列化的数字
    cfg[YAJIN_THRESHOLD_KEY] = float(val)
    club.config_json = cfg
    return val
