const axios = require('axios');
const logger = require('../utils/logger');

class TechStackService {
  constructor() {
    this.baseURL = process.env.TECH_STACK_SELECTOR_URL || 'http://pipeline_tech_stack_selector:8002';
    this.timeout = parseInt(process.env.REQUEST_TIMEOUT) || 30000;
  }

  /**
   * Get tech stack recommendations from tech-stack-selector service
   * @param {Object} params - Request parameters
   * @param {string} params.domain - Domain for recommendations
   * @param {number} params.budget - Budget constraint
   * @param {Array<string>} params.preferredTechnologies - Preferred technologies
   * @returns {Promise<Object>} Recommendations from tech-stack-selector
   */
  async getRecommendations({ domain, budget, preferredTechnologies }) {
    try {
      logger.info({
        message: 'Fetching recommendations from tech-stack-selector',
        domain,
        budget,
        preferredTechnologies
      });

      const requestData = {
        domain,
        budget,
        preferredTechnologies
      };

      // Remove undefined values
      Object.keys(requestData).forEach(key => {
        if (requestData[key] === undefined) {
          delete requestData[key];
        }
      });

      const response = await axios.post(
        `${this.baseURL}/recommend/best`,
        requestData,
        {
          timeout: this.timeout,
          headers: {
            'Content-Type': 'application/json',
            'User-Agent': 'Unison-Service/1.0'
          }
        }
      );

      if (response.data.success) {
        logger.info({
          message: 'Successfully fetched recommendations from tech-stack-selector',
          count: response.data.count,
          budget: response.data.budget,
          domain: response.data.domain
        });

        return {
          success: true,
          data: response.data,
          source: 'tech-stack-selector'
        };
      } else {
        throw new Error(`Tech-stack-selector returned error: ${response.data.error || 'Unknown error'}`);
      }

    } catch (error) {
      logger.error({
        message: 'Failed to fetch recommendations from tech-stack-selector',
        error: error.message,
        domain,
        budget,
        preferredTechnologies
      });

      throw new Error(`Tech-stack-selector service error: ${error.message}`);
    }
  }

  /**
   * Get price tiers from tech-stack-selector service
   * @returns {Promise<Object>} Price tiers data
   */
  async getPriceTiers() {
    try {
      logger.info('Fetching price tiers from tech-stack-selector');

      const response = await axios.get(
        `${this.baseURL}/api/price-tiers`,
        {
          timeout: this.timeout,
          headers: {
            'User-Agent': 'Unison-Service/1.0'
          }
        }
      );

      if (response.data.success) {
        logger.info({
          message: 'Successfully fetched price tiers from tech-stack-selector',
          count: response.data.count
        });

        return {
          success: true,
          data: response.data,
          source: 'tech-stack-selector'
        };
      } else {
        throw new Error(`Tech-stack-selector returned error: ${response.data.error || 'Unknown error'}`);
      }

    } catch (error) {
      logger.error({
        message: 'Failed to fetch price tiers from tech-stack-selector',
        error: error.message
      });

      throw new Error(`Tech-stack-selector service error: ${error.message}`);
    }
  }

  /**
   * Get technologies by tier from tech-stack-selector service
   * @param {string} tierName - Name of the price tier
   * @returns {Promise<Object>} Technologies for the tier
   */
  async getTechnologiesByTier(tierName) {
    try {
      logger.info({
        message: 'Fetching technologies by tier from tech-stack-selector',
        tierName
      });

      const response = await axios.get(
        `${this.baseURL}/api/technologies/${encodeURIComponent(tierName)}`,
        {
          timeout: this.timeout,
          headers: {
            'User-Agent': 'Unison-Service/1.0'
          }
        }
      );

      if (response.data.success) {
        logger.info({
          message: 'Successfully fetched technologies by tier from tech-stack-selector',
          tierName,
          count: response.data.count
        });

        return {
          success: true,
          data: response.data,
          source: 'tech-stack-selector'
        };
      } else {
        throw new Error(`Tech-stack-selector returned error: ${response.data.error || 'Unknown error'}`);
      }

    } catch (error) {
      logger.error({
        message: 'Failed to fetch technologies by tier from tech-stack-selector',
        error: error.message,
        tierName
      });

      throw new Error(`Tech-stack-selector service error: ${error.message}`);
    }
  }

  /**
   * Check health of tech-stack-selector service
   * @returns {Promise<Object>} Health status
   */
  async checkHealth() {
    try {
      const response = await axios.get(
        `${this.baseURL}/health`,
        {
          timeout: parseInt(process.env.HEALTH_CHECK_TIMEOUT) || 5000,
          headers: {
            'User-Agent': 'Unison-HealthCheck/1.0'
          }
        }
      );

      return {
        status: 'healthy',
        data: response.data,
        responseTime: response.headers['x-response-time'] || 'unknown'
      };

    } catch (error) {
      logger.warn({
        message: 'Tech-stack-selector health check failed',
        error: error.message
      });

      return {
        status: 'unhealthy',
        error: error.message
      };
    }
  }
}

module.exports = new TechStackService();
