import sys

with open('localSetup.js', 'r', encoding='utf-8') as f:
    js = f.read()

# 1. Add translation logic at the top
trans_code = '''// --- Storage helpers ---
let uiLocales = {};

async function applyTranslations(lang) {
  try {
    const url = chrome.runtime.getURL(`_locales/${lang}/messages.json`);
    const res = await fetch(url);
    uiLocales = await res.json();
    document.querySelectorAll('[data-i18n]').forEach(el => {
      const key = el.getAttribute('data-i18n');
      if (uiLocales[key]) {
        if (el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT' && el.type === 'text')) {
          el.placeholder = uiLocales[key].message;
        } else {
          el.innerHTML = uiLocales[key].message;
        }
      }
    });
  } catch (e) {
    console.error('Translation error:', e);
  }
}
'''
js = js.replace('// --- Storage helpers ---', trans_code)

# 2. Update loadSavedData
load_old = '''  // Settings
  const settings = await localGet('localSettings', {});
  document.getElementById('maxKeywords').value = settings.maxKeywords || 35;
  document.getElementById('language').value = settings.language || 'en';'''

load_new = '''  // Settings
  const settings = await localGet('localSettings', {});
  document.getElementById('maxKeywords').value = settings.maxKeywords || 35;
  document.getElementById('language').value = settings.language || 'en';
  
  const defaultUiLang = chrome.i18n.getUILanguage().startsWith('id') ? 'id' : 'en';
  const uiLang = settings.uiLanguage || defaultUiLang;
  const uiLangSelect = document.getElementById('uiLanguage');
  if (uiLangSelect) uiLangSelect.value = uiLang;
  applyTranslations(uiLang);'''
js = js.replace(load_old, load_new)

# 3. Update saveSettings
save_old = '''    maxKeywords: parseInt(document.getElementById('maxKeywords').value) || 35,
    language: document.getElementById('language').value || 'en',
    // Auto fill'''

save_new = '''    maxKeywords: parseInt(document.getElementById('maxKeywords').value) || 35,
    language: document.getElementById('language').value || 'en',
    uiLanguage: document.getElementById('uiLanguage') ? document.getElementById('uiLanguage').value : 'id',
    // Auto fill'''
js = js.replace(save_old, save_new)

# 4. Update settingIds
settingIds_old = "  'maxKeywords', 'language', 'autoCategory', 'autoFileType', 'defaultNo', 'defaultAi', 'minTitleLength', 'enableSmartUpload', 'syncEmail'"
settingIds_new = "  'maxKeywords', 'language', 'uiLanguage', 'autoCategory', 'autoFileType', 'defaultNo', 'defaultAi', 'minTitleLength', 'enableSmartUpload', 'syncEmail'"
js = js.replace(settingIds_old, settingIds_new)

# 5. Add event listener for uiLanguage to apply immediately
event_code = '''settingIds.forEach(id => {
  const el = document.getElementById(id);
  if (el) el.addEventListener('change', saveSettings);
});

const uiLangEl = document.getElementById('uiLanguage');
if (uiLangEl) {
  uiLangEl.addEventListener('change', (e) => {
    applyTranslations(e.target.value);
  });
}'''
js = js.replace('''settingIds.forEach(id => {
  const el = document.getElementById(id);
  if (el) el.addEventListener('change', saveSettings);
});''', event_code)

with open('localSetup.js', 'w', encoding='utf-8') as f:
    f.write(js)

print('Updated localSetup.js')
