"""
AI 自动出题器
基于药典原文 + 考试大纲知识点，使用 LLM 自动生成 A/B/X 型试题
"""
import json
import logging
from typing import Optional
from dataclasses import dataclass

logger = logging.getLogger(__name__)


@dataclass
class GeneratedQuestion:
    question_type: str  # A / B / X
    subject: str
    chapter_id: str
    difficulty: int
    content: str
    options: list[str]
    answer: str
    explanation: str
    source: str
    knowledge_point_ids: list[str]


class QuestionGenerator:
    def __init__(self, llm_client=None):
        self.llm = llm_client

    def generate(
        self,
        knowledge_point: dict,
        drug_reference: Optional[dict] = None,
        question_type: str = "A",
        count: int = 3,
    ) -> list[GeneratedQuestion]:
        """
        Phase 2 实现。
        基于知识点 + 药典原文，生成指定类型和数量的题目。
        """
        return []

    def generate_batch(
        self,
        knowledge_points: list[dict],
        question_counts: dict = None,
    ) -> list[GeneratedQuestion]:
        """批量出题，按题型比例分配"""
        if question_counts is None:
            question_counts = {"A": 4, "B": 3, "X": 3}
        return []

    def validate_answer(self, question: GeneratedQuestion) -> bool:
        """
        验证答案是否能在原文中找到明确依据。
        若验证失败，标记需要人工审核。
        """
        return True

    def export_jsonl(self, questions: list[GeneratedQuestion], output_path: str):
        """导出为 JSONL 格式，用于人工审核"""
        with open(output_path, "w", encoding="utf-8") as f:
            for q in questions:
                f.write(json.dumps({
                    "question_type": q.question_type,
                    "subject": q.subject,
                    "chapter_id": q.chapter_id,
                    "difficulty": q.difficulty,
                    "content": q.content,
                    "options": q.options,
                    "answer": q.answer,
                    "explanation": q.explanation,
                    "source": q.source,
                    "knowledge_point_ids": q.knowledge_point_ids,
                }, ensure_ascii=False) + "\n")
        logger.info(f"Exported {len(questions)} questions to {output_path}")
