import json
import os
import subprocess
import sys


def main():
    try:
        print('Begin update localazy.')
        # 读取translateKey.txt并生成include_keys
        with open('translateKey.txt', 'r') as f:
            include_keys = [f'MATCH:{line.strip()}' for line in f]

        # 读取和更新localazy.json
        with open('localazy.json', 'r+') as f:
            content = json.load(f)
            content['conversion']['actions']['includeKeys'] = include_keys
            f.seek(0)
            f.truncate()
            f.write(json.dumps(content, indent=4, ensure_ascii=False))

        # 根据平台执行localazy download命令
        params = ['cmd', '/c', 'localazy', 'download'] if sys.platform.startswith('win') else ['localazy', 'download']
        result = subprocess.run(params, stdout=subprocess.PIPE, text=True, errors='ignore')

        # 检查命令执行结果
        if 'Done.' in result.stdout:
            print('Download localazy successful.')
        else:
            print('Download localazy failed.')
            sys.exit(-1)

        # 读取strings.json并写入strings.ts
        with open('strings.json', 'r', encoding='utf8') as f:
            string_json = json.load(f)

        with open('src/i18n/strings.ts', 'w', encoding='utf8') as f:
            pt = string_json.get('pt-BR')
            if pt:
                string_json['pt_BR'] = pt
            f.write(f'export default {json.dumps(string_json, indent=4, ensure_ascii=False)}')

        os.remove('strings.json')
        print('Update localazy finished.')

    except Exception as e:
        print(f'An error occurred: {e}')
        sys.exit(-1)


if __name__ == '__main__':
    main()
