// Zeq Mathematical Framework - Grok (X/Twitter) Content Script
// Intercepts Grok input and enriches queries with server-side mathematical state

(function() {
  'use strict';

  async function fetchPhase() {
    try {
      return await new Promise((resolve) => {
        chrome.runtime.sendMessage({ type: 'getState' }, (response) => {
          if (chrome.runtime.lastError || !response) { resolve(null); return; }
          resolve(response);
        });
      });
    } catch(e) { return null; }
  }

  let settings = { enabled: true };

  try {
    if (typeof chrome !== 'undefined' && chrome.runtime) {
      chrome.runtime.sendMessage({ action: 'getSettings' }, (response) => {
        if (chrome.runtime.lastError) {
          settings = { enabled: true, platforms: { grok: true } };
        } else if (response) {
          settings = response;
        }
      });
    } else {
      settings = { enabled: true, platforms: { grok: true } };
    }
  } catch (error) {
    settings = { enabled: true, platforms: { grok: true } };
  }

  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'settingsUpdated') {
      settings = request.settings;
      sendResponse({ success: true });
      return false;
    }
    if (request.action === 'getTransparencyStats') {
      sendResponse({ stats: { interactions: 0, verificationRate: '--' } });
      return false;
    }
    if (request.action === 'downloadTransparencyJSON') {
      sendResponse({ success: false, error: 'Transparency logger not available' });
      return false;
    }
    return false;
  });

  async function buildMathPrompt(originalMessage) {
    if (!settings.enabled || !settings.platforms?.grok) return originalMessage;
    try {
      var phaseData = await fetchPhase();
      var sys = '{"zeq_os":{"version":"1.287.6","pulse":"1.287 Hz","operators":"1,500+ catalogued"';
      if (phaseData) {
        sys += ',"phase":' + (phaseData.phase || 0);
        sys += ',"ko42":' + (phaseData.ko42 || 0);
      }
      sys += '},"query":"' + originalMessage.replace(/"/g, '\\"').substring(0, 500) + '"}';
      return sys;
    } catch (error) {
      return originalMessage;
    }
  }

  window.addEventListener('message', async (event) => {
    if (event.source !== window) return;
    if (event.data && event.data.type === 'ZEQ_PROCESS_REQUEST') {
      if (!settings.enabled || !settings.platforms?.grok) {
        window.postMessage({ type: 'ZEQ_PROCESSED_RESPONSE', requestId: event.data.requestId, processedContent: event.data.originalContent }, '*');
        return;
      }
      try {
        const processed = await buildMathPrompt(event.data.originalContent);
        window.postMessage({ type: 'ZEQ_PROCESSED_RESPONSE', requestId: event.data.requestId, processedContent: processed }, '*');
      } catch (error) {
        window.postMessage({ type: 'ZEQ_PROCESSED_RESPONSE', requestId: event.data.requestId, processedContent: event.data.originalContent }, '*');
      }
    }
  });

  function injectNetworkInterception() {
    if (window.zeqGrokInterceptionInjected) return;
    try {
      if (typeof chrome === 'undefined' || !chrome.runtime) return;
      const script = document.createElement('script');
      script.src = chrome.runtime.getURL('content/grok-page-context.js');
      script.onload = () => { window.zeqGrokInterceptionInjected = true; script.remove(); };
      script.onerror = () => {};
      (document.head || document.documentElement).appendChild(script);
    } catch (e) {}
  }

  injectNetworkInterception();
  document.addEventListener('DOMContentLoaded', injectNetworkInterception);

  const observer = new MutationObserver(() => {});
  if (document.body) {
    observer.observe(document.body, { childList: true, subtree: true });
  } else {
    document.addEventListener('DOMContentLoaded', () => {
      observer.observe(document.body, { childList: true, subtree: true });
    });
  }

})();
