import { apiClient } from './client'

export interface OHLCVData {
  time: number
  open: number
  high: number
  low: number
  close: number
  volume: number
}

export interface TickerData {
  symbol: string
  bid: number
  ask: number
  last: number
  high: number
  low: number
  volume: number
  timestamp: number
  provider: string
}

export interface ProviderHealth {
  status: 'healthy' | 'degraded' | 'unhealthy' | 'unknown'
  last_check?: string
  last_success?: string
  last_failure?: string
  success_count: number
  failure_count: number
  avg_response_time: number
  consecutive_failures: number
  circuit_breaker_open: boolean
  circuit_breaker_opened_at?: string
}

export interface ProviderStatus {
  active_provider: string | null
  providers: Record<string, ProviderHealth>
  cache: {
    size: number
    max_size: number
    hits: number
    misses: number
    hit_rate: number
    evictions: number
    avg_age_seconds: number
  }
}

export interface ProviderConfig {
  primary: Array<{
    name: string
    enabled: boolean
    priority: number
  }>
  fallback: {
    name: string
    enabled: boolean
    api_key?: string
  }
  caching: {
    ticker_ttl: number
    ohlcv_ttl: number
    max_cache_size: number
  }
  websocket: {
    enabled: boolean
    reconnect_interval: number
    ping_interval: number
  }
}

export const marketDataApi = {
  getOHLCV: async (symbol: string, timeframe: string = '1h'): Promise<OHLCVData[]> => {
    const response = await apiClient.get(`/api/market-data/ohlcv/${symbol}`, {
      params: { timeframe }
    })
    return response.data
  },

  getTicker: async (symbol: string): Promise<TickerData> => {
    const response = await apiClient.get(`/api/market-data/ticker/${symbol}`)
    return response.data
  },

  getProviderHealth: async (provider?: string): Promise<{ active_provider: string | null; health: Record<string, ProviderHealth> | ProviderHealth }> => {
    const params = provider ? { provider } : {}
    const response = await apiClient.get('/api/market-data/providers/health', { params })
    return response.data
  },

  getProviderStatus: async (): Promise<ProviderStatus> => {
    const response = await apiClient.get('/api/market-data/providers/status')
    return response.data
  },

  getProviderConfig: async (): Promise<ProviderConfig> => {
    const response = await apiClient.get('/api/market-data/providers/config')
    return response.data
  },

  updateProviderConfig: async (config: Partial<ProviderConfig>): Promise<{ message: string; config: ProviderConfig }> => {
    const response = await apiClient.put('/api/market-data/providers/config', config)
    return response.data
  },

  getSpreadData: async (
    primarySymbol: string,
    secondarySymbol: string,
    timeframe: string = '1h',
    lookback: number = 50
  ): Promise<SpreadDataResponse> => {
    const response = await apiClient.get('/api/market-data/spread', {
      params: {
        primary_symbol: primarySymbol,
        secondary_symbol: secondarySymbol,
        timeframe,
        lookback,
      }
    })
    return response.data
  }
}

export interface SpreadDataPoint {
  timestamp: number
  spread: number
  zScore: number
  priceA: number
  priceB: number
}

export interface SpreadDataResponse {
  primarySymbol: string
  secondarySymbol: string
  timeframe: string
  lookbackWindow: number
  data: SpreadDataPoint[]
  currentSpread: number | null
  currentZScore: number | null
}
