import axios from 'axios';
import { StockRequest, MacdResult } from '../types/stock';
import { getApiBaseUrl } from './apiConfig';

// API 베이스 URL (통합 설정 사용)
const API_BASE_URL = getApiBaseUrl();

const upbitApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 60000, // 60초로 증가 (외부 DB 연결 시간 고려)
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  withCredentials: false,
});

export interface UpbitMarket {
  market: string;
  korean_name: string;
  english_name: string;
  market_warning?: string;
}

export interface CryptoInfo {
  symbol: string;
  koreanName: string;
  englishName: string;
  marketWarning?: string;
  isActive: boolean;
  isFavorite: boolean;
  lastUpdated?: string;
}

export interface TrendStrengthResult {
  symbol: string;
  koreanName: string;
  englishName?: string;
  trendStrength: number;
  ma10: number;
  ma20: number;
  ma60: number;
  atr14: number;
  dataAvailable: boolean;
  trendUpdatedAt?: string;
}

export interface UpbitTicker {
  market: string;
  trade_date: string;
  trade_time: string;
  trade_price: number;
  prev_closing_price: number;
  change: string;
  change_price: number;
  change_rate: number;
  signed_change_price: number;
  signed_change_rate: number;
  trade_volume: number;
  acc_trade_price_24h: number;
  acc_trade_volume_24h: number;
  timestamp: number;
}

export const upbitApiService = {
  async getMarkets(): Promise<UpbitMarket[]> {
    try {
      const cryptos = await this.getActiveCryptos();
      return cryptos.map(crypto => ({
        market: crypto.symbol,
        korean_name: crypto.koreanName,
        english_name: crypto.englishName,
        market_warning: crypto.marketWarning
      }));
    } catch (error) {
      console.error('업비트 마켓 목록 조회 실패:', error);
      throw new Error('업비트 마켓 목록을 가져올 수 없습니다.');
    }
  },

  async getActiveCryptos(): Promise<CryptoInfo[]> {
    try {
      const response = await upbitApi.get<CryptoInfo[]>('/crypto/list');
      return response.data;
    } catch (error) {
      console.error('활성화된 암호화폐 목록 조회 실패:', error);
      throw new Error('암호화폐 목록을 가져올 수 없습니다.');
    }
  },

  async refreshCryptoList(): Promise<string> {
    try {
      const response = await upbitApi.post<string>('/crypto/refresh');
      return response.data;
    } catch (error) {
      console.error('암호화폐 목록 새로고침 실패:', error);
      throw new Error('암호화폐 목록 새로고침에 실패했습니다.');
    }
  },

  async getFavoriteCryptos(): Promise<CryptoInfo[]> {
    try {
      const response = await upbitApi.get<CryptoInfo[]>('/crypto/favorites');
      return response.data;
    } catch (error) {
      console.error('즐겨찾기 암호화폐 목록 조회 실패:', error);
      throw new Error('즐겨찾기 암호화폐 목록을 가져올 수 없습니다.');
    }
  },

  async toggleFavorite(symbol: string, isFavorite: boolean): Promise<string> {
    try {
      const response = await upbitApi.put<string>(`/crypto/${symbol}/favorite?isFavorite=${isFavorite}`);
      return response.data;
    } catch (error) {
      console.error('즐겨찾기 상태 변경 실패:', error);
      throw new Error('즐겨찾기 상태 변경에 실패했습니다.');
    }
  },

  async clearAllFavorites(): Promise<string> {
    try {
      const response = await upbitApi.delete<string>('/crypto/favorites/all');
      return response.data;
    } catch (error) {
      console.error('모든 즐겨찾기 삭제 실패:', error);
      throw new Error('즐겨찾기 삭제에 실패했습니다.');
    }
  },

  async analyzeCryptoMacd(request: StockRequest): Promise<{ data: MacdResult[], backendSettings?: any }> {
    if (!request.symbol.startsWith('KRW-')) {
      throw new Error('업비트 암호화폐는 KRW- 형식이어야 합니다.');
    }

    console.log(`🚀 [빠른조회] ${request.symbol} ${request.interval}`, request);
    
    const response = await upbitApi.post('/upbit/analyze', request, {
      timeout: 30000,
    });
    
    console.log('📥 API 응답:', response.data);
    
    if (!response.data || response.data.length === 0) {
      throw new Error(`데이터가 없습니다. (심볼: ${request.symbol}, 인터벌: ${request.interval})`);
    }

    // ✅ 백엔드 설정값 파싱 (정수 + 소수점 모두 지원)
    const backendSettingsHeader = response.headers['x-indicator-settings'];
    let backendSettings = null;
    if (backendSettingsHeader) {
      try {
        const settings: any = {};
        const parts = backendSettingsHeader.split(';');
        parts.forEach((part: string) => {
          const [key, values] = part.split(':');
          if (key && values) {
            // parseFloat으로 정수와 소수점 모두 처리 (볼린저 밴드 표준편차 등)
            const nums = values.split(',').map((v: string) => parseFloat(v));
            settings[key.trim()] = nums;
          }
        });
        backendSettings = settings;
        console.log('📊 백엔드 설정값:', backendSettings);
      } catch (error) {
        console.error('백엔드 설정값 파싱 실패:', error);
      }
    }

    console.log(`✅ 수신: ${response.data.length}개`);
    return { data: response.data, backendSettings };
  },

  async getTrendStrength(sort: 'bullish' | 'bearish' | 'default' = 'default'): Promise<TrendStrengthResult[]> {
    try {
      const response = await upbitApi.get<TrendStrengthResult[]>(`/upbit/trend-strength?sort=${sort}`, {
        timeout: 30000,
      });
      return response.data;
    } catch (error) {
      console.error('추세 강도 조회 실패:', error);
      throw new Error('추세 강도를 가져올 수 없습니다.');
    }
  },

  async getCurrentPrice(markets: string[]): Promise<UpbitTicker[]> {
    try {
      const marketString = markets.join(',');
      const response = await upbitApi.get<UpbitTicker[]>(
        `/upbit/ticker?markets=${encodeURIComponent(marketString)}`
      );
      return response.data;
    } catch (error) {
      console.error('업비트 현재가 조회 실패:', error);
      return [];
    }
  },

  /** 상위 종목 조회 - 전체 KRW 마켓 기준 (상승추세/거래량 순) */
  async getTopTickers(sort: 'uptrend' | 'volume', limit: number): Promise<Array<{ market: string; koreanName: string }>> {
    try {
      const response = await upbitApi.get<Array<{ market: string; koreanName: string }>>(
        `/upbit/ticker/top?sort=${sort}&limit=${limit}`
      );
      return response.data || [];
    } catch (error) {
      console.error('상위 티커 조회 실패:', error);
      return [];
    }
  },

  /** 티커 조회 - 상승추세/거래량 정렬용 (백엔드 API 사용) */
  async getTickers(markets: string[]): Promise<Array<{ market: string; signedChangeRate: number; accTradeVolume24h: number }>> {
    const marketString = markets.join(',');
    type TickerRaw = { market: string; signed_change_rate?: number; acc_trade_volume_24h?: number; signedChangeRate?: number; accTradeVolume24h?: number };
    const normalize = (raw: TickerRaw[]) =>
      (raw || []).map((t) => ({
        market: t.market,
        signedChangeRate: t.signedChangeRate ?? t.signed_change_rate ?? 0,
        accTradeVolume24h: t.accTradeVolume24h ?? t.acc_trade_volume_24h ?? 0,
      }));

    try {
      const response = await upbitApi.get<TickerRaw[]>(
        `/upbit/ticker?markets=${encodeURIComponent(marketString)}`
      );
      return normalize(response.data || []);
    } catch (error) {
      console.error('티커 조회 실패:', error);
      return [];
    }
  },

  validateCryptoSymbol(symbol: string): boolean {
    return symbol.startsWith('KRW-') && symbol.length > 4;
  },

  getCryptoDisplayName(symbol: string): string {
    const cryptoNames: Record<string, string> = {
      'KRW-BTC': '비트코인',
      'KRW-ETH': '이더리움',
      'KRW-XRP': '리플',
      'KRW-ADA': '에이다',
      'KRW-DOT': '폴카닷',
      'KRW-LINK': '체인링크',
      'KRW-SOL': '솔라나',
      'KRW-AVAX': '아발란체',
      'KRW-MATIC': '폴리곤',
      'KRW-DOGE': '도지코인',
    };
    return cryptoNames[symbol] || symbol.replace('KRW-', '');
  },
};

export default upbitApiService;

