<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Services\QuestionBankService;
use Illuminate\Support\Facades\DB;

class QuestionBankOcrGenerationTest extends TestCase
{
    /**
     * 不使用数据库事务,使用真实数据库
     */
    protected $connectionsToTransact = [];

    /**
     * 测试从MySQL OCR数据生成题库
     * 
     * 此测试使用MySQL中已OCR识别的题目,避免重复调用第三方OCR接口
     */
    public function test_generate_questions_from_mysql_ocr_data()
    {
        // 强制使用MySQL连接
        config(['database.default' => 'mysql']);

        echo "\n" . str_repeat("=", 80) . "\n";
        echo "🧪 OCR题目生成题库测试 (使用MySQL已有数据)\n";
        echo str_repeat("=", 80) . "\n\n";

        // 1. 从MySQL读取OCR识别的题目
        $recordId = 12; // 使用已有的OCR记录
        echo "📚 从MySQL读取OCR记录 #{$recordId} 的题目...\n";

        $ocrQuestions = DB::connection('mysql')
            ->table('ocr_question_results')
            ->where('ocr_record_id', $recordId)
            ->orderBy('question_number')
            ->get();

        if ($ocrQuestions->isEmpty()) {
            echo "❌ 未找到OCR记录 {$recordId} 的题目数据\n";
            $this->markTestSkipped("No OCR data found for record {$recordId}");
            return;
        }

        echo "✅ 获取到 {$ocrQuestions->count()} 道题目\n\n";

        // 2. 构建请求数据(只需要题目文本,不需要学生答案)
        $questions = [];
        foreach ($ocrQuestions as $oq) {
            $questions[] = [
                'question_number' => $oq->question_number,
                'question_text' => $oq->question_text ?? ''
            ];

            echo "  题目 {$oq->question_number}: " . mb_substr($oq->question_text ?? '', 0, 50) . "...\n";
        }
        echo "\n";

        // 3. 调用QuestionBankService生成题目
        echo "🤖 调用题库服务生成题目...\n";
        echo "API地址: " . config('services.question_bank.base_url', 'http://localhost:5015') . "\n\n";

        $service = app(QuestionBankService::class);
        $result = $service->generateQuestionsFromOcr($questions, '高一', '数学');

        // 4. 验证结果
        echo str_repeat("=", 80) . "\n";
        echo "📊 分析结果\n";
        echo str_repeat("=", 80) . "\n\n";

        // 输出完整响应用于调试
        echo "API返回数据:\n";
        echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";

        $this->assertIsArray($result, "返回结果应该是数组");
        $this->assertEquals('success', $result['status'] ?? '', "生成应该成功");

        if ($result['status'] !== 'success') {
            echo "❌ 生成失败: " . ($result['message'] ?? 'Unknown error') . "\n";
            $this->fail("OCR题目生成失败: " . ($result['message'] ?? 'Unknown error'));
            return;
        }

        echo "✅ 生成成功\n";
        echo "使用模型: " . ($result['model_used'] ?? 'unknown') . "\n";
        echo "生成数量: " . ($result['generated_count'] ?? 0) . "/" . ($result['total_count'] ?? 0) . "\n\n";

        $generatedQuestions = $result['questions'] ?? [];
        $this->assertNotEmpty($generatedQuestions, "应该返回生成的题目");

        // 5. 验证每道生成的题目
        foreach ($generatedQuestions as $index => $generated) {
            echo str_repeat("-", 60) . "\n";
            echo "题目 " . ($index + 1) . "\n";
            echo str_repeat("-", 60) . "\n";

            // 验证必要字段
            $this->assertArrayHasKey('question_id', $generated, "题目应该有题库ID");
            $this->assertArrayHasKey('question_type', $generated, "题目应该有题型");
            $this->assertArrayHasKey('kp_code', $generated, "题目应该有知识点");
            $this->assertArrayHasKey('saved', $generated, "题目应该有保存状态");

            // 显示生成结果
            echo "📝 题目ID: " . ($generated['question_id'] ?? 'N/A') . "\n";
            echo "📊 题型: " . ($generated['question_type'] ?? 'N/A') . "\n";
            echo "🎯 知识点: " . ($generated['kp_code'] ?? 'N/A') . "\n";
            echo "   难度: " . ($generated['difficulty'] ?? 'N/A') . "\n";
            echo "💾 已保存: " . ($generated['saved'] ? '是' : '否') . "\n\n";

            // 验证已保存
            $this->assertTrue($generated['saved'] ?? false, "题目应该已保存到题库");
        }

        // 6. 验证题目已保存到QuestionBankService数据库
        echo str_repeat("=", 80) . "\n";
        echo "🔍 验证题目已保存到题库\n";
        echo str_repeat("=", 80) . "\n\n";

        $savedCount = 0;
        foreach ($generatedQuestions as $generated) {
            if ($generated['saved'] ?? false) {
                $savedCount++;
            }
        }

        echo "✅ 成功保存 {$savedCount}/{$result['generated_count']} 道题目到题库\n";
        $this->assertEquals($result['generated_count'], $savedCount, "所有生成的题目都应该已保存");

        echo str_repeat("=", 80) . "\n";
        echo "✅ 测试完成\n";
        echo str_repeat("=", 80) . "\n\n";

        // 最终断言
        $this->assertTrue(true, "OCR题目生成题库测试通过");
    }

    /**
     * 测试QuestionBankService健康检查
     */
    public function test_question_bank_service_health()
    {
        echo "\n🏥 检查题库服务健康状态...\n";

        $service = app(QuestionBankService::class);
        $isHealthy = $service->checkHealth();

        $this->assertTrue($isHealthy, "题库服务应该健康");
        echo "✅ 题库服务运行正常\n\n";
    }
}
