/**
 * OCR Processor Service
 * 处理图片 OCR 识别的异步服务
 * 支持多种 OCR Provider: Tesseract.js, Baidu OCR, RapidOCR
 */

import { prisma } from '../lib/prisma';
import { ImageService } from './image.service';
import {
  OCRProviderFactory,
  OCRProviderType,
  IImageSource,
} from './ocr-providers';

export interface OCRProcessOptions {
  /** 指定 OCR Provider */
  provider?: OCRProviderType;
  /** 置信度阈值 */
  confidenceThreshold?: number;
}

export class OCRProcessorService {
  /**
   * 处理图片的 OCR 识别
   * @param imageId 图片 ID
   * @param userId 用户 ID
   * @param options 处理选项
   */
  static async processImage(
    imageId: string,
    userId: string,
    options: OCRProcessOptions = {}
  ): Promise<void> {
    try {
      // 更新状态为处理中
      await prisma.image.update({
        where: { id: imageId },
        data: { processing_status: 'processing' },
      });

      // 获取图片信息
      const image = await ImageService.findById(imageId, userId);
      if (!image) {
        throw new Error('Image not found');
      }

      // 执行 OCR 识别
      const ocrResult = await this.performOCR(image, options);

      // 根据置信度决定状态
      const threshold = options.confidenceThreshold
        ? parseFloat(options.confidenceThreshold.toString())
        : parseFloat(process.env.OCR_CONFIDENCE_THRESHOLD || '0.3');
      const status = ocrResult.confidence >= threshold ? 'completed' : 'failed';

      await prisma.image.update({
        where: { id: imageId },
        data: {
          ocr_result: ocrResult.text,
          ocr_confidence: ocrResult.confidence,
          processing_status: status,
          error_message: status === 'failed' ? 'OCR 识别置信度过低' : null,
        },
      });
    } catch (error) {
      // 处理失败
      await prisma.image.update({
        where: { id: imageId },
        data: {
          processing_status: 'failed',
          error_message: error instanceof Error ? error.message : 'OCR 处理失败',
        },
      });
    }
  }

  /**
   * 执行 OCR 识别
   * @param image 图片信息
   * @param options 处理选项
   */
  private static async performOCR(
    image: any,
    options: OCRProcessOptions = {}
  ): Promise<{ text: string; confidence: number }> {
    // 获取 OCR Provider
    const providerType = options.provider || (process.env.OCR_PROVIDER as OCRProviderType) || 'auto';
    const provider = OCRProviderFactory.create(providerType);

    // 检查 provider 是否可用
    const available = await provider.isAvailable();
    if (!available) {
      throw new Error(
        `OCR Provider "${provider.getName()}" 不可用。` +
        `请检查配置或安装相应的依赖。`
      );
    }

    // 准备图片来源
    const source: IImageSource = {
      path: image.file_path,
    };

    // 执行识别
    const result = await provider.recognize(source);

    console.log(
      `[OCR] Provider: ${provider.getName()}, ` +
      `Confidence: ${(result.confidence * 100).toFixed(1)}%, ` +
      `Duration: ${result.duration}ms, ` +
      `Text length: ${result.text.length}`
    );

    return {
      text: result.text,
      confidence: result.confidence,
    };
  }

  /**
   * 获取所有可用的 OCR Providers
   */
  static async getAvailableProviders(): Promise<
    Array<{ type: string; name: string; available: boolean; typeDesc: string }>
  > {
    return OCRProviderFactory.getAvailableProviders();
  }

  /**
   * 测试指定的 OCR Provider
   */
  static async testProvider(
    providerType: OCRProviderType,
    imagePath: string
  ): Promise<{
    success: boolean;
    result?: { text: string; confidence: number; duration: number };
    error?: string;
  }> {
    try {
      const provider = OCRProviderFactory.create(providerType);
      const available = await provider.isAvailable();

      if (!available) {
        return {
          success: false,
          error: `Provider "${provider.getName()}" 不可用`,
        };
      }

      const result = await provider.recognize({ path: imagePath });

      return {
        success: true,
        result: {
          text: result.text,
          confidence: result.confidence,
          duration: result.duration || 0,
        },
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error),
      };
    }
  }
}

// 导出异步处理函数（用于在后台触发 OCR）
export const triggerOCRProcessing = async (
  imageId: string,
  userId: string,
  options?: OCRProcessOptions
) => {
  // 不等待完成，在后台处理
  OCRProcessorService.processImage(imageId, userId, options).catch((error) => {
    console.error('OCR processing failed:', error);
  });
};
