import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
import type { McpSseConfig } from './client'
import type { CallToolResultPayload, McpTool } from './types'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'
import { McpClient } from './client'

/**
 * MCP SSE Client
 *
 * Responsibilities:
 * - Manage deprecated HTTP+SSE MCP transport for a single MCP server
 * - Retrieve and call tools via MCP protocol
 * - Implement McpClient interface for shared runtime usage
 */
export class McpSseClient extends McpClient {
  private client?: Client
  private cachedTools: McpTool[] = []
  private _connected = false
  private lastError?: string

  constructor(public readonly config: McpSseConfig) {
    super()
    if (this._enableLogging) {
      console.warn(`🔌 McpSseClient created for: ${config.name}`)
    }
  }

  get connected(): boolean {
    return this._connected && !!this.client
  }

  async initialize(): Promise<void> {
    if (this._connected) {
      return
    }

    try {
      this.client = await this.createClient()
      await this.refreshToolCache()
      this._connected = true
      this.lastError = undefined
      if (this._enableLogging) {
        console.warn(
          `✅ McpSseClient initialized: ${this.config.name} (${this.cachedTools.length} tools)`,
        )
      }
    }
    catch (error) {
      const msg = error instanceof Error ? error.message : String(error)
      this.lastError = msg
      if (this._enableLogging) {
        console.error(
          `Failed to initialize SSE MCP client "${this.config.name}":`,
          msg,
        )
      }
      throw error
    }
  }

  private async createClient(): Promise<Client> {
    const headers: Record<string, string> = { ...this.config.headers }

    if (this.config.auth?.type === 'bearer') {
      const token
        = typeof this.config.auth.token === 'function'
          ? this.config.auth.token()
          : this.config.auth.token
      if (token)
        headers.Authorization = `Bearer ${token}`
    }

    const transport = new SSEClientTransport(
      new URL(this.config.url),
      Object.keys(headers).length > 0
        ? {
            eventSourceInit: {
              fetch: (input, init) =>
                fetch(input, {
                  ...init,
                  headers: {
                    ...(init.headers as Record<string, string> | undefined),
                    ...headers,
                  },
                }),
            },
            requestInit: { headers },
          }
        : undefined,
    )

    const client = new Client(
      {
        name: `mcp-sse-client-${this.config.name}`,
        version: '1.0.0',
      },
      {
        capabilities: {
          roots: {},
          sampling: {},
        },
      },
    )

    await client.connect(transport)
    if (this._enableLogging) {
      console.warn(
        `🔗 Connected to SSE MCP server: ${this.config.name} at ${this.config.url}`,
      )
    }

    return client
  }

  private async refreshToolCache(): Promise<void> {
    if (!this.client) {
      throw new Error('Client not initialized. Call initialize() first.')
    }

    try {
      const response = await this.client.listTools()
      const tools = response.tools || []

      this.cachedTools = tools.map(tool => ({
        name: tool.name,
        title: tool.title,
        description: tool.description,
        inputSchema: tool.inputSchema as any,
      }))

      if (this._enableLogging) {
        console.warn(
          `🔄 Refreshed tool cache for ${this.config.name}: ${this.cachedTools.length} tools`,
        )
      }
    }
    catch (error) {
      const msg = error instanceof Error ? error.message : String(error)
      if (this._enableLogging) {
        console.error(
          `Failed to refresh tool cache for "${this.config.name}":`,
          msg,
        )
      }
      throw error
    }
  }

  async listTools(): Promise<McpTool[]> {
    if (!this._connected) {
      if (this._enableLogging) {
        console.warn(
          `McpSseClient "${this.config.name}" not initialized, returning cached tools`,
        )
      }
      return this.cachedTools
    }

    try {
      await this.refreshToolCache()
    }
    catch (error) {
      if (this._enableLogging) {
        console.warn(`Failed to refresh tools, returning cached: ${error}`)
      }
    }

    return this.cachedTools
  }

  async callTool(
    name: string,
    args: Record<string, unknown>,
  ): Promise<CallToolResultPayload> {
    if (!this.client) {
      throw new Error(
        `SSE MCP client for "${this.config.name}" not initialized. Call initialize() first.`,
      )
    }

    if (this._enableLogging) {
      console.warn(`🔧 Invoking SSE MCP tool: ${this.config.name}/${name}`, {
        args,
      })
    }

    try {
      const result = await this.client.callTool({
        name,
        arguments: args,
      })

      return result as CallToolResult
    }
    catch (error) {
      const msg = error instanceof Error ? error.message : String(error)
      this.lastError = msg
      if (this._enableLogging) {
        console.error(
          `Failed to invoke SSE MCP tool "${this.config.name}/${name}": ${msg}`,
        )
      }
      throw error
    }
  }

  async disconnect(): Promise<void> {
    if (this.client) {
      try {
        await this.client.close()
        if (this._enableLogging) {
          console.warn(`🔌 Closed SSE MCP client: ${this.config.name}`)
        }
      }
      catch (error) {
        if (this._enableLogging) {
          console.error(
            `Error closing SSE MCP client "${this.config.name}":`,
            error instanceof Error ? error.message : error,
          )
        }
      }
      this.client = undefined
    }
    this._connected = false
    this.cachedTools = []
  }

  getStatus() {
    return {
      connected: this._connected,
      toolCount: this.cachedTools.length,
      error: this.lastError,
    }
  }
}
