/**
 * 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('🚀 开始 Vision Pipeline 端到端测试\n');

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

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

    // 检查健康状态
    const isHealthy = await libreOffice.healthCheck();
    console.log(`LibreOffice 健康检查: ${isHealthy ? '✅ 通过' : '❌ 失败'}`);

    if (!isHealthy) {
      console.log('⚠️  LibreOffice 服务未运行，跳过后续测试');
      return;
    }

    // 2. 测试 PDF 转图片服务
    console.log('\n=== 测试 2: PDF 转图片服务 ===');
    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(`测试 PDF: ${path.basename(testPdf)}`);

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

      console.log(`✅ 转换成功: ${result.images.length}/${result.totalPages} 页`);
      console.log(`   成功: ${result.successCount}, 失败: ${result.failedCount}`);

      // 清理测试文件
      await pdf2Image.cleanupImages(result.images);
      console.log('✅ 临时文件已清理');
    } else {
      console.log('⚠️  测试 PDF 文件不存在，跳过此测试');
    }

    // 3. 测试 Vision Pipeline 完整流程
    console.log('\n=== 测试 3: Vision Pipeline 完整流程 ===');
    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(`测试文件: ${path.basename(testFile)}`);

      // 模式推荐测试
      const recommendation = await visionPipeline.recommendMode(testFile);
      console.log(`模式推荐: ${recommendation.recommendedMode}`);
      console.log(`原因: ${recommendation.reason}`);
      if (recommendation.estimatedCost) {
        console.log(`预估成本: $${recommendation.estimatedCost.toFixed(2)}`);
      }
      if (recommendation.estimatedTime) {
        console.log(`预估时间: ${recommendation.estimatedTime.toFixed(1)}s`);
      }
      if (recommendation.warnings && recommendation.warnings.length > 0) {
        console.log(`警告: ${recommendation.warnings.join(', ')}`);
      }

      // 注意：完整流程测试需要配置 Vision 模型 API Key
      // 这里只测试流程结构
      console.log('\n✅ Vision Pipeline 模块已正确配置');
      console.log('   注意: 完整流程测试需要配置有效的 Vision 模型 API Key');

    } else {
      console.log('⚠️  未找到测试文件，跳过完整流程测试');
    }

    // 4. 检查环境配置
    console.log('\n=== 测试 4: 环境配置检查 ===');
    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}: 未配置`);
      }
    }

    console.log('\n🎉 所有基础测试完成！');

  } catch (error) {
    console.error('❌ 测试失败:', error.message);
    console.error(error.stack);
  } finally {
    await app.close();
  }
}

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

export { testVisionPipeline };
