/**
 * 通用HTTP客户端主类 - 重构版本
 *
 * 重构后的HTTP客户端，基于新的HttpClientCore架构，
 * 提供向后兼容的API同时使用模块化的核心组件。
 *
 * 按照constitution要求，从libs/http-client迁移并模块化集成
 */

import { EventEmitter } from 'events'

import type {
  HttpClientRequest,
  HttpClientResponse,
  BatchRequestOptions,
  BatchResult,
  UniversalHttpClientConfig,
  PerformanceOptimizationConfig,
  OptimizationStats,
  CacheStats,
  ConnectionPoolStats,
} from '@/types/httpClient'
import type { PlatformConfig, IPlatformAdapter } from '@/types/platformAdapter'
import type { IUniversalHttpClient, HealthStatus } from '@/types/httpClientCore'

import { HttpClientCore } from '@/core/http-client/HttpClientCore'
import { PlatformAdapterFactory } from '@/core/http-client/PlatformAdapterFactory'
import { AccountRegistry, globalAccountRegistry } from '@/core/http-client/AccountRegistry'
import { HttpClient } from './httpClient'

// Compatibility interfaces
interface PlatformRegistrationResult {
  success: boolean
  platformName: string
  adapter?: IPlatformAdapter
  error?: string
}

interface ProxyConfigurationResult {
  success: boolean
  proxyUrl?: string
  authConfigured?: boolean
  customHeaders?: boolean
  accountId?: string
  error?: string
}

export class UniversalHttpClient extends EventEmitter implements IUniversalHttpClient {
  private readonly core: HttpClientCore
  private readonly config: UniversalHttpClientConfig
  private readonly accountRegistry: AccountRegistry
  private optimizationEnabled = false
  private optimizationStats: OptimizationStats = {
    totalOptimizations: 0,
    routingDecisions: 0,
    performanceImprovement: 0,
    strategiesUsed: [],
    lastOptimization: new Date(),
  }

  constructor(config: UniversalHttpClientConfig = {}, accountRegistry?: AccountRegistry) {
    super()
    this.config = config
    this.accountRegistry = accountRegistry || globalAccountRegistry
    this.core = new HttpClientCore(config, this.accountRegistry)

    // Setup event forwarding from core to this instance
    this.setupEventForwarding()

    // Setup legacy event listeners
    this.setupEventListeners()
  }

  /**
   * Setup event forwarding from core to this instance
   */
  private setupEventForwarding(): void {
    // Forward core events to maintain compatibility
    this.core.on('request:start', (data) => this.emit('request:start', data))
    this.core.on('request:complete', (data) => this.emit('request:complete', data))
    this.core.on('request:error', (data) => this.emit('request:error', data))
    this.core.on('platform:registered', (data) => this.emit('platform:registered', data))
    this.core.on('cache:hit', (data) => this.emit('cache:hit', data))
    this.core.on('cache:miss', (data) => this.emit('cache:miss', data))
  }

  /**
   * 执行单个HTTP请求 - 委托给HttpClientCore
   */
  async request<T = any>(request: HttpClientRequest): Promise<HttpClientResponse<T>> {
    // Delegate to core implementation
    const response = await this.core.request<T>(request)

    // Update optimization stats
    this.updateOptimizationStats({
      requestId: response.metadata.requestId,
      duration: response.metadata.duration,
      success: response.ok
    })

    return response
  }

  /**
   * 执行批量HTTP请求 - 委托给HttpClientCore
   */
  async batchRequest<T = any>(
    requests: HttpClientRequest[],
    options: BatchRequestOptions = {},
  ): Promise<BatchResult<T>> {
    // Delegate to core implementation
    return this.core.batchRequest<T>(requests, options)
  }

  /**
   * 注册平台配置 - 兼容性方法
   */
  async registerPlatform(config: PlatformConfig): Promise<PlatformRegistrationResult>
  async registerPlatform(platform: string, adapter: IPlatformAdapter): Promise<void>
  async registerPlatform(
    configOrPlatform: PlatformConfig | string,
    adapter?: IPlatformAdapter
  ): Promise<PlatformRegistrationResult | void> {
    try {
      if (typeof configOrPlatform === 'string' && adapter) {
        // New API: register platform with adapter directly
        this.core.registerPlatform(configOrPlatform, adapter)
        return
      } else if (typeof configOrPlatform === 'object') {
        // Legacy API: register platform with config
        const config = configOrPlatform
        this.validatePlatformConfig(config)

        // Create platform adapter using factory
        const createdAdapter = await this.createPlatformAdapter(config.platform, config)

        // Register with core
        this.core.registerPlatform(config.platform, createdAdapter)

        return {
          success: true,
          platformName: config.platform,
          adapter: createdAdapter,
        }
      } else {
        throw new Error('Invalid arguments for registerPlatform')
      }
    } catch (error) {
      if (typeof configOrPlatform === 'object') {
        return {
          success: false,
          platformName: configOrPlatform.platform,
          error: error instanceof Error ? error.message : String(error),
        }
      }
      throw error
    }
  }

  /**
   * 获取客户端健康状态 - 委托给HttpClientCore
   */
  async getHealth(): Promise<HealthStatus> {
    return this.core.getHealth()
  }

  /**
   * 关闭客户端并释放资源 - 委托给HttpClientCore
   */
  async close(): Promise<void> {
    return this.core.close()
  }

  /**
   * 检查平台是否已注册 - 委托给HttpClientCore
   */
  isPlatformRegistered(platform: string): boolean {
    return this.core.isPlatformRegistered(platform)
  }

  /**
   * 获取平台适配器 - 委托给HttpClientCore
   */
  getPlatformAdapter(platform: string): IPlatformAdapter | undefined {
    return this.core.getPlatformAdapter(platform)
  }

  /**
   * 获取已注册平台列表 - 委托给HttpClientCore
   */
  getRegisteredPlatforms(): string[] {
    return this.core.getRegisteredPlatforms()
  }

  /**
   * 取消注册平台 - 委托给HttpClientCore
   */
  async unregisterPlatform(platform: string): Promise<{ success: boolean }> {
    return this.core.unregisterPlatform(platform)
  }

  /**
   * 更新平台配置 - 委托给HttpClientCore
   */
  async updatePlatformConfig(platform: string, config: Partial<PlatformConfig>): Promise<{ success: boolean }> {
    return this.core.updatePlatformConfig(platform, config)
  }

  /**
   * 获取平台信息 - 委托给HttpClientCore
   */
  getPlatformInfo(platform: string): PlatformConfig | undefined {
    return this.core.getPlatformInfo(platform)
  }

  /**
   * 配置全局代理 - 委托给HttpClientCore
   */
  async configureGlobalProxy(config: any): Promise<ProxyConfigurationResult> {
    try {
      const result = await this.core.configureGlobalProxy(config)

      // Emit event for compatibility
      this.emit('proxy:configured', { type: 'global', config })

      return {
        success: result.success,
        proxyUrl: result.proxyUrl,
        authConfigured: result.authConfigured,
        customHeaders: result.customHeaders,
        error: result.error
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error),
      }
    }
  }

  /**
   * 配置账户专用代理 - 委托给HttpClientCore
   */
  async configureAccountProxy(accountId: string, config: any): Promise<ProxyConfigurationResult> {
    try {
      const result = await this.core.configureAccountProxy(accountId, config)

      // Emit event for compatibility
      this.emit('proxy:configured', { type: 'account', config })

      return {
        success: result.success,
        accountId: result.accountId,
        proxyUrl: result.proxyUrl,
        authConfigured: result.authConfigured,
        customHeaders: result.customHeaders,
        error: result.error
      }
    } catch (error) {
      return {
        success: false,
        accountId,
        error: error instanceof Error ? error.message : String(error),
      }
    }
  }

  // Account Management Methods

  /**
   * Register account with credentials
   */
  registerAccount(
    platform: string,
    accountId: string,
    credentials: any,
    metadata?: { name?: string; description?: string }
  ): void {
    this.core.registerAccount(platform, accountId, credentials, metadata)
  }

  /**
   * Check if account is registered
   */
  hasAccount(platform: string, accountId: string): boolean {
    return this.core.hasAccount(platform, accountId)
  }

  /**
   * Get registered accounts
   */
  getRegisteredAccounts(): Array<{ platform: string; accountId: string; metadata?: any }> {
    return this.core.getRegisteredAccounts()
  }

  /**
   * Get account registry (for advanced usage)
   */
  getAccountRegistry(): AccountRegistry {
    return this.accountRegistry
  }

  /**
   * 启用性能优化
   */
  async enablePerformanceOptimization(config: PerformanceOptimizationConfig): Promise<void> {
    this.optimizationEnabled = true

    if (this.config.performanceMonitor) {
      // await this.config.performanceMonitor.enableOptimization(config);
    }

    this.emit('optimization:enabled', { config })
  }

  /**
   * 启用响应缓存
   */
  async enableResponseCaching(config: any): Promise<void> {
    // 实现响应缓存逻辑
    this.config.cache = { ...this.config.cache, ...config }
  }

  /**
   * 配置连接池
   */
  async configureConnectionPooling(config: any): Promise<void> {
    // 实现连接池配置逻辑
  }

  /**
   * 获取优化统计
   */
  getOptimizationStats(): OptimizationStats {
    return { ...this.optimizationStats }
  }

  /**
   * 获取缓存统计
   */
  getCacheStats(): CacheStats {
    const totalRequests = this.optimizationStats.totalOptimizations
    const hitCount = Array.from(this.requestCache.values()).length

    return {
      hitRate: totalRequests > 0 ? hitCount / totalRequests : 0,
      size: this.requestCache.size,
      totalHits: hitCount,
      totalMisses: totalRequests - hitCount,
      averageCachedResponseTime: 50, // 示例值
      memoryUsage: this.requestCache.size * 1024, // 估算值
    }
  }

  /**
   * 获取连接池统计
   */
  getConnectionPoolStats(): ConnectionPoolStats {
    return {
      activeConnections: this.activeRequests.size,
      idleConnections: 5, // 示例值
      totalConnections: this.activeRequests.size + 5,
      connectionReuse: this.optimizationStats.totalOptimizations,
      averageConnectionAge: 30000, // 30秒
      efficiency: 0.8, // 80%效率
    }
  }

  /**
   * 获取平台适配器
   */
  getPlatformAdapter(platform: string): IPlatformAdapter | undefined {
    return this.core.getPlatformAdapter(platform)
  }

  /**
   * 获取已注册平台列表
   */
  getRegisteredPlatforms(): string[] {
    return this.core.getRegisteredPlatforms()
  }

  /**
   * 检查平台是否已注册
   */
  isPlatformRegistered(platform: string): boolean {
    return this.core.isPlatformRegistered(platform)
  }

  /**
   * 取消注册平台
   */
  async unregisterPlatform(platform: string): Promise<{ success: boolean }> {
    return this.core.unregisterPlatform(platform)
  }

  /**
   * 更新平台配置
   */
  async updatePlatformConfig(platform: string, config: Partial<PlatformConfig>): Promise<{ success: boolean }> {
    return this.core.updatePlatformConfig(platform, config)
  }

  /**
   * 获取平台信息
   */
  getPlatformInfo(platform: string): PlatformConfig | undefined {
    return this.core.getPlatformInfo(platform)
  }

  // Private helper methods

  private setupEventListeners(): void {
    // Setup internal event listeners for legacy compatibility
    this.on('request:complete', data => {
      this.updateOptimizationStats(data)
    })
  }

  private validatePlatformConfig(config: PlatformConfig): void {
    if (!config.platform || !config.baseUrl || !config.authConfig?.type) {
      throw new Error('Invalid platform configuration: missing required fields')
    }

    const supportedAuthTypes = ['signature', 'apikey', 'bearer']
    if (!supportedAuthTypes.includes(config.authConfig.type)) {
      throw new Error(`Unsupported authentication type: ${config.authConfig.type}`)
    }
  }

  /**
   * Create platform adapter using factory - implements T026
   */
  private async createPlatformAdapter(platform: string, config: PlatformConfig): Promise<IPlatformAdapter> {
    try {
      // Ensure adapters are registered with factory
      this.ensureAdaptersRegistered()

      // Create adapter using PlatformAdapterFactory
      const adapter = PlatformAdapterFactory.createAdapter(platform, config)

      // Set up credential manager if available
      if (this.config.credentialManager) {
        adapter.setCredentialManager?.(this.config.credentialManager)
      }

      return adapter
    } catch (error) {
      throw new Error(`Failed to create platform adapter for ${platform}: ${error instanceof Error ? error.message : String(error)}`)
    }
  }

  /**
   * Ensure platform adapters are registered with the factory
   */
  private ensureAdaptersRegistered(): void {
    // Register adapters if not already registered
    if (!PlatformAdapterFactory.isAdapterRegistered('pacifica')) {
      // Dynamic import to avoid circular dependencies
      import('@/adapters/pacifica/PacificaHttpAdapter').then(({ PacificaHttpAdapter }) => {
        PlatformAdapterFactory.registerAdapter('pacifica', PacificaHttpAdapter)
      }).catch(() => {
        // Fallback - adapter may not be available
      })
    }

    if (!PlatformAdapterFactory.isAdapterRegistered('binance')) {
      import('@/adapters/binance/BinanceHttpAdapter').then(({ BinanceHttpAdapter }) => {
        PlatformAdapterFactory.registerAdapter('binance', BinanceHttpAdapter)
      }).catch(() => {
        // Fallback - adapter may not be available
      })
    }

    if (!PlatformAdapterFactory.isAdapterRegistered('aster')) {
      import('@/adapters/aster/AsterHttpAdapter').then(({ AsterHttpAdapter }) => {
        PlatformAdapterFactory.registerAdapter('aster', AsterHttpAdapter)
      }).catch(() => {
        // Fallback - adapter may not be available
      })
    }
  }


  private updateOptimizationStats(data: any): void {
    this.optimizationStats.totalOptimizations++

    if (data.success && data.duration < 100) {
      this.optimizationStats.performanceImprovement += 0.1
    }

    this.optimizationStats.lastOptimization = new Date()
  }
}

// 重新导出类型定义，从本地类型文件导入
export type {
  HttpClientRequest,
  HttpClientResponse,
  RequestOptions,
  TimeoutConfig,
  RetryConfig,
  ProxyControlOptions,
  ResponseMetadata,
  BatchRequestOptions,
  BatchResult,
  UniversalHttpClientConfig,
  OptimizationStats,
  CacheStats,
  ConnectionPoolStats,
} from '@/types/httpClient'

export type { PlatformConfig, IPlatformAdapter, PlatformRequest, PlatformResponse } from '@/types/platformAdapter'


/**
 * HttpClientAdapter - 适配现有HttpClient到新的UniversalHttpClient
 *
 * 这个适配器让现有代码可以无缝迁移到新的HTTP客户端库
 */
export class HttpClientAdapter {
  private universalClient: UniversalHttpClient
  private legacyClient: HttpClient

  constructor(config: UniversalHttpClientConfig = {}) {
    this.universalClient = new UniversalHttpClient(config)
    this.legacyClient = HttpClient.getInstance()
  }

  /**
   * 兼容旧版request方法
   */
  async request<T = any>(url: string, options: any = {}): Promise<T> {
    // 检查是否应该使用新的统一客户端
    if (options.platform && options.accountId) {
      // 使用新的统一客户端
      const request: HttpClientRequest = {
        platform: options.platform,
        accountId: options.accountId,
        method: options.method || 'GET',
        url: url,
        headers: options.headers,
        body: options.body,
        options: {
          timeout: options.timeout
            ? {
                connect: 5000,
                read: options.timeout,
                write: 15000,
              }
            : undefined,
          retry: options.retries
            ? {
                maxAttempts: options.retries,
                delay: options.retryDelay || 1000,
                exponentialBackoff: true,
              }
            : undefined,
          proxy: options.useProxy
            ? {
                enabled: true,
                strategy: 'global',
              }
            : undefined,
        },
      }

      const response = await this.universalClient.request(request)
      return response.data
    } else {
      // 使用传统HTTP客户端
      const response = await this.legacyClient.request(url, options)
      return response.data
    }
  }

  /**
   * 兼容旧版GET方法
   */
  async get<T = any>(url: string, options: any = {}): Promise<T> {
    return this.request<T>(url, { ...options, method: 'GET' })
  }

  /**
   * 兼容旧版POST方法
   */
  async post<T = any>(url: string, body?: any, options: any = {}): Promise<T> {
    return this.request<T>(url, { ...options, method: 'POST', body })
  }

  /**
   * 兼容旧版PUT方法
   */
  async put<T = any>(url: string, body?: any, options: any = {}): Promise<T> {
    return this.request<T>(url, { ...options, method: 'PUT', body })
  }

  /**
   * 兼容旧版DELETE方法
   */
  async delete<T = any>(url: string, options: any = {}): Promise<T> {
    return this.request<T>(url, { ...options, method: 'DELETE' })
  }

  /**
   * 注册平台
   */
  async registerPlatform(platform: string, config: PlatformConfig): Promise<void> {
    await this.universalClient.registerPlatform(config)
  }

  /**
   * 获取统一客户端实例（用于高级功能）
   */
  getUniversalClient(): UniversalHttpClient {
    return this.universalClient
  }

  /**
   * 获取传统客户端实例（向后兼容）
   */
  getLegacyClient(): HttpClient {
    return this.legacyClient
  }
}

/**
 * 全局HTTP客户端适配器实例
 */
export const httpClientAdapter = new HttpClientAdapter()

/**
 * 便捷函数：快速执行Pacifica API调用
 *
 * 这是一个简化的API调用函数，当平台适配器完全迁移后将提供完整功能
 */
export async function pacificaApiCall<T = any>(
  accountId: string,
  method: 'GET' | 'POST' | 'PUT' | 'DELETE',
  endpoint: string,
  data?: any,
  options?: any,
): Promise<T> {
  // 临时实现：直接使用HttpClient进行API调用
  // 当Pacifica适配器迁移完成后，将使用完整的平台适配器

  const httpClient = HttpClient.getInstance()
  const baseUrl = options?.baseUrl || 'https://api.pacifica.fi'
  const url = `${baseUrl}${endpoint}`

  const requestOptions = {
    method,
    headers: {
      'Content-Type': 'application/json',
      ...options?.headers,
    },
    body: data ? JSON.stringify(data) : undefined,
    timeout: options?.timeout || 10000,
  }

  try {
    const response = await httpClient.request(url, requestOptions)
    return response.data
  } catch (error) {
    throw new Error(`Pacifica API call failed: ${error instanceof Error ? error.message : String(error)}`)
  }
}

/**
 * Create Universal HTTP Client with optional AccountRegistry
 */
export function createUniversalHttpClient(
  config: UniversalHttpClientConfig = {},
  accountRegistry?: AccountRegistry
): UniversalHttpClient {
  return new UniversalHttpClient(config, accountRegistry)
}

/**
 * Create Universal HTTP Client with accounts pre-configured
 */
export function createUniversalHttpClientWithAccounts(
  config: UniversalHttpClientConfig = {},
  accounts: Array<{
    platform: string
    accountId: string
    credentials: any
    metadata?: { name?: string; description?: string }
  }> = []
): UniversalHttpClient {
  const client = new UniversalHttpClient(config)

  // Register all accounts
  accounts.forEach(account => {
    client.registerAccount(account.platform, account.accountId, account.credentials, account.metadata)
  })

  return client
}
