const TOOL_DEFINITIONS = [
  {
    name: 'read_page',
    description: 'Liest den Inhalt der aktuell geöffneten Webseite. Gibt den Textinhalt, Titel und URL zurück.',
    parameters: {
      type: 'object',
      properties: {
        selector: {
          type: 'string',
          description: 'Optional: CSS-Selector um nur ein bestimmtes Element zu lesen'
        },
        include_html: {
          type: 'boolean',
          description: 'Falls true, wird HTML anstatt nur Text zurückgegeben',
          default: false
        }
      }
    }
  },
  {
    name: 'read_selection',
    description: 'Liest den aktuell vom User markierten Text auf der Seite.',
    parameters: {
      type: 'object',
      properties: {}
    }
  },
  {
    name: 'write_dom',
    description: 'Schreibt Text oder HTML in ein DOM-Element auf der Seite.',
    parameters: {
      type: 'object',
      properties: {
        selector: {
          type: 'string',
          description: 'CSS-Selector des Ziel-Elements'
        },
        content: {
          type: 'string',
          description: 'Text oder HTML der eingefuegt werden soll'
        },
        mode: {
          type: 'string',
          enum: ['replace', 'append', 'prepend'],
          description: 'Wie der Inhalt eingefuegt wird',
          default: 'append'
        }
      },
      required: ['selector', 'content']
    }
  },
  {
    name: 'execute_js',
    description: 'Fuehrt JavaScript-Code im Kontext der aktuellen Webseite aus.',
    parameters: {
      type: 'object',
      properties: {
        code: {
          type: 'string',
          description: 'Der JavaScript-Code der ausgefuehrt werden soll'
        }
      },
      required: ['code']
    }
  },
  {
    name: 'fill_form',
    description: 'Fuellt ein Formularfeld mit einem Wert aus.',
    parameters: {
      type: 'object',
      properties: {
        selector: {
          type: 'string',
          description: 'CSS-Selector des Formularfelds'
        },
        value: {
          type: 'string',
          description: 'Der Wert der eingetragen werden soll'
        }
      },
      required: ['selector', 'value']
    }
  },
  {
    name: 'click_element',
    description: 'Klickt auf ein Element auf der Webseite.',
    parameters: {
      type: 'object',
      properties: {
        selector: {
          type: 'string',
          description: 'CSS-Selector des Elements das geklickt werden soll'
        }
      },
      required: ['selector']
    }
  },
  {
    name: 'take_screenshot',
    description: 'Macht einen Screenshot des aktuell sichtbaren Bereichs der Webseite.',
    parameters: {
      type: 'object',
      properties: {
        analyze: {
          type: 'boolean',
          description: 'Falls true, wird der Screenshot analysiert und beschrieben',
          default: true
        }
      }
    }
  },
  {
    name: 'search_web',
    description: 'Sucht im Web mit Google nach einem Suchbegriff.',
    parameters: {
      type: 'object',
      properties: {
        query: {
          type: 'string',
          description: 'Der Suchbegriff'
        },
        num_results: {
          type: 'number',
          description: 'Anzahl der Ergebnisse (1-10)',
          default: 5
        }
      },
      required: ['query']
    }
  },
  {
    name: 'run_terminal',
    description: 'Fuehrt einen Shell/Terminal-Befehl auf dem lokalen Rechner aus. Benoetigt den Native Messaging Host.',
    parameters: {
      type: 'object',
      properties: {
        command: {
          type: 'string',
          description: 'Der Shell-Befehl der ausgefuehrt werden soll'
        },
        timeout: {
          type: 'number',
          description: 'Timeout in Millisekunden (default: 30000)',
          default: 30000
        }
      },
      required: ['command']
    }
  },
  {
    name: 'get_tab_info',
    description: 'Gibt Informationen ueber den aktuellen Tab zurueck: URL, Titel, etc.',
    parameters: {
      type: 'object',
      properties: {}
    }
  },
  {
    name: 'navigate_tab',
    description: 'Navigiert den aktuellen Tab zu einer neuen URL.',
    parameters: {
      type: 'object',
      properties: {
        url: {
          type: 'string',
          description: 'Die Ziel-URL'
        }
      },
      required: ['url']
    }
  },
  {
    name: 'manage_tabs',
    description: 'Verwaltet Browser-Tabs: oeffnen, schliessen, wechseln.',
    parameters: {
      type: 'object',
      properties: {
        action: {
          type: 'string',
          enum: ['open', 'close', 'switch', 'list'],
          description: 'Die Aktion die ausgefuehrt werden soll'
        },
        url: {
          type: 'string',
          description: 'URL fuer "open" Aktion'
        },
        tab_id: {
          type: 'number',
          description: 'Tab-ID fuer "switch" oder "close" Aktion'
        }
      },
      required: ['action']
    }
  }
];

async function executeTool(name, args, sender) {
  switch (name) {
    case 'read_page':
      return await executeReadPage(args, sender);
    case 'read_selection':
      return await executeReadSelection(sender);
    case 'write_dom':
      return await executeWriteDom(args, sender);
    case 'execute_js':
      return await executeJs(args, sender);
    case 'fill_form':
      return await executeFillForm(args, sender);
    case 'click_element':
      return await executeClickElement(args, sender);
    case 'take_screenshot':
      return await executeScreenshot(args, sender);
    case 'search_web':
      return await executeSearchWeb(args);
    case 'run_terminal':
      return await executeTerminal(args);
    case 'get_tab_info':
      return await executeGetTabInfo(sender);
    case 'navigate_tab':
      return await executeNavigateTab(args, sender);
    case 'manage_tabs':
      return await executeManageTabs(args);
    default:
      return { error: `Unknown tool: ${name}` };
  }
}

async function executeReadPage(args, sender) {
  const tabId = sender?.tab?.id;
  if (!tabId) return { error: 'Kein aktiver Tab' };
  const results = await chrome.scripting.executeScript({
    target: { tabId },
    func: (selector, includeHtml) => {
      if (selector) {
        const el = document.querySelector(selector);
        if (!el) return { error: `Element nicht gefunden: ${selector}` };
        return includeHtml ? el.innerHTML : el.innerText;
      }
      return {
        title: document.title,
        url: window.location.href,
        content: document.body.innerText.substring(0, 50000)
      };
    },
    args: [args.selector || null, !!args.include_html]
  });
  return results[0]?.result || { error: 'Konnte Seite nicht lesen' };
}

async function executeReadSelection(sender) {
  const tabId = sender?.tab?.id;
  if (!tabId) return { error: 'Kein aktiver Tab' };
  const results = await chrome.scripting.executeScript({
    target: { tabId },
    func: () => window.getSelection()?.toString() || ''
  });
  return { selection: results[0]?.result || '' };
}

async function executeWriteDom(args, sender) {
  const tabId = sender?.tab?.id;
  if (!tabId) return { error: 'Kein aktiver Tab' };
  const results = await chrome.scripting.executeScript({
    target: { tabId },
    func: (selector, content, mode) => {
      const el = document.querySelector(selector);
      if (!el) return { error: `Element nicht gefunden: ${selector}` };
      if (mode === 'replace') el.innerHTML = content;
      else if (mode === 'prepend') el.insertAdjacentHTML('afterbegin', content);
      else el.insertAdjacentHTML('beforeend', content);
      return { success: true };
    },
    args: [args.selector || '', args.content || '', args.mode || 'append']
  });
  return results[0]?.result;
}

  async function executeJs(args, sender) {
    const tabId = sender?.tab?.id;
    if (!tabId) return { error: 'Kein aktiver Tab' };
    try {
      const allowedGlobals = ['document', 'window', 'console', 'location', 'history', 'navigator'];
      const results = await chrome.scripting.executeScript({
        target: { tabId },
        func: (code) => {
          try {
            const fn = new Function('document', 'window', 'console', 'location', 'history', 'navigator', `return (${code})`);
            return { result: fn(document, window, console, location, history, navigator) };
          } catch (e) {
            return { error: e.message };
          }
        },
        args: [args.code || '']
      });
      return results[0]?.result || { error: 'Kein Ergebnis' };
    } catch (e) {
      return { error: e.message };
    }
  }

async function executeFillForm(args, sender) {
  const tabId = sender?.tab?.id;
  if (!tabId) return { error: 'Kein aktiver Tab' };
  const results = await chrome.scripting.executeScript({
    target: { tabId },
    func: (selector, value) => {
      const el = document.querySelector(selector);
      if (!el) return { error: `Element nicht gefunden: ${selector}` };
      const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set
        || Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')?.set;
      if (nativeInputValueSetter) {
        nativeInputValueSetter.call(el, value);
        el.dispatchEvent(new Event('input', { bubbles: true }));
        el.dispatchEvent(new Event('change', { bubbles: true }));
      } else {
        el.value = value;
      }
      return { success: true };
    },
    args: [args.selector || '', args.value || '']
  });
  return results[0]?.result;
}

async function executeClickElement(args, sender) {
  const tabId = sender?.tab?.id;
  if (!tabId) return { error: 'Kein aktiver Tab' };
  const results = await chrome.scripting.executeScript({
    target: { tabId },
    func: (selector) => {
      const el = document.querySelector(selector);
      if (!el) return { error: `Element nicht gefunden: ${selector}` };
      el.click();
      return { success: true };
    },
    args: [args.selector || '']
  });
  return results[0]?.result;
}

async function executeScreenshot(args, sender) {
  const tabId = sender?.tab?.id;
  if (!tabId) return { error: 'Kein aktiver Tab' };
  try {
    const tab = await chrome.tabs.get(tabId);
    const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, { format: 'png' });
    return { success: true, screenshot: dataUrl, analyze: args.analyze !== false };
  } catch (e) {
    return { error: e.message };
  }
}

async function executeSearchWeb(args) {
  try {
    const { getSettings } = await import('./utils.js');
    const settings = await getSettings();
    if (!settings.googleSearchKey || !settings.googleSearchCx) {
      return { error: 'Google Custom Search nicht konfiguriert. Bitte API Key und CX in Settings eintragen.' };
    }
    const url = `https://www.googleapis.com/customsearch/v1?key=${settings.googleSearchKey}&cx=${settings.googleSearchCx}&q=${encodeURIComponent(args.query)}&num=${args.num_results || 5}`;
    const response = await fetch(url);
    if (!response.ok) {
      return { error: `Suche fehlgeschlagen: HTTP ${response.status}` };
    }
    const data = await response.json();
    const results = (data.items || []).map(item => ({
      title: item.title,
      url: item.link,
      snippet: item.snippet
    }));
    return { results, query: args.query };
  } catch (e) {
    return { error: e.message };
  }
}

async function executeTerminal(args) {
  try {
    const response = await chrome.runtime.sendNativeMessage('com.syntrix.nova', {
      command: args.command,
      timeout: args.timeout || 30000
    });
    return response;
  } catch (e) {
    if (e.message.includes('could not be started') || e.message.includes('native messaging host')) {
      return { error: 'Native Messaging Host nicht installiert. Bitte native-host/install.bat ausfuehren.' };
    }
    return { error: e.message };
  }
}

async function executeGetTabInfo(sender) {
  const tabId = sender?.tab?.id;
  if (!tabId) return { error: 'Kein aktiver Tab' };
  try {
    const tab = await chrome.tabs.get(tabId);
    return { url: tab.url, title: tab.title, id: tab.id, status: tab.status };
  } catch (e) {
    return { error: e.message };
  }
}

async function executeNavigateTab(args, sender) {
  const tabId = sender?.tab?.id;
  if (!tabId) return { error: 'Kein aktiver Tab' };
  try {
    await chrome.tabs.update(tabId, { url: args.url });
    return { success: true, url: args.url };
  } catch (e) {
    return { error: e.message };
  }
}

async function executeManageTabs(args) {
  try {
    switch (args.action) {
      case 'open':
        const tab = await chrome.tabs.create({ url: args.url, active: true });
        return { success: true, tabId: tab.id };
      case 'close':
        if (args.tab_id) await chrome.tabs.remove(args.tab_id);
        return { success: true };
      case 'switch':
        if (args.tab_id) await chrome.tabs.update(args.tab_id, { active: true });
        return { success: true };
      case 'list': {
        const tabs = await chrome.tabs.query({});
        return tabs.map(t => ({ id: t.id, title: t.title, url: t.url, active: t.active }));
      }
      default:
        return { error: `Unbekannte Aktion: ${args.action}` };
    }
  } catch (e) {
    return { error: e.message };
  }
}

export { TOOL_DEFINITIONS, executeTool };
