import { createLogger } from './render_prescript/utils/logger';
import { initialize } from './render_prescript/index';
import { messageInvoke } from '../utils/invoke';
import { ServiceFunc } from '../types/index';

const logger = createLogger('McpInjector');

// 1. Setup minimal Chat GPT adapter
const simpleGptAdapter = {
  capabilities: ['text-insertion', 'form-submission', 'dom-manipulation'],
  insertText: async (text: string): Promise<boolean> => {
    // Quick insertion logic
    const input = document.querySelector('#prompt-textarea') || document.querySelector('.ProseMirror[contenteditable="true"]');
    if (!input) return false;
    
    // Check if it's text area
    if (input.tagName.toLowerCase() === 'textarea') {
      const textarea = input as HTMLTextAreaElement;
      textarea.value += '\n' + text;
      textarea.dispatchEvent(new Event('input', { bubbles: true }));
      return true;
    } 
    
    // Handle prosemirror text addition
    if (input.innerHTML === '<p><br></p>') {
      input.innerHTML = `<p>${text}</p>`;
    } else {
      input.innerHTML += `<p>${text}</p>`;
    }
    input.dispatchEvent(new Event('input', { bubbles: true }));
    // Wait briefly, then optionally submit
    setTimeout(() => {
       const submitBtn = document.querySelector('button[data-testid="send-button"]') as HTMLButtonElement;
       if (submitBtn) submitBtn.click();
    }, 100);
    return true;
  }
};

// 2. Setup MCP Client Proxy
export async function setupMcpClient() {
  logger.info('Setting up MCP Client Proxy in Webview Content Script...');
  
  // Expose adapter globally so `render_prescript` can pick it up
  (window as any).mcpAdapter = simpleGptAdapter;
  
  // Provide the global interface required by render_prescript and components
  // Look at render_prescript/renderer/components.ts -> useTool()
  // It calls `(window as any).mcpClient.callTool(name, payload)`
  (window as any).mcpClient = {
    callTool: async (toolName: string, args: Record<string, any>) => {
      logger.info(`Proxying tool call: ${toolName}`, args);
      // Let's call the bg script
      try {
           const result = await messageInvoke.invoke({
               func: ServiceFunc.mcpExecuteTool,
               args: [{ name: toolName, args }]
           });
           return result;
      } catch(e) {
           logger.error(`Error calling ${toolName}`, e);
           throw e;
      }
    },
    getTools: async () => {
         const result = await messageInvoke.invoke({
             func: ServiceFunc.mcpGetTools,
             args: []
         });
         return result;
    }
  };
  
  // 3. Initialize the renderer
  initialize();
  logger.info('MCP execution UI injected!');
}
