# Fix 2: loadAPIsCredentials — add loading of global config values (Claude, Meta, Google)
# + add loadGlobalConfig() function that reads from a new endpoint get-config.php

with open("public_html/supercerebro/js/app.js", "r") as f:
    content = f.read()

old = """async function loadAPIsCredentials(clientId) {
  try {
    const r = await fetch(`api/get-credentials.php?client_id=${clientId}`).then(x => x.json());
    if (!r.ok) return;
    const wp = r.credentials?.wordpress || {};
    if (wp.wp_url)  { const el = document.getElementById('wp-url');  if (el) el.value = wp.wp_url; }
    if (wp.wp_user) { const el = document.getElementById('wp-user'); if (el) el.value = wp.wp_user; }
  } catch(e) {}
}"""

new = """async function loadAPIsCredentials(clientId) {
  try {
    const r = await fetch(`api/get-credentials.php?client_id=${clientId}`).then(x => x.json());
    if (!r.ok) return;
    const wp = r.credentials?.wordpress || {};
    if (wp.wp_url)  { const el = document.getElementById('wp-url');  if (el) el.value = wp.wp_url; }
    if (wp.wp_user) { const el = document.getElementById('wp-user'); if (el) el.value = wp.wp_user; }
    const sh = r.credentials?.shopify || {};
    if (sh.shop_domain) { const el = document.getElementById('shopify-domain'); if (el) el.value = sh.shop_domain; }
  } catch(e) {}
  // Load global config values (Claude, Meta, Google) into their input fields
  try {
    const g = await fetch('api/get-config.php').then(x => x.json());
    if (!g.ok) return;
    const set = (id, val) => { const el = document.getElementById(id); if (el && val) el.placeholder = val.slice(0,6) + '••••••••••••'; };
    set('claude-key',  g.claude_key_hint);
    set('meta-tok',    g.meta_token_hint);
    set('meta-app',    g.meta_app_id);
    set('g-tok',       g.google_dev_token_hint);
    set('g-oauth-cid', g.google_client_id);
    set('g-mcc-id',    g.google_mcc_id);
    // Show "ya configurado" badges
    if (g.claude_key_hint) { const el=document.getElementById('s-claude'); if(el&&!el.textContent) { el.style.color='var(--g)'; el.textContent='✓ API Key configurada'; } }
    if (g.meta_token_hint) { const el=document.getElementById('s-meta');   if(el&&!el.textContent) { el.style.color='var(--g)'; el.textContent='✓ Token configurado';   } }
    if (g.google_dev_token_hint) { const el=document.getElementById('s-google'); if(el&&!el.textContent) { el.style.color='var(--g)'; el.textContent='✓ Credenciales configuradas'; } }
  } catch(e) {}
}"""

if old in content:
    content = content.replace(old, new, 1)
    with open("public_html/supercerebro/js/app.js", "w") as f:
        f.write(content)
    print("OK fix 2: loadAPIsCredentials updated with shopify + global config hints")
else:
    print("ERROR fix 2: loadAPIsCredentials anchor not found")
