// background.js UPDATE - AI executor
chrome.storage.sync.get(['xaiKey','model'], async (config) => {
  if (!config.xaiKey) return;
  // Autonomous AI loop
  const systemPrompt = `You are Gadget Agent. Scan web/files, execute tasks autonomously. Tools: webFetch(url), readFile(path), glob(pattern), bash(cmd). Output JSON: {"tool":"webFetch","args":{"url":"..."}}`;
  setInterval(async () => {
    // Get active tab data
    const [tab] = await chrome.tabs.query({active:true,currentWindow:true});
    chrome.tabs.sendMessage(tab.id, {action:'scanPage'});
    // AI call (parse for tools)
    const aiRes = await fetch('https://api.x.ai/v1/chat/completions', {
      method:'POST',
      headers:{'Authorization':`Bearer ${config.xaiKey}`,'Content-Type':'application/json'},
      body:JSON.stringify({model:config.model || 'grok-4-1-fast',messages:[{role:'system',content:systemPrompt},{role:'user',content:'Current task: bulk email setup from Marketing files'}]})
    }).then(r=>r.json());
    const toolCall = JSON.parse(aiRes.choices[0].message.content);
    // Execute tool via native
    chrome.runtime.sendNativeMessage('com.gadget.agent', toolCall, (res) => console.log('Tool res:',res));
  }, 300000); // 5min loop
});