from collections import defaultdict

from data_sync.utils import to_epoch, tzlc
from qa.models.answer import AnswerTop, QuestionTag
from utils.rpc import get_rpc_invoker

rpc = get_rpc_invoker()


def get_qa_tops(pks):
    results = []
    queryset = AnswerTop.objects.filter(id__in=pks)
    question_ids = list(filter(None, queryset.values_list("question_id", flat=True)))

    q_top_tags = defaultdict(list)
    for q_id, t_id in QuestionTag.objects.filter(question_id__in=question_ids).values_list("question_id", "tag"):
        q_top_tags[q_id].append(t_id)

    for qa_top in queryset:
        _c_time = tzlc(qa_top.create_time)
        _s_time = tzlc(qa_top.start_time)
        _e_time = tzlc(qa_top.end_time)
        _data = {
            "id": qa_top.id,
            "question_id": qa_top.question_id,
            "answer_id": qa_top.answer_id,
            "top_type": qa_top.top_type,
            "enable": qa_top.enable,
            "create_time": _c_time,
            "start_time": _s_time,
            "end_time": _e_time,
            "create_time_epoch": to_epoch(_c_time),
            "start_time_epoch": to_epoch(_s_time),
            "end_time_epoch": to_epoch(_e_time),
        }
        tag_ids = q_top_tags.get(qa_top.question_id, [])
        _data["tag_ids"] = tag_ids
        _data['closure_tag_ids'] = rpc['api/tag/closure_tags'](tag_ids=tag_ids) if tag_ids else []

        results.append(_data)

    for result in results:
        if not isinstance(result['closure_tag_ids'], list):
            result['closure_tag_ids'] = list(map(lambda tag: tag['id'], result['closure_tag_ids'].unwrap()))

    return results