"""轻量错误消息翻译（基于 Accept-Language header）"""

# (lang, translation) tuples — add ("en", ...) for future English variants
ERROR_MESSAGES: dict[str, tuple[str, str]] = {
    # auth.py
    "Invalid credentials": ("zh", "邮箱或密码错误"),
    "Account disabled": ("zh", "账号已停用"),
    "Invalid or expired token": ("zh", "登录已过期，请重新登录"),
    "Refresh token revoked": ("zh", "刷新令牌已被吊销"),
    "Password must be at least 6 characters": ("zh", "密码长度不能少于6位"),
    "Invalid or expired reset token": ("zh", "重置链接无效或已过期"),
    "If approved, a confirmation email will be sent": ("zh", "该邮箱已注册，请查看邮件确认"),
    "If the email exists, a reset link has been sent.": ("zh", "如果该邮箱已注册，重置链接已发送"),
    # permissions.py
    "Not authenticated": ("zh", "未登录，请先登录"),
    "Invalid token type": ("zh", "令牌类型无效"),
    "Token has been revoked": ("zh", "令牌已被吊销"),
    "Missing tenant context": ("zh", "缺少租户信息"),
    "Not a member of this tenant": ("zh", "不属于该组织"),
    "Invalid role": ("zh", "角色无效"),
    "Insufficient permissions": ("zh", "权限不足"),
    # error_handlers.py
    "An unexpected error occurred": ("zh", "服务器内部错误，请稍后重试"),
}


def translate(message: str, lang: str = "zh") -> str:
    """根据语言返回翻译后的消息，找不到翻译则返回原文作为 fallback。"""
    entry = ERROR_MESSAGES.get(message)
    if entry and entry[0] == lang:
        return entry[1]
    return message


def detect_language(accept_language: str | None) -> str:
    """从 Accept-Language header 提取语言偏好，默认中文。"""
    if not accept_language:
        return "zh"
    lang = accept_language.split(",")[0].split("-")[0].strip().lower()
    return lang if lang in ("zh", "en") else "zh"
