/**
 * MCP Bridge — Exposes McpService to content script via window.__n8nMcpBridge
 *
 * The renderer calls window.__n8nMcpBridge.callTool(name, args) when user clicks "Run".
 * This bridge delegates to the background script's McpService via chrome.runtime messaging.
 */
import { createLogger } from "./logger"

const logger = createLogger("McpBridge")

export interface McpBridge {
  callTool(name: string, args: Record<string, any>): Promise<any>
  isConnected(): boolean
}

/**
 * Create and expose the MCP bridge on window.__n8nMcpBridge
 * Content scripts can't directly access McpService (lives in background),
 * so we relay calls through chrome.runtime.sendMessage
 */
export function initializeBridge(): McpBridge {
  const bridge: McpBridge = {
    async callTool(name: string, args: Record<string, any>): Promise<any> {
      // ★ Auto-attach workflow context if available
      const ctx = (window as any).__n8nWorkflowContext
      if (ctx?.workflowId && !args.workflow_id) {
        args = { ...args, workflow_id: ctx.workflowId }
        logger.info(`Auto-attached workflow_id: ${ctx.workflowId}`)
      }

      logger.info(`Calling tool: ${name}`, args)

      return new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(
          {
            type: "n8n-mcp:call-tool",
            toolName: name,
            args: args,
          },
          (response) => {
            if (chrome.runtime.lastError) {
              const err = chrome.runtime.lastError.message || "Extension communication error"
              logger.error(`Bridge error: ${err}`)
              reject(new Error(err))
              return
            }

            if (response?.success) {
              logger.info(`Tool ${name} succeeded`)
              resolve(response.result)
            } else {
              const errMsg = response?.error || "Unknown error"
              logger.error(`Tool ${name} failed: ${errMsg}`)
              reject(new Error(errMsg))
            }
          }
        )
      })
    },

    isConnected(): boolean {
      // Check via sync message (best effort)
      return true // Will fail gracefully when callTool is invoked
    },
  }

  // Expose globally for renderer access
  ;(window as any).__n8nMcpBridge = bridge
  logger.info("MCP bridge initialized on window.__n8nMcpBridge")

  return bridge
}

/**
 * Background script handler — add this listener in bg/index.ts
 * Receives "n8n-mcp:call-tool" messages and delegates to McpService
 */
export function createBackgroundHandler(mcpService: any) {
  return function handleMcpBridgeMessage(
    message: any,
    _sender: chrome.runtime.MessageSender,
    sendResponse: (response: any) => void
  ): boolean | void {
    if (message.type !== "n8n-mcp:call-tool") return

    const { toolName, args } = message
    logger.info(`[BG] Received tool call: ${toolName}`)

    mcpService
      .callTool(toolName, args)
      .then((result: any) => {
        sendResponse({ success: true, result })
      })
      .catch((err: any) => {
        sendResponse({
          success: false,
          error: err instanceof Error ? err.message : String(err),
        })
      })

    return true // Async response
  }
}
