import { Body, Controller, Post, Get, Path, Query, Route, Tags } from 'tsoa';
import { ImageRecognitionService } from '../../core/ai/ImageRecognitionService';

interface ImageRecognitionRequest {
  tenantId: string;
  imageUrl: string;
  imageData?: string; // Base64 encoded image data
  tasks: ('classification' | 'detection' | 'ocr' | 'quality')[];
}

interface ImageRecognitionResponse {
  recognitionId: number;
  results: any;
  processingTime: number;
  status: string;
}

interface BatchRecognitionRequest {
  tenantId: string;
  imageUrls: string[];
  tasks: ('classification' | 'detection' | 'ocr' | 'quality')[];
}

interface BatchRecognitionResponse {
  processed: number;
  failed: number;
  results: ImageRecognitionResponse[];
}

interface RecognitionHistoryResponse {
  id: number;
  imageUrl: string;
  imageHash: string;
  recognitionResults: any;
  classificationResults: any;
  qualityMetrics: any;
  ocrResults: any;
  processingTime: number;
  createdAt: Date;
}

interface ModelStatsResponse {
  totalImages: number;
  avgProcessingTime: string;
  maxProcessingTime: string;
  minProcessingTime: string;
}

/**
 * [AI_VISION_01] 图像识别API控制器
 */
@Route('image-recognition')
@Tags('ImageRecognition')
export class ImageRecognitionController extends Controller {
  /**
   * 单张图像识别
   */
  @Post('recognize')
  async recognizeImage(@Body() request: ImageRecognitionRequest): Promise<ImageRecognitionResponse> {
    try {
      let imageData: Buffer | undefined;
      
      // 如果提供了Base64图像数据，进行解码
      if (request.imageData) {
        imageData = Buffer.from(request.imageData, 'base64');
      }

      const result = await ImageRecognitionService.processImage({
        tenantId: request.tenantId,
        imageUrl: request.imageUrl,
        imageData,
        tasks: request.tasks
      });

      return {
        recognitionId: result.recognitionId,
        results: result.results,
        processingTime: result.processingTime,
        status: 'success'
      };
    } catch (error) {
      this.setStatus(500);
      return {
        recognitionId: 0,
        results: {},
        processingTime: 0,
        status: `error: ${error.message}`
      };
    }
  }

  /**
   * 批量图像识别
   */
  @Post('batch-recognize')
  async batchRecognizeImages(@Body() request: BatchRecognitionRequest): Promise<BatchRecognitionResponse> {
    try {
      const result = await ImageRecognitionService.batchProcessImages({
        tenantId: request.tenantId,
        imageUrls: request.imageUrls,
        tasks: request.tasks
      });

      const responseResults = result.results.map(r => ({
        recognitionId: r.recognitionId,
        results: r.results,
        processingTime: r.processingTime,
        status: 'success'
      }));

      return {
        processed: result.processed,
        failed: result.failed,
        results: responseResults
      };
    } catch (error) {
      this.setStatus(500);
      return {
        processed: 0,
        failed: request.imageUrls.length,
        results: [],
        status: `error: ${error.message}`
      } as any;
    }
  }

  /**
   * 获取识别历史
   */
  @Get('history')
  async getRecognitionHistory(
    @Query() tenantId: string,
    @Query() limit: number = 50
  ): Promise<RecognitionHistoryResponse[]> {
    try {
      const history = await ImageRecognitionService.getRecognitionHistory(tenantId, limit);
      
      return history.map(record => ({
        id: record.id,
        imageUrl: record.image_url,
        imageHash: record.image_hash,
        recognitionResults: record.recognition_results,
        classificationResults: record.classification_results,
        qualityMetrics: record.quality_metrics,
        ocrResults: record.ocr_results,
        processingTime: record.processing_time,
        createdAt: record.created_at
      }));
    } catch (error) {
      this.setStatus(500);
      return [];
    }
  }

  /**
   * 获取模型性能统计
   */
  @Get('stats')
  async getModelStats(@Query() tenantId: string): Promise<ModelStatsResponse> {
    try {
      const stats = await ImageRecognitionService.getModelStats(tenantId);
      
      return {
        totalImages: stats.totalImages,
        avgProcessingTime: stats.avgProcessingTime,
        maxProcessingTime: stats.maxProcessingTime,
        minProcessingTime: stats.minProcessingTime
      };
    } catch (error) {
      this.setStatus(500);
      return {
        totalImages: 0,
        avgProcessingTime: '0',
        maxProcessingTime: '0',
        minProcessingTime: '0'
      };
    }
  }

  /**
   * 初始化图像识别服务
   */
  @Post('init')
  async initImageRecognition(): Promise<{ status: string; message: string }> {
    try {
      await ImageRecognitionService.initTable();
      return { status: 'success', message: 'ImageRecognition service initialized' };
    } catch (error) {
      this.setStatus(500);
      return { status: 'error', message: error.message };
    }
  }

  /**
   * 健康检查
   */
  @Get('health')
  async healthCheck(): Promise<{ status: string; service: string; timestamp: Date }> {
    return {
      status: 'healthy',
      service: 'ImageRecognitionService',
      timestamp: new Date()
    };
  }
}