<?php

namespace App\Services;

class QuestionGenerationService
{
    public function generateFromSource(string $sourceText): array
    {
        $prompt = app(QuestionPromptService::class)->buildQuestionFromSourcePrompt($sourceText);

        try {
            $result = app(AiClientService::class)->callJson($prompt);
        } catch (\Throwable $e) {
            return [
                'success' => false,
                'message' => 'AI 生成失败',
                'prompt' => $prompt,
                'question' => [],
            ];
        }

        $question = $this->normalizeGeneratedQuestion($result);

        return [
            'success' => true,
            'message' => '生成完成',
            'prompt' => $prompt,
            'question' => $question,
        ];
    }

    public function normalizeGeneratedQuestion(array $payload): array
    {
        return [
            'stem' => $payload['stem'] ?? '',
            'options' => $payload['options'] ?? null,
            'answer' => $payload['answer'] ?? null,
            'solution' => $payload['solution'] ?? null,
            'question_type' => $payload['question_type'] ?? null,
            'difficulty' => $payload['difficulty'] ?? null,
            'knowledge_points' => $payload['knowledge_points'] ?? [],
            'solution_steps' => $payload['solution_steps'] ?? [],
            'abilities' => $payload['abilities'] ?? [],
        ];
    }
}
