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

class TemplateService {
  constructor() {
    this.baseURL = process.env.TEMPLATE_MANAGER_URL || 'http://pipeline_template_manager:8009';
    this.aiURL = process.env.TEMPLATE_MANAGER_AI_URL || 'http://pipeline_template_manager:8013';
    this.timeout = parseInt(process.env.REQUEST_TIMEOUT) || 30000;
  }

  /**
   * Get template by ID from template-manager service
   * @param {string} templateId - Template ID
   * @returns {Promise<Object>} Template data
   */
  async getTemplate(templateId) {
    try {
      logger.info({
        message: 'Fetching template from template-manager',
        templateId
      });

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

      if (response.data.success) {
        logger.info({
          message: 'Successfully fetched template from template-manager',
          templateId,
          templateName: response.data.data?.name || 'Unknown'
        });

        return {
          success: true,
          data: response.data.data,
          source: 'template-manager'
        };
      } else {
        throw new Error(`Template-manager returned error: ${response.data.error || 'Unknown error'}`);
      }

    } catch (error) {
      logger.error({
        message: 'Failed to fetch template from template-manager',
        error: error.message,
        templateId
      });

      throw new Error(`Template-manager service error: ${error.message}`);
    }
  }

  /**
   * Get AI recommendations for a template
   * @param {string} templateId - Template ID
   * @param {Object} options - Request options
   * @param {boolean} options.forceRefresh - Force refresh recommendations
   * @returns {Promise<Object>} AI recommendations
   */
  async getAIRecommendations(templateId, options = {}) {
    try {
      logger.info({
        message: 'Fetching AI recommendations from template-manager',
        templateId,
        options
      });

      const requestData = {
        template_id: templateId
      };
      
      if (options.forceRefresh) {
        requestData.force_refresh = true;
      }

      const url = `${this.aiURL}/ai/recommendations`;

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

      // AI service returns data directly (not wrapped in success object)
      if (response.data && response.data.stack_name) {
        logger.info({
          message: 'Successfully fetched AI recommendations from template-manager',
          templateId,
          stackName: response.data.stack_name || 'Unknown'
        });

        return {
          success: true,
          data: response.data,
          source: 'template-manager-ai'
        };
      } else {
        throw new Error(`Template-manager AI returned invalid data: ${JSON.stringify(response.data)}`);
      }

    } catch (error) {
      logger.error({
        message: 'Failed to fetch AI recommendations from template-manager',
        error: error.message,
        templateId,
        options
      });

      throw new Error(`Template-manager AI service error: ${error.message}`);
    }
  }

  /**
   * Select template with additional options
   * @param {string} templateId - Template ID
   * @param {Object} options - Selection options
   * @param {boolean} options.includeSimilar - Include similar templates
   * @param {boolean} options.includeKeywords - Include keywords
   * @returns {Promise<Object>} Template selection data
   */
  async selectTemplate(templateId, options = {}) {
    try {
      logger.info({
        message: 'Selecting template from template-manager',
        templateId,
        options
      });

      const queryParams = new URLSearchParams();
      if (options.includeSimilar) {
        queryParams.append('include_similar', 'true');
      }
      if (options.includeKeywords) {
        queryParams.append('include_keywords', 'true');
      }

      const url = `${this.baseURL}/api/templates/${templateId}/select${queryParams.toString() ? '?' + queryParams.toString() : ''}`;

      const response = await axios.get(url, {
        timeout: this.timeout,
        headers: {
          'User-Agent': 'Unison-Service/1.0'
        }
      });

      if (response.data.success) {
        logger.info({
          message: 'Successfully selected template from template-manager',
          templateId
        });

        return {
          success: true,
          data: response.data.data,
          source: 'template-manager'
        };
      } else {
        throw new Error(`Template-manager returned error: ${response.data.error || 'Unknown error'}`);
      }

    } catch (error) {
      logger.error({
        message: 'Failed to select template from template-manager',
        error: error.message,
        templateId,
        options
      });

      throw new Error(`Template-manager service error: ${error.message}`);
    }
  }

  /**
   * Get all templates from template-manager service
   * @param {Object} options - Query options
   * @returns {Promise<Object>} Templates list
   */
  async getTemplates(options = {}) {
    try {
      logger.info({
        message: 'Fetching templates from template-manager',
        options
      });

      const queryParams = new URLSearchParams();
      Object.keys(options).forEach(key => {
        if (options[key] !== undefined) {
          queryParams.append(key, options[key]);
        }
      });

      const url = `${this.baseURL}/api/templates${queryParams.toString() ? '?' + queryParams.toString() : ''}`;

      const response = await axios.get(url, {
        timeout: this.timeout,
        headers: {
          'User-Agent': 'Unison-Service/1.0'
        }
      });

      if (response.data.success) {
        logger.info({
          message: 'Successfully fetched templates from template-manager',
          count: response.data.data?.length || 0
        });

        return {
          success: true,
          data: response.data.data,
          source: 'template-manager'
        };
      } else {
        throw new Error(`Template-manager returned error: ${response.data.error || 'Unknown error'}`);
      }

    } catch (error) {
      logger.error({
        message: 'Failed to fetch templates from template-manager',
        error: error.message,
        options
      });

      throw new Error(`Template-manager service error: ${error.message}`);
    }
  }

  /**
   * Check health of template-manager 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: 'Template-manager health check failed',
        error: error.message
      });

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

  /**
   * Check health of template-manager AI service
   * @returns {Promise<Object>} Health status
   */
  async checkAIHealth() {
    try {
      const response = await axios.get(
        `${this.aiURL}/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: 'Template-manager AI health check failed',
        error: error.message
      });

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

module.exports = new TemplateService();
