/**
 * Vision Pipeline 端到端测试脚本
 *
 * 测试流程：
 * 1. LibreOffice 文档转换
 * 2. PDF 转图片
 * 3. Vision 模型分析
 * 4. 完整流程集成
 */

import { NestFactory } from '@nestjs/core';
import { AppModule } from './src/app.module';
import { VisionPipelineService } from './src/vision-pipeline/vision-pipeline.service';
import { LibreOfficeService } from './src/libreoffice/libreoffice.service';
import { Pdf2ImageService } from './src/pdf2image/pdf2image.service';
import { VisionService } from './src/vision/vision.service';
import * as fs from 'fs/promises';
import * as path from 'path';

async function testVisionPipeline() {
  console.log('🚀 Starting Vision Pipeline end-to-end test\n');

  // 初始化 Nest 应用
  const app = await NestFactory.createApplicationContext(AppModule, {
    logger: ['error', 'warn', 'log'],
  });

  try {
    // 1. 测试 LibreOffice 服务
    console.log('=== Test 1: LibreOffice service ===');
    const libreOffice = app.get(LibreOfficeService);

    // 检查健康状态
    const isHealthy = await libreOffice.healthCheck();
    console.log(`LibreOffice health check: ${isHealthy ? '✅ Passed' : '❌ Failed'}`);

    if (!isHealthy) {
      console.log('⚠️  LibreOffice service not running, skipping subsequent tests');
      return;
    }

    // 2. 测试 PDF 转图片服务
    console.log('\n=== Test 2: PDF to Image service ===');
    const pdf2Image = app.get(Pdf2ImageService);

    const testPdf = '/home/fzxs/workspaces/demo/simple-kb/uploads/file-1766236004300-577549403.pdf';
    if (await fs.access(testPdf).then(() => true).catch(() => false)) {
      console.log(`Test PDF: ${path.basename(testPdf)}`);

      const result = await pdf2Image.convertToImages(testPdf, {
        density: 150,  // 降低密度以加快测试
        quality: 75,
        format: 'jpeg',
      });

      console.log(`✅ Conversion successful: ${result.images.length}/${result.totalPages} pages`);
      console.log(`   Success: ${result.successCount}, Failed: ${result.failedCount}`);

      // 清理测试文件
      await pdf2Image.cleanupImages(result.images);
      console.log('✅ Temporary files cleaned up');
    } else {
      console.log('⚠️  Test PDF file does not exist, skipping this test');
    }

    // 3. 测试 Vision Pipeline 完整流程
    console.log('\n=== Test 3: Vision Pipeline complete flow ===');
    const visionPipeline = app.get(VisionPipelineService);

    // 检查是否有支持的测试文件
    const testFiles = [
      '/home/fzxs/workspaces/demo/simple-kb/uploads/file-1766236004300-577549403.pdf',
      '/home/fzxs/workspaces/demo/simple-kb/uploads/file-1765705143480-947461268.pdf',
    ];

    let testFile: string | null = null;
    for (const file of testFiles) {
      if (await fs.access(file).then(() => true).catch(() => false)) {
        testFile = file;
        break;
      }
    }

    if (testFile) {
      console.log(`Test file: ${path.basename(testFile)}`);

      // 模式推荐测试
      const recommendation = await visionPipeline.recommendMode(testFile);
      console.log(`Recommended mode: ${recommendation.recommendedMode}`);
      console.log(`Reason: ${recommendation.reason}`);
      if (recommendation.estimatedCost) {
        console.log(`Estimated cost: $${recommendation.estimatedCost.toFixed(2)}`);
      }
      if (recommendation.estimatedTime) {
        console.log(`Estimated time: ${recommendation.estimatedTime.toFixed(1)}s`);
      }
      if (recommendation.warnings && recommendation.warnings.length > 0) {
        console.log(`Warnings: ${recommendation.warnings.join(', ')}`);
      }

      // 注意：完整流程测试需要配置 Vision 模型 API Key
      // 这里只测试流程结构
      console.log('\n✅ Vision Pipeline module correctly configured');
      console.log('   Note: Full flow testing requires a valid Vision model API Key');

    } else {
      console.log('⚠️  Test files not found, skipping complete flow test');
    }

    // 4. 检查环境配置
    console.log('\n=== Test 4: Environment configuration check ===');
    const configService = app.get(require('@nestjs/config').ConfigService);

    const requiredEnvVars = [
      'LIBREOFFICE_URL',
      'TEMP_DIR',
      'ELASTICSEARCH_HOST',
      'TIKA_HOST',
    ];

    for (const envVar of requiredEnvVars) {
      const value = configService.get(envVar);
      if (value) {
        console.log(`✅ ${envVar}: ${value}`);
      } else {
        console.log(`❌ ${envVar}: Not configured`);
      }
    }

    console.log('\n🎉 All basic tests completed!');

  } catch (error) {
    console.error('❌ Test failed:', error.message);
    console.error(error.stack);
  } finally {
    await app.close();
  }
}

// 运行测试
if (require.main === module) {
  testVisionPipeline().catch(console.error);
}

export { testVisionPipeline };
