"""俱乐部默认打手邀请码（一键登录无扫码时使用）。"""
import logging

logger = logging.getLogger(__name__)

CONFIG_KEY = 'default_dashou_invite'

# 与 club_migrate.CLUB_MIGRATE_DEFAULT_GUANSHI_INVITE 保持同步（无 config_json 时回落）
_FALLBACK_DEFAULT_INVITE = {
    'lxs': '0000008VfJKPu4Spmcjt',
    'xq': '0000008RffVgKHMj7kQC',
}


def get_club_default_dashou_invite(club_id: str) -> str:
    """
    优先读 Club.config_json.default_dashou_invite，
    否则回落内置各店默认管事邀请码。
    """
    cid = (club_id or '').strip()
    if not cid:
        return ''
    try:
        from jituan.models import Club
        club = Club.query.filter(club_id=cid).first()
        if club:
            cfg = club.config_json or {}
            code = (cfg.get(CONFIG_KEY) or '').strip()
            if code:
                return code
    except Exception:
        logger.exception('read default_dashou_invite failed club=%s', cid)
    try:
        from jituan.services.club_migrate import CLUB_MIGRATE_DEFAULT_GUANSHI_INVITE
        code = (CLUB_MIGRATE_DEFAULT_GUANSHI_INVITE.get(cid) or '').strip()
        if code:
            return code
    except Exception:
        pass
    return (_FALLBACK_DEFAULT_INVITE.get(cid) or '').strip()


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