from typing import Any


REQUIRED_QA_FIELDS = {
    "session_id",
    "qa_id",
    "raw_question",
    "normalized_question",
    "raw_answer",
    "normalized_answer",
    "suggested_standard_question",
    "suggested_standard_answer",
    "answer_person",
    "primary_topic",
    "problem_tags",
    "course_stage",
    "audience_tags",
    "emotion_intensity",
    "risk_level",
    "risk_types",
    "risk_notes",
    "need_desensitization",
    "desensitization_status",
    "suggested_review_status",
    "suggested_to_standard_qa",
    "source_timestamp",
    "review_notes",
}


def validate_ai_qa_items(payload: Any) -> list[dict[str, Any]]:
    if not isinstance(payload, list):
        raise ValueError("AI 返回必须是 JSON 数组")
    valid_items: list[dict[str, Any]] = []
    for index, item in enumerate(payload, start=1):
        if not isinstance(item, dict):
            raise ValueError(f"第 {index} 条 AI 结果不是对象")
        missing = REQUIRED_QA_FIELDS.difference(item)
        if missing:
            raise ValueError(f"第 {index} 条 AI 结果缺少字段: {', '.join(sorted(missing))}")
        valid_items.append(item)
    return valid_items

