from pathlib import Path
import xml.etree.ElementTree as ET
BASE = Path('/home/sebas/work/tasks/T-ballbox-rebrand-v3/decode')
OVERRIDES = {
    'background_info_item_language_by_paging': 'Idioma',
    'app_ui_switch_language': 'Español',
    'setting_language_english': 'Español',
    'english': 'Español',
    'chinese': 'Español',
    'languags_type_en': 'Español',
    'languags_type_zh': 'Español',
    'background_menu_language': 'Español',
    'background_wmlanguagek': 'Español',
    'background_wmlanguagev': 'Español',
    'background_wmlanguagey': 'Español',
}
APK_DIRS=['tcn-v1','tcn-legacy']
for apk in APK_DIRS:
    res=BASE/apk/'res'
    es = res/'values-es/strings.xml'
    if not es.exists():
        print('missing es', apk)
        continue
    es_root = ET.parse(es).getroot()
    es_map={el.attrib['name']:(el.text or '') for el in es_root.findall('string') if 'name' in el.attrib}
    targets=[res/'values/strings.xml', res/'values-en/strings.xml', res/'values-zh-rCN/strings.xml', res/'values-zh-rTW/strings.xml']
    for path in targets:
        if not path.exists(): continue
        tree=ET.parse(path); root=tree.getroot(); changed=0
        for el in root.findall('string'):
            name=el.attrib.get('name')
            if not name: continue
            if name in es_map and el.text != es_map[name]:
                el.text = es_map[name]; changed += 1
            if name in OVERRIDES and el.text != OVERRIDES[name]:
                el.text = OVERRIDES[name]; changed += 1
        tree.write(path, encoding='utf-8', xml_declaration=True)
        print(path, changed)
    for path in [res/'values/arrays.xml', res/'values-en/arrays.xml']:
        if not path.exists(): continue
        tree=ET.parse(path); root=tree.getroot(); changed=0
        for el in root.findall('.//item'):
            txt=el.text or ''
            if '101~Language 0~10(0,R/W) 0:Chinese 1:English' in txt:
                el.text = txt.replace('101~Language 0~10(0,R/W) 0:Chinese 1:English','101~Idioma 0~10(0,R/W) 0:Español 1:Español')
                changed += 1
        tree.write(path, encoding='utf-8', xml_declaration=True)
        print(path, changed)
