import { Injectable, Logger } from '@nestjs/common';
import { I18nService } from '../i18n/i18n.service';
import { ConfigService } from '@nestjs/config';
import { ChatOpenAI } from '@langchain/openai';
import { HumanMessage } from '@langchain/core/messages';
import * as fs from 'fs/promises';
import { VisionAnalysisResult, VisionModelConfig, BatchAnalysisResult, ImageDescription } from './vision.interface';

@Injectable()
export class VisionService {
  private readonly logger = new Logger(VisionService.name);

  constructor(
    private configService: ConfigService,
    private i18nService: I18nService,
  ) { }

  
  async analyzeImage(
    imagePath: string,
    modelConfig: VisionModelConfig,
    pageIndex?: number,
  ): Promise<VisionAnalysisResult> {
    const maxRetries = 3;
    const baseDelay = 3000; 

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        return await this.performAnalysis(imagePath, modelConfig, pageIndex);
      } catch (error) {
        const isRetryableError = this.isRetryableError(error);

        if (attempt === maxRetries || !isRetryableError) {
          throw new Error(this.i18nService.formatMessage('visionAnalysisFailed', { message: error.message }));
        }

        const delay = baseDelay + Math.random() * 2000; 
        this.logger.warn(
          `⚠️ Failed to analyze page ${pageIndex || '?'} (${attempt}/${maxRetries}), retrying in ${delay.toFixed(0)}ms: ${error.message}`
        );

        await this.sleep(delay);
      }
    }

    
    throw new Error(this.i18nService.getMessage('retryMechanismError'));
  }

  
  private async performAnalysis(
    imagePath: string,
    modelConfig: VisionModelConfig,
    pageIndex?: number,
  ): Promise<VisionAnalysisResult> {
    try {
      
      const imageBuffer = await fs.readFile(imagePath);
      const base64Image = imageBuffer.toString('base64');
      const mimeType = this.getMimeType(imagePath);

      
      const model = new ChatOpenAI({
        apiKey: modelConfig.apiKey,
        model: modelConfig.modelId,
        configuration: {
          baseURL: modelConfig.baseUrl,
        },
        temperature: 0.1, 
      });

      
      const systemPrompt = this.i18nService.getMessage('visionSystemPrompt');

      const message = new HumanMessage({
        content: [
          {
            type: 'text',
            text: systemPrompt,
          },
          {
            type: 'image_url',
            image_url: {
              url: `data:${mimeType};base64,${base64Image}`,
            },
          },
        ],
      });

      
      this.logger.log(this.i18nService.formatMessage('visionModelCall', { model: modelConfig.modelId, page: pageIndex || 'single' }));
      const response = await model.invoke([message]);
      let content = response.content as string;

      
      let result: VisionAnalysisResult;
      try {
        
        content = content.replace(/```json/g, '').replace(/```/g, '').trim();
        const parsed = JSON.parse(content);

        result = {
          text: parsed.text || '',
          images: parsed.images || [],
          layout: parsed.layout || 'unknown',
          confidence: parsed.confidence ?? 0.8,
          pageIndex,
        };
      } catch (parseError) {
        
        this.logger.warn(`Failed to parse JSON response for ${imagePath}, using raw text`);
        result = {
          text: content,
          images: [],
          layout: 'unknown',
          confidence: 0.5,
          pageIndex,
        };
      }

      this.logger.log(
        this.i18nService.formatMessage('visionAnalysisSuccess', {
          path: imagePath,
          page: pageIndex ? ` (th page ${pageIndex})` : '',
          textLen: result.text.length,
          imgCount: result.images.length,
          layout: result.layout,
          confidence: (result.confidence * 100).toFixed(1)
        })
      );

      return result;
    } catch (error) {
      throw error; 
    }
  }

  
  private isRetryableError(error: any): boolean {
    const errorMessage = error.message?.toLowerCase() || '';
    const errorCode = error.status || error.code;

    
    if (errorCode === 429 || errorMessage.includes('rate limit') || errorMessage.includes('Too many requests')) {
      return true;
    }

    // 5xx Server error
    if (errorCode >= 500 && errorCode < 600) {
      return true;
    }

    
    if (errorMessage.includes('timeout') || errorMessage.includes('network') || errorMessage.includes('connection')) {
      return true;
    }

    return false;
  }

  
  private sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  
  async batchAnalyze(
    imagePaths: string[],
    modelConfig: VisionModelConfig,
    options: {
      startIndex?: number;
      skipQualityCheck?: boolean;
      onProgress?: (current: number, total: number, pageResult?: VisionAnalysisResult) => void;
    } = {},
  ): Promise<BatchAnalysisResult> {
    const { startIndex = 1, skipQualityCheck = false, onProgress } = options;
    const results: VisionAnalysisResult[] = [];
    let successCount = 0;
    let failedCount = 0;

    this.logger.log(this.i18nService.formatMessage('batchAnalysisStarted', { count: imagePaths.length }));
    this.logger.log(`🔧 Model configuration: ${modelConfig.modelId} (${modelConfig.baseUrl || 'OpenAI'})`);

    for (let i = 0; i < imagePaths.length; i++) {
      const imagePath = imagePaths[i];
      const pageIndex = startIndex + i;
      const progress = Math.round(((i + 1) / imagePaths.length) * 100);

      this.logger.log(`🖼️  Analyzing page ${pageIndex} (${i + 1}/${imagePaths.length}, ${progress}%)`);

      
      if (onProgress) {
        onProgress(i + 1, imagePaths.length);
      }

      
      if (!skipQualityCheck) {
        const quality = await this.checkImageQuality(imagePath);
        if (!quality.isGood) {
          this.logger.warn(`⚠️  Skipping page ${pageIndex} (Poor quality): ${quality.reason}`);
          failedCount++;
          continue;
        } else {
          this.logger.log(`✅ Page ${pageIndex} passed quality check (Score: ${(quality.score || 0).toFixed(2)})`);
        }
      }

      try {
        this.logger.log(`🔍 Analyzing page ${pageIndex} with Vision model...`);
        const startTime = Date.now();
        const result = await this.analyzeImage(imagePath, modelConfig, pageIndex);
        const duration = ((Date.now() - startTime) / 1000).toFixed(1);

        results.push(result);
        successCount++;

        this.logger.log(
          `✅ Analysis for page ${pageIndex} complete (Time taken: ${duration}s, ` +
          `Text: ${result.text.length} chars, ` +
          `Images: ${result.images.length}, ` +
          `Confidence: ${(result.confidence * 100).toFixed(1)}%)`
        );

        
        if (onProgress) {
          onProgress(i + 1, imagePaths.length, result);
        }
      } catch (error) {
        this.logger.error(this.i18nService.formatMessage('pageAnalysisFailed', { page: pageIndex }) + `: ${error.message}`);
        failedCount++;
      }
    }

    
    const estimatedCost = successCount * 0.01;

    this.logger.log(
      `🎉 Vision batch analysis complete! ` +
      `✅ Success: ${successCount} pages, ❌ Failed: ${failedCount} pages, ` +
      `💰 Estimated cost: $${estimatedCost.toFixed(2)}`
    );

    return {
      results,
      totalPages: imagePaths.length,
      successCount,
      failedCount,
      estimatedCost,
    };
  }

  
  async checkImageQuality(imagePath: string): Promise<{ isGood: boolean; reason?: string; score?: number }> {
    try {
      const stats = await fs.stat(imagePath);
      const sizeKB = stats.size / 1024;

      
      if (sizeKB < 5) {
        return { isGood: false, reason: `File is too small (${sizeKB.toFixed(2)}KB)`, score: 0 };
      }

      
      if (sizeKB > 10240) {
        return { isGood: false, reason: `File is too large (${sizeKB.toFixed(2)}KB)`, score: 0 };
      }

      
      let score = 0.5;
      if (sizeKB > 50) score += 0.2;
      if (sizeKB > 100) score += 0.2;
      if (sizeKB > 500) score += 0.1;

      score = Math.min(score, 1.0);

      return { isGood: true, score };
    } catch (error) {
      return { isGood: false, reason: this.i18nService.formatMessage('imageLoadError', { message: error.message }), score: 0 };
    }
  }

  
  isImageFile(mimetype: string): boolean {
    const imageMimeTypes = [
      'image/jpeg',
      'image/jpg',
      'image/png',
      'image/gif',
      'image/bmp',
      'image/webp',
    ];
    return imageMimeTypes.includes(mimetype);
  }

  
  private getMimeType(filePath: string): string {
    const ext = filePath.toLowerCase().split('.').pop();
    if (!ext) return 'image/jpeg';

    const mimeTypes: Record<string, string> = {
      jpg: 'image/jpeg',
      jpeg: 'image/jpeg',
      png: 'image/png',
      gif: 'image/gif',
      bmp: 'image/bmp',
      webp: 'image/webp',
    };
    return mimeTypes[ext] || 'image/jpeg';
  }

  
  async extractImageContent(
    imagePath: string,
    modelConfig: { baseUrl: string; apiKey: string; modelId: string },
  ): Promise<string> {
    const result = await this.analyzeImage(imagePath, modelConfig);
    return result.text;
  }
}

