/**
 * Market Data API 서비스
 * - 런타임 환경에 따라 동적으로 URL 결정
 */
const getMarketDataUrl = (): string => {
  const envUrl = process.env.REACT_APP_MARKET_DATA_URL;
  if (envUrl) return envUrl.replace(/\/$/, '');
  
  // 런타임 환경 감지
  if (typeof window === 'undefined') {
    return '/market-data'; // SSR fallback
  }
  
  const isLocalhost = window.location.hostname === 'localhost' || 
    window.location.hostname === '127.0.0.1' ||
    window.location.hostname === '';
  
  if (isLocalhost) {
    // 로컬 개발 시 서버로 직접 연결
    return 'http://localhost:8086';
  }
  
  // 서버 환경: 현재 origin 사용 (nginx가 프록시)
  return `${window.location.origin}/market-data`;
};

export const MARKET_DATA_API_URL = getMarketDataUrl();
export const MARKET_DATA_WS_URL = MARKET_DATA_API_URL.replace('http', 'ws');

export interface CandleSnapshot {
  timestamp: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
}

export interface IndicatorSnapshot {
  rsi_14?: number;
  ema_9?: number;
  ema_21?: number;
  macd?: number;
  macd_signal?: number;
  macd_histogram?: number;
  bb_upper?: number;
  bb_middle?: number;
  bb_lower?: number;
  stoch_k?: number;
  stoch_d?: number;
  adx?: number;
  plus_di?: number;
  minus_di?: number;
}

export interface CandleSnapshotResponse {
  market: string;
  timeframe: string;
  candles: CandleSnapshot[];
  indicators: IndicatorSnapshot;
  count: number;
}

/**
 * 초기 캔들 스냅샷 가져오기
 */
export const fetchCandleSnapshot = async (
  market: string,
  timeframe: string,
  limit: number = 200
): Promise<CandleSnapshotResponse> => {
  const url = `${MARKET_DATA_API_URL}/candles?market=${market}&timeframe=${timeframe}&limit=${limit}`;
  
  const response = await fetch(url);
  
  if (!response.ok) {
    throw new Error(`Failed to fetch candle snapshot: ${response.status}`);
  }
  
  return await response.json();
};

/**
 * 서버 상태 확인
 */
export const checkHealth = async (): Promise<boolean> => {
  try {
    const response = await fetch(`${MARKET_DATA_API_URL}/health`);
    const data = await response.json();
    return data.status === 'healthy';
  } catch {
    return false;
  }
};

/**
 * 서버 통계 조회
 */
export const fetchStats = async (): Promise<any> => {
  const response = await fetch(`${MARKET_DATA_API_URL}/stats`);
  return await response.json();
};
