# Copyright (c) 2024-2026 Tencent Zhuque Lab. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Requirement: Any integration or derivative work must explicitly attribute
# Tencent Zhuque Lab (https://github.com/Tencent/AI-Infra-Guard) in its
# documentation or user interface, as detailed in the NOTICE file.

import re
from typing import Literal

def judge_language(text: str, chinese_threshold: int = 0.5, english_threshold: int = 0.5) -> Literal["default", "chinese", "english"]:
    if not text or not text.strip():
        return 'default'
    
    chinese_pattern = re.compile(r'[\u4e00-\u9fff]')
    english_pattern = re.compile(r'[A-Za-z]')
    
    chinese_chars = chinese_pattern.findall(text)
    english_chars = english_pattern.findall(text)
    
    total_chars = len([c for c in text if c.strip()])
    
    if total_chars == 0:
        return 'default'
    
    chinese_ratio = len(chinese_chars) / total_chars
    english_ratio = len(english_chars) / total_chars
    
    if chinese_ratio >= chinese_threshold:
        return 'chinese'
    elif english_ratio >= english_threshold:
        return 'english'
    else:
        return 'default'
