<?php

namespace App\Services;

use App\Models\OCRRecord;
use App\Models\OCRQuestionResult;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class LearningAnalyticsClient
{
    /**
     * Send OCR record data to LearningAnalytics for AI analysis.
     *
     * @param OCRRecord $record
     * @return array|null Returns array of results keyed by question id, or null on failure.
     */
    public function analyze(OCRRecord $record): ?array
    {
        $url = env('LEARNING_ANALYTICS_URL') . '/api/analysis/process-answers';

        $payload = [
            'exam_id' => $record->exam_id ?? 'exam_' . $record->id,
            'student_id' => $record->student_id ?? 'student_' . $record->id,
            'ocr_record_id' => $record->id,
            'teacher_name' => 'System', // 可以根据需要调整
            'analysis_type' => 'mastery',
            'questions' => $record->questions->map(function (OCRQuestionResult $q) {
                return [
                    'question_id' => $q->id,
                    'question_number' => (string)($q->question_number ?? $q->id),
                    'kp_code' => $q->kp_code,
                    'student_answer' => $q->manual_answer ?? $q->student_answer,
                    'correct_answer' => $q->correct_answer, // 如果有正确答案
                    'teacher_validated' => !is_null($q->manual_answer), // 手动答案表示已校验
                    'ocr_confidence' => $q->answer_confidence ?? 1.0,
                    'score_value' => $q->score_value,
                    'mark_detected' => $q->mark_detected,
                ];
            })->toArray(),
        ];

        try {
            $response = Http::timeout(30)->post($url, $payload);
            if ($response->successful()) {
                // Expected format: { "success": true, "data": { "question_results": [...] } }
                $data = $response->json();
                $questionResults = $data['data']['question_results'] ?? null;

                // Save analysis results back to database
                if ($questionResults) {
                    $this->saveAnalysisResults($record, $questionResults);
                }

                return $questionResults;
            }
            Log::error('LearningAnalytics API error', ['status' => $response->status(), 'body' => $response->body()]);
        } catch (\Exception $e) {
            Log::error('LearningAnalytics request failed', ['exception' => $e]);
        }
        return null;
    }

    /**
     * Save AI analysis results back to OCR question results.
     *
     * @param OCRRecord $record
     * @param array $questionResults
     * @return void
     */
    private function saveAnalysisResults(OCRRecord $record, array $questionResults): void
    {
        foreach ($questionResults as $result) {
            $questionId = $result['question_id'] ?? null;
            if (!$questionId) continue;

            $questionResult = $record->questions()->where('id', $questionId)->first();
            if (!$questionResult) continue;

            // Extract relevant data from analysis result
            $aiScore = $result['score'] ?? null;
            $aiFeedback = $result['suggestions'] ?? $result['reason'] ?? null;
            $aiConfidence = $result['confidence'] ?? null;
            $aiAnalysisMethod = $result['analysis_method'] ?? null;

            // Update the question result with AI analysis data
            $questionResult->update([
                'ai_score' => $aiScore,
                'ai_feedback' => $aiFeedback,
                'ai_confidence' => $aiConfidence,
                'ai_analysis_method' => $aiAnalysisMethod,
                'ai_analyzed_at' => now(),
            ]);
        }
    }
}
