// Service Implementation API Client
// This client interacts with the service_implementation API documented in api_documentation.md

import { logger } from '../utils/logger';

class ServiceImplementationClient {
  private baseUrl: string;

  constructor(baseUrl: string = 'http://localhost:5000') {
    this.baseUrl = baseUrl;
  }

  async get<T>(endpoint: string, params?: Record<string, string>): Promise<T> {
    let url = `${this.baseUrl}${endpoint}`;
    if (params) {
      const queryString = new URLSearchParams(params).toString();
      url += `?${queryString}`;
    }

    try {
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
      }

      const data = await response.json();
      return data as T;
    } catch (error: any) {
      logger.error('GET request failed:', error.message || error);
      throw new Error(`Network request failed: ${error.message || error}`);
    }
  }

  async post<T>(endpoint: string, data?: any): Promise<T> {
    const url = `${this.baseUrl}${endpoint}`;

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: data ? JSON.stringify(data) : undefined
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
      }

      const responseData = await response.json();
      return responseData as T;
    } catch (error: any) {
      logger.error('POST request failed:', error.message || error);
      throw new Error(`Network request failed: ${error.message || error}`);
    }
  }

  // Health check
  async healthCheck() {
    return this.get<{ status: string; message: string }>('/health');
  }

  // Get contracts
  async getContracts(exchange?: string, symbol?: string) {
    const params: Record<string, string> = {};
    if (exchange) params.exchange = exchange;
    if (symbol) params.symbol = symbol;
    logger.info(`Getting contracts for exchange ${exchange} and symbol ${symbol}`);
    return this.get<{ status: string; data: any[] }>('/api/contracts', params);
  }

  // Get Kline data
  async getKlineData(symbol: string, duration: string = '1m', limit: number = 100) {
    return this.get<{ status: string; data: any[] }>('/api/kline', {
      symbol,
      duration,
      limit: limit.toString()
    });
  }

  // Analyze market
  async analyzeMarket(symbol: string, duration: string = '1m', analysisType: string = 'technical') {
    return this.post<{ status: string; data: any }>('/api/analyze', {
      symbol,
      duration,
      analysis_type: analysisType
    });
  }

  // Get recommendations
  async getRecommendations(symbol: string, status?: string) {
    const params: Record<string, string> = { symbol };
    if (status) params.status = status;
    return this.get<{ status: string; data: any[] }>('/api/recommendations', params);
  }

  // Risk monitoring
  async monitorRisk(symbol: string, currentPrice: number, entryPrice: number, stopLoss: number, targetPrice: number) {
    return this.post<{ status: string; data: any }>('/api/risk', {
      symbol,
      current_price: currentPrice,
      entry_price: entryPrice,
      stop_loss: stopLoss,
      target_price: targetPrice
    });
  }

  // Get analysis history
  async getAnalysisHistory(symbol: string, limit: number = 100) {
    return this.get<{ status: string; data: any[] }>('/api/analysis/history', {
      symbol,
      limit: limit.toString()
    });
  }
}

// Export singleton instance
export const serviceImplementationClient = new ServiceImplementationClient();
export default ServiceImplementationClient;
