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

dotenv.config();

/**
 * [CORE_AI_12] AI 自动化 1688 询盘机器人 (AI 1688 Inquiry Bot)
 * @description 拟人化生成询盘文案，预留 IM 协议对接
 */
export class SupplierInquiryService {
  private static API_KEY = process.env.OPENAI_API_KEY;
  private static API_URL = 'https://api.openai.com/v1/chat/completions';
  private static DEFAULT_MODEL = 'gpt-4o';

  /**
   * @description 根据商品信息生成针对供应商的询价文案
   */
  static async generateInquiry(data: {
    productTitle: string;
    attributes: Record<string, string>;
    targetQuantity: number;
    platform: string;
  }): Promise<{
    message: string;
    suggestedPrice?: number;
    explanation: string;
  }> {
    if (!this.API_KEY || this.API_KEY === 'sk-xxx') {
      return {
        message: `您好，我对您的商品“${data.productTitle}”很感兴趣，请问采购 ${data.targetQuantity} 件是否有优惠？`,
        explanation: 'AI Key not configured, returning fallback template.'
      };
    }

    try {
      const response = await axios.post(
        this.API_URL,
        {
          model: this.DEFAULT_MODEL,
          messages: [
            {
              role: 'system',
              content: `You are an expert procurement agent for global trade. 
              Your task is to generate a polite, professional, and persuasive inquiry message to a supplier on ${data.platform} (usually 1688).
              The goal is to get the best price for a specific quantity.
              Please include specific questions about:
              1. Lead time for the specified quantity.
              2. OEM/Customization possibilities if the quantity is large.
              3. Discount tiers for higher quantities.
              Return JSON: { "message": string, "suggestedPrice": number, "explanation": string }`
            },
            {
              role: 'user',
              content: `Product: ${data.productTitle}\nAttributes: ${JSON.stringify(data.attributes)}\nQuantity: ${data.targetQuantity}`
            }
          ],
          response_format: { type: 'json_object' }
        },
        {
          headers: {
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const result = JSON.parse(response.data.choices[0].message.content);
      logger.info(`[Inquiry] Generated inquiry for: ${data.productTitle}`);
      return result;
    } catch (err: any) {
      logger.error(`[Inquiry] Failed to generate: ${err.message}`);
      throw err;
    }
  }

  /**
   * @description 模拟发送消息 (IM 协议对接预留)
   */
  static async sendInquiry(supplierId: string, message: string): Promise<boolean> {
    logger.info(`[Inquiry] Sending message to supplier ${supplierId}: ${message.substring(0, 20)}...`);
    // 实际对接 1688 API 或通过 Extension 注入模拟发送
    await new Promise(resolve => setTimeout(resolve, 1000));
    return true;
  }
}
