from collections import defaultdict

class TranslationCandidateSelector:
    def __init__(self, term_base=None, weights=None):
        """
        初始化翻译候选选择器
        :param term_base: 术语库字典 {源术语: 目标术语}
        :param weights: 权重字典 {'word_order', 'term', 'frequency'}
        """
        self.term_base = term_base or {}
        self.history = defaultdict(int)
        self.weights = weights or {'word_order': 0.4, 'term': 0.3, 'frequency': 0.3}
        
    def add_term(self, source, target):
        """添加术语到术语库"""
        self.term_base[source] = target
        
    def update_history(self, candidate):
        """更新候选历史使用记录"""
        self.history[candidate] += 1
        
    def calculate_word_order_similarity(self, source_tokens, candidate_tokens):
        """
        计算词序相似度（基于相对位置差异）
        返回值范围：0.0-1.0，1表示完全相同
        """
        common = set(source_tokens) & set(candidate_tokens)
        if not common:
            return 0.0
        
        total_diff = 0.0
        src_len = len(source_tokens)
        cand_len = len(candidate_tokens)
        
        for word in common:
            # 获取词在双方中的第一个出现位置
            src_pos = source_tokens.index(word)
            cand_pos = candidate_tokens.index(word)
            
            # 计算相对位置（处理单字情况）
            rel_src = src_pos / (src_len-1) if src_len > 1 else 0.0
            rel_cand = cand_pos / (cand_len-1) if cand_len > 1 else 0.0
            total_diff += abs(rel_src - rel_cand)
            
        return 1.0 - (total_diff / len(common))
    
    def calculate_term_consistency(self, source_tokens, candidate_tokens):
        """
        计算术语一致性
        返回值范围：0.0-1.0，1表示完全一致
        """
        source_terms = [term for term in source_tokens if term in self.term_base]
        if not source_terms:
            return 1.0  # 无术语时返回满分
        
        correct = 0
        for term in source_terms:
            target_term = self.term_base.get(term)
            if target_term and (target_term in candidate_tokens):
                correct += 1
                
        return correct / len(source_terms)
    
    def calculate_frequency_score(self, candidate):
        """
        计算历史使用频率得分
        返回值范围：0.0-1.0，1表示使用最频繁
        """
        if not self.history:
            return 0.0  # 无历史记录时返回0分
            
        counts = list(self.history.values())
        max_count = max(counts) if counts else 1
        return self.history[candidate] / max_count
    
    def evaluate_candidates(self, source_text, candidates):
        """
        评估所有候选译文
        :param source_text: 源文本（已分词列表）
        :param candidates: 候选译文列表（字符串列表）
        :return: 排序后的候选列表（候选文本，总分）
        """
        scored = []
        source_tokens = source_text if isinstance(source_text, list) else source_text.split()
        
        for candidate in candidates:
            cand_tokens = candidate.split()  # 简单分词处理
            
            # 计算各项得分
            word_order_score = self.calculate_word_order_similarity(source_tokens, cand_tokens)
            term_score = self.calculate_term_consistency(source_tokens, cand_tokens)
            freq_score = self.calculate_frequency_score(candidate)
            
            # 加权综合得分
            total_score = (
                self.weights['word_order'] * word_order_score +
                self.weights['term'] * term_score +
                self.weights['frequency'] * freq_score
            )
            
            scored.append((candidate, total_score))
        
        # 按得分降序排序
        return sorted(scored, key=lambda x: x[1], reverse=True)
    
    def select_best(self, source_text, candidates):
        """选择最佳候选并更新历史"""
        scored = self.evaluate_candidates(source_text, candidates)
        best_candidate = scored[0][0]
        self.update_history(best_candidate)
        return best_candidate

# 使用示例
if __name__ == "__main__":
    # 初始化系统
    term_base = {
        "Python": "Python",
        "AI": "人工智能",
        "translation": "翻译"
    }
    selector = TranslationCandidateSelector(
        term_base=term_base,
        weights={'word_order': 0.4, 'term': 0.4, 'frequency': 0.2}
    )

    # 模拟历史记录
    selector.history.update({
        "Python 人工智能 翻译": 5,
        "人工智能 Python 翻译": 3
    })
    # 测试用例
    source = ["Python", "AI", "translation"]
    candidates = [
        "Python 人工智能 翻译",    # 完美匹配
        "人工智能 Python 翻译",    # 词序不同
        "AI 的 Python 翻译",      # 包含额外词汇
        "Python 的 人工翻译"       # 术语错误
    ]
    # 评估候选
    results = selector.evaluate_candidates(source, candidates)
    print("候选评分：")
    for candidate, score in results:
        print(f"{score:.3f}: {candidate}")

    # 选择最佳
    best = selector.select_best(source, candidates)
    print("\n最佳候选：", best)