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

import os
import re
import glob

def extract_keys_from_file(file_path):
    """从本地化文件中提取所有key"""
    keys = set()
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            match = re.match(r'^"([^"]+)"\s*=', line.strip())
            if match:
                keys.add(match.group(1))
    return keys

def get_all_keys():
    """获取所有文件中出现的key"""
    all_keys = set()
    lproj_files = glob.glob('MyQrCode/*.lproj/Localizable.strings')
    
    for file_path in lproj_files:
        keys = extract_keys_from_file(file_path)
        all_keys.update(keys)
    
    return all_keys

def get_translations_from_file(file_path):
    """从文件中获取所有翻译"""
    translations = {}
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            match = re.match(r'^"([^"]+)"\s*=\s*"([^"]*)"\s*;', line.strip())
            if match:
                key, value = match.group(1), match.group(2)
                translations[key] = value
    return translations

def sync_file(file_path, all_keys, reference_translations):
    """同步单个文件，确保包含所有key"""
    print(f"Syncing {file_path}...")
    
    # 读取现有内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 获取现有翻译
    existing_translations = get_translations_from_file(file_path)
    
    # 找出缺失的key
    missing_keys = all_keys - set(existing_translations.keys())
    
    if not missing_keys:
        print(f"  No missing keys for {file_path}")
        return
    
    print(f"  Adding {len(missing_keys)} missing keys...")
    
    # 在文件末尾添加缺失的key
    additions = []
    for key in sorted(missing_keys):
        if key in reference_translations:
            # 使用参考翻译作为默认值
            additions.append(f'"{key}" = "{reference_translations[key]}";')
        else:
            # 如果没有参考翻译，使用key本身
            additions.append(f'"{key}" = "{key}";')
    
    if additions:
        # 确保文件以换行符结尾
        if not content.endswith('\n'):
            content += '\n'
        
        # 添加缺失的条目
        content += '\n// Missing keys (using reference as fallback)\n'
        content += '\n'.join(additions) + '\n'
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"  Added {len(additions)} keys to {file_path}")

def main():
    """主函数"""
    print("Synchronizing all localization files...")
    
    # 获取所有key
    all_keys = get_all_keys()
    print(f"Found {len(all_keys)} unique keys across all files")
    
    # 使用英语文件作为参考
    en_translations = get_translations_from_file('MyQrCode/en.lproj/Localizable.strings')
    print(f"Using English file as reference with {len(en_translations)} translations")
    
    # 同步所有文件
    lproj_files = glob.glob('MyQrCode/*.lproj/Localizable.strings')
    
    for file_path in lproj_files:
        sync_file(file_path, all_keys, en_translations)
    
    print("Done!")

if __name__ == "__main__":
    main()
