#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
自定义唤醒词配置脚本
解决menuconfig中文乱码问题
"""

import os
import sys
import re

def set_custom_wake_word(pinyin, display_text):
    """
    设置自定义唤醒词配置
    
    Args:
        pinyin (str): 拼音，如 "ni hao qi yuan"
        display_text (str): 显示文本，如 "你好气元"
    """
    sdkconfig_path = "sdkconfig"
    
    if not os.path.exists(sdkconfig_path):
        print(f"错误：找不到 {sdkconfig_path} 文件")
        return False
    
    # 读取sdkconfig文件
    with open(sdkconfig_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 定义要修改的配置项
    configs = {
        'CONFIG_USE_WAKE_WORD_DETECT': 'n',
        'CONFIG_USE_CUSTOM_WAKE_WORD': 'y',
        'CONFIG_CUSTOM_WAKE_WORD': f'"{pinyin}"',
        'CONFIG_CUSTOM_WAKE_WORD_DISPLAY': f'"{display_text}"'
    }
    
    # 应用配置
    for key, value in configs.items():
        pattern = rf'^{key}=.*$'
        replacement = f'{key}={value}'
        
        if re.search(pattern, content, re.MULTILINE):
            # 如果配置项存在，替换它
            content = re.sub(pattern, replacement, content, flags=re.MULTILINE)
        else:
            # 如果配置项不存在，添加到文件末尾
            content += f'\n{replacement}'
    
    # 写回文件
    with open(sdkconfig_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"✅ 成功设置自定义唤醒词配置：")
    print(f"   拼音: {pinyin}")
    print(f"   显示: {display_text}")
    print(f"   文件: {sdkconfig_path}")
    
    return True

def main():
    """主函数"""
    if len(sys.argv) != 3:
        print("使用方法：")
        print("  python scripts/set_custom_wake_word.py <拼音> <显示文本>")
        print("")
        print("示例：")
        print("  python scripts/set_custom_wake_word.py 'ni hao qi yuan' '你好气元'")
        print("  python scripts/set_custom_wake_word.py 'xiao ai tong xue' '小爱同学'")
        print("  python scripts/set_custom_wake_word.py 'tian mao jing ling' '天猫精灵'")
        return
    
    pinyin = sys.argv[1]
    display_text = sys.argv[2]
    
    if set_custom_wake_word(pinyin, display_text):
        print("\n🎉 配置完成！现在可以编译项目：")
        print("  idf.py build")
    else:
        print("\n❌ 配置失败！")

if __name__ == "__main__":
    main() 