#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import sys
import os

# 添加父目录到路径以便导入模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from excel_reader import get_questions_data

def analyze_tags():
    """分析题库中的所有标签"""
    questions = get_questions_data()
    
    all_tags = set()
    tag_counts = {}
    
    for question_type, question_list in questions.items():
        for question in question_list:
            tags = question.get('题目标签', '') or question.get('标签', '')
            if tags:
                # 分割标签并去重
                question_tags = [tag.strip() for tag in tags.split() if tag.strip()]
                for tag in question_tags:
                    all_tags.add(tag)
                    tag_counts[tag] = tag_counts.get(tag, 0) + 1
    
    # 按标签出现次数排序
    sorted_tags = sorted(all_tags, key=lambda x: tag_counts[x], reverse=True)
    
    print("题库标签分析结果:")
    print(f"总共有 {len(all_tags)} 个不同的标签")
    print("\n标签列表 (按出现频率排序):")
    for i, tag in enumerate(sorted_tags, 1):
        count = tag_counts[tag]
        print(f"{i:2d}. {tag} ({count}题)")
    
    # 保存标签列表到文件
    tag_data = {
        'tags': sorted_tags,
        'tag_counts': tag_counts,
        'total_unique_tags': len(all_tags)
    }
    
    with open('/Users/moshui/Documents/survey/public/tags.json', 'w', encoding='utf-8') as f:
        json.dump(tag_data, f, ensure_ascii=False, indent=2)
    
    print(f"\n标签数据已保存到: public/tags.json")
    return tag_data

if __name__ == "__main__":
    analyze_tags()