const cosConfig = require('../config/cos.js');

module.exports = class extends think.Service {
  /**
   * 对图片进行 OCR 识别，匹配瘤种关键词
   * @param {string[]} imageUrls - 图片 URL 数组
   * @param {string[]} tagOptions - 瘤种关键词列表
   * @returns {string} 匹配到的第一个瘤种，未匹配返回空字符串
   */
  async matchTag(imageUrls, tagOptions) {
    if (!imageUrls || !imageUrls.length || !tagOptions || !tagOptions.length) return '';

    for (const url of imageUrls) {
      try {
        const text = await this.recognizeText(url);
        if (!text) continue;

        // 按瘤种列表顺序匹配，优先匹配靠前的
        for (const tag of tagOptions) {
          // 去掉括号内容做模糊匹配，如 "胃肠道间质瘤（GIST）" 同时匹配 "胃肠道间质瘤" 和 "GIST"
          const cleanTag = tag.replace(/[（(][^）)]*[）)]/g, '').trim();
          const bracketMatch = tag.match(/[（(]([^）)]*)[）)]/);
          if (text.includes(cleanTag)) return tag;
          if (bracketMatch && bracketMatch[1] && text.toUpperCase().includes(bracketMatch[1].toUpperCase())) return tag;
          if (text.includes(tag)) return tag;
        }
      } catch (err) {
        think.logger.warn(`[OCR] 识别失败 ${url}:`, err.message);
      }
    }
    return '';
  }

  /**
   * 调用腾讯云通用印刷体 OCR
   * @param {string} imageUrl - 图片 URL
   * @returns {string} 识别出的全部文字
   */
  async recognizeText(imageUrl) {
    const tencentcloud = require('tencentcloud-sdk-nodejs');
    const OcrClient = tencentcloud.ocr.v20181119.Client;

    const client = new OcrClient({
      credential: {
        secretId: cosConfig.secretId,
        secretKey: cosConfig.secretKey
      },
      region: 'ap-shanghai',
      profile: {
        httpProfile: { endpoint: 'ocr.tencentcloudapi.com' }
      }
    });

    const result = await client.GeneralBasicOCR({ ImageUrl: imageUrl });
    if (!result.TextDetections || !result.TextDetections.length) return '';

    return result.TextDetections.map(item => item.DetectedText).join('');
  }
};
