/**
 * HTTP客户端核心类型定义
 *
 * 从libs/http-client迁移的核心类型，按照constitution要求模块化集成
 */

export interface HttpClientRequest {
  /** Platform identifier (pacifica, aster, binance) */
  platform: string
  /** Account identifier for the request */
  accountId: string
  /** HTTP method */
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
  /** Request URL path */
  url: string
  /** Optional request headers */
  headers?: Record<string, string>
  /** Optional request body */
  body?: any
  /** Optional request configuration */
  options?: RequestOptions
}

export interface RequestOptions {
  /** Timeout configuration */
  timeout?: TimeoutConfig
  /** Retry configuration */
  retry?: RetryConfig
  /** Proxy control options */
  proxy?: ProxyControlOptions
  /** Whether to log sensitive data */
  logSensitiveData?: boolean
  /** Idempotency key for request deduplication */
  idempotencyKey?: string
  /** Enable response caching */
  cache?: CacheOptions
  /** Enable performance optimization */
  enableOptimization?: boolean
}

export interface TimeoutConfig {
  /** Connection timeout in milliseconds */
  connect?: number
  /** Read timeout in milliseconds */
  read?: number
  /** Write timeout in milliseconds */
  write?: number
}

export interface RetryConfig {
  /** Maximum number of retry attempts */
  maxAttempts?: number
  /** Delay between retries in milliseconds */
  delay?: number
  /** Whether to use exponential backoff */
  exponentialBackoff?: boolean
  /** Custom retry condition function */
  shouldRetry?: (error: any) => boolean
}

export interface ProxyControlOptions {
  /** Whether proxy is enabled */
  enabled?: boolean
  /** Proxy selection strategy */
  strategy?: 'global' | 'account' | 'force' | 'disabled'
  /** Proxy rotation strategy */
  rotation?: 'none' | 'round-robin' | 'random' | 'sticky-session'
  /** Enable proxy health checks */
  healthCheck?: boolean
  /** Enable automatic failover */
  failover?: boolean
  /** Required geographic location */
  requiredGeo?: string
  /** Specific proxy pool name */
  poolName?: string
  /** Session identifier for sticky sessions */
  sessionId?: string
}

export interface CacheOptions {
  /** Whether caching is enabled */
  enabled?: boolean
  /** Time-to-live in milliseconds */
  ttl?: number
  /** Cache key override */
  key?: string
  /** Cache invalidation tags */
  tags?: string[]
}

export interface HttpClientResponse<T = any> {
  /** HTTP status code */
  status: number
  /** HTTP status text */
  statusText: string
  /** Whether the request was successful */
  ok: boolean
  /** Response data */
  data: T
  /** Response headers */
  headers: Record<string, string>
  /** Response metadata */
  metadata: ResponseMetadata
}

export interface ResponseMetadata {
  /** Unique request identifier */
  requestId: string
  /** Request duration in milliseconds */
  duration: number
  /** Number of retry attempts made */
  retryCount: number
  /** Whether a proxy was used */
  usedProxy: boolean
  /** Proxy identifier if used */
  proxyUsed?: string
  /** Request timestamp */
  timestamp: Date
  /** Platform identifier */
  platform: string
  /** Account identifier */
  accountId: string
  /** Whether response came from cache */
  cacheHit?: boolean
  /** Network latency in milliseconds */
  networkLatency?: number
  /** Processing time in milliseconds */
  processingTime?: number
  /** Response size in bytes */
  responseSize?: number
  /** Proxy geographic location */
  proxyGeo?: string
  /** Session identifier */
  sessionId?: string
  /** Whether request was authenticated */
  authenticated?: boolean
  /** Signature algorithm used for authentication */
  signatureAlgorithm?: string
  /** Authentication timestamp */
  authTimestamp?: Date
  /** Whether credential manager was used */
  credentialManagerUsed?: boolean
  /** Whether signature was verified */
  signatureVerified?: boolean
  /** Timeout configuration used */
  timeout?: TimeoutConfig
  /** Idempotency key */
  idempotencyKey?: string
  /** Whether resources were cleaned up */
  resourcesCleanedUp?: boolean
}

export interface BatchRequestOptions {
  /** Maximum number of concurrent requests */
  concurrency?: number
  /** Whether to stop on first failure */
  failFast?: boolean
  /** Whether to retry failed requests */
  retryFailedRequests?: boolean
  /** Whether to aggregate results */
  aggregateResults?: boolean
  /** Batch execution timeout */
  timeout?: number
}

export interface BatchResult<T = any> {
  /** Individual request results */
  results: Array<{
    /** Whether the request succeeded */
    success: boolean
    /** Response data if successful */
    data?: T
    /** Error if failed */
    error?: any
    /** Original request index */
    requestIndex: number
    /** Request duration */
    duration: number
  }>
  /** Batch execution summary */
  summary: {
    /** Total number of requests */
    total: number
    /** Number of successful requests */
    successful: number
    /** Number of failed requests */
    failed: number
    /** Total execution duration */
    totalDuration: number
    /** Average request duration */
    averageDuration: number
  }
}

export interface UniversalHttpClientConfig {
  /** Global timeout configuration */
  timeout?: TimeoutConfig
  /** Global retry configuration */
  retry?: RetryConfig
  /** Global proxy configuration */
  proxy?: ProxyControlOptions
  /** Credential manager instance */
  credentialManager?: any
  /** Performance monitor instance */
  performanceMonitor?: any
  /** Proxy manager instance */
  proxyManager?: any
  /** Enable performance optimization */
  enablePerformanceOptimization?: boolean
  /** Default cache configuration */
  cache?: CacheOptions
  /** Rate limiting configuration */
  rateLimiting?: {
    /** Global rate limit */
    globalLimit?: number
    /** Per-platform rate limits */
    platformLimits?: Record<string, number>
  }
  /** Logging configuration */
  logging?: {
    /** Log level */
    level?: 'debug' | 'info' | 'warn' | 'error'
    /** Whether to log sensitive data */
    logSensitiveData?: boolean
    /** Custom logger instance */
    logger?: any
  }
}

export interface PerformanceOptimizationConfig {
  /** Optimization strategy */
  strategy?: 'adaptive-routing' | 'load-balancing' | 'caching' | 'connection-pooling'
  /** Optimization interval in milliseconds */
  optimizationInterval?: number
  /** Performance weight (0-1) */
  performanceWeight?: number
  /** Reliability weight (0-1) */
  reliabilityWeight?: number
  /** Enable automatic optimization */
  autoOptimize?: boolean
  /** Minimum requests before optimization */
  minRequestsForOptimization?: number
}

export interface OptimizationStats {
  /** Total optimizations performed */
  totalOptimizations: number
  /** Routing decisions made */
  routingDecisions: number
  /** Performance improvement percentage */
  performanceImprovement: number
  /** Optimization strategies used */
  strategiesUsed: string[]
  /** Last optimization timestamp */
  lastOptimization: Date
}

export interface CacheStats {
  /** Cache hit rate (0-1) */
  hitRate: number
  /** Current cache size */
  size: number
  /** Total cache hits */
  totalHits: number
  /** Total cache misses */
  totalMisses: number
  /** Average response time for cached requests */
  averageCachedResponseTime: number
  /** Cache memory usage in bytes */
  memoryUsage: number
}

export interface ConnectionPoolStats {
  /** Number of active connections */
  activeConnections: number
  /** Number of idle connections */
  idleConnections: number
  /** Total number of connections */
  totalConnections: number
  /** Connection reuse count */
  connectionReuse: number
  /** Average connection age */
  averageConnectionAge: number
  /** Connection pool efficiency (0-1) */
  efficiency: number
}

// Type aliases
export type AuthenticationType = 'ed25519' | 'eip191' | 'hmac-sha256' | 'bearer' | 'api-key'
export type ProxyStrategy = 'global' | 'account' | 'force' | 'disabled'
export type RotationStrategy = 'none' | 'round-robin' | 'random' | 'sticky-session'
export type CacheStrategy = 'lru' | 'lfu' | 'ttl' | 'none'
export type LoadBalancingStrategy = 'round-robin' | 'weighted-round-robin' | 'least-connections' | 'random'

// Event types for the HTTP client
export interface HttpClientEvents {
  'request:start': { requestId: string; platform: string; accountId: string }
  'request:complete': { requestId: string; duration: number; success: boolean }
  'request:error': { requestId: string; error: any }
  'platform:registered': { platform: string }
  'platform:health': { platform: string; healthy: boolean }
  'proxy:configured': { type: 'global' | 'account'; config: any }
  'cache:hit': { requestId: string; key: string }
  'cache:miss': { requestId: string; key: string }
  'optimization:applied': { type: string; improvement: number }
}

// Error classes
export class HttpClientError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly platform?: string,
    public readonly accountId?: string,
    public readonly originalError?: any,
  ) {
    super(message)
    this.name = 'HttpClientError'
  }
}

export class PlatformError extends HttpClientError {
  constructor(message: string, platform: string, accountId?: string, originalError?: any) {
    super(message, 'PLATFORM_ERROR', platform, accountId, originalError)
    this.name = 'PlatformError'
  }
}

export class AuthenticationError extends HttpClientError {
  constructor(message: string, platform: string, accountId: string, originalError?: any) {
    super(message, 'AUTHENTICATION_ERROR', platform, accountId, originalError)
    this.name = 'AuthenticationError'
  }
}

export class ProxyError extends HttpClientError {
  constructor(
    message: string,
    public readonly proxyUrl?: string,
    originalError?: any,
  ) {
    super(message, 'PROXY_ERROR', undefined, undefined, originalError)
    this.name = 'ProxyError'
  }
}

export class TimeoutError extends HttpClientError {
  constructor(
    message: string,
    public readonly timeoutMs: number,
    platform?: string,
    accountId?: string,
  ) {
    super(message, 'TIMEOUT_ERROR', platform, accountId)
    this.name = 'TimeoutError'
  }
}

export class RateLimitError extends HttpClientError {
  constructor(
    message: string,
    public readonly retryAfter?: number,
    platform?: string,
    accountId?: string,
  ) {
    super(message, 'RATE_LIMIT_ERROR', platform, accountId)
    this.name = 'RateLimitError'
  }
}

// Type guards
export function isHttpClientRequest(obj: any): obj is HttpClientRequest {
  return (
    obj &&
    typeof obj.platform === 'string' &&
    typeof obj.accountId === 'string' &&
    typeof obj.method === 'string' &&
    typeof obj.url === 'string'
  )
}

export function isHttpClientResponse(obj: any): obj is HttpClientResponse {
  return obj && typeof obj.status === 'number' && typeof obj.ok === 'boolean' && obj.data !== undefined && obj.metadata
}

export function isBatchResult(obj: any): obj is BatchResult {
  return obj && Array.isArray(obj.results) && obj.summary && typeof obj.summary.total === 'number'
}
