"""Phase 4-B v1 세션 단위 RAG — documents 만 (같은 토픽 다른 문제는 prompt 에 직접 박힘).

PR-3 explanation_rag 의 _gather_document_evidence 만 재사용. query 는 wrong/unsure
question_text 를 concat (첫 80자 × 최대 10개).
"""

from __future__ import annotations

from sqlalchemy.ext.asyncio import AsyncSession

from ai.client import AIClient
from models.study_question import StudyQuestion
from services.study.explanation_rag import (
    EvidenceItem,
    _gather_document_evidence,
    _truncate,
)


async def gather_session_summary_context(
    session: AsyncSession,
    *,
    user_id: int,
    study_topic_id: int,
    wrong_unsure_questions: list[StudyQuestion],
) -> list[EvidenceItem]:
    """세션 분석용 documents RAG. 빈 리스트 반환은 정상 (4-B 정책상 호출 진행).

    query: wrong/unsure question_text 첫 80자를 " | " 로 join (최대 10개).
    """
    if not wrong_unsure_questions:
        return []
    query = " | ".join(
        _truncate(q.question_text or "", 80)
        for q in wrong_unsure_questions[:10]
    )
    if not query.strip():
        return []
    client = AIClient()
    try:
        return await _gather_document_evidence(
            session, user_id, study_topic_id, query, client
        )
    finally:
        await client.close()
