'''Random Retriever'''
import torch
import torch.nn as nn

import numpy as np
from tqdm import tqdm

from common import get_logger
from .base_retrieve import BaseRetriever

logger = get_logger(__name__)


class RandomRetriever(BaseRetriever):
    def __init__(self, task,ice_dataloader, candidate_dataloader, inferencer, device, metric_model, metric_tokenizer):
        super().__init__(task, ice_dataloader, candidate_dataloader, inferencer, device, metric_model, metric_tokenizer)
        
    def raw_retrieve(self, test_forward, ice_embed_list, ice_forward, base_index, ice_num, texts, labels):
        rtr_idx_list = [[] for _ in range(len(test_forward))]
        rtr_score_list = [[] for _ in range(len(test_forward))]
        cos = nn.CosineSimilarity(dim=1, eps=1e-6)

        for entry in tqdm(test_forward):
            idx = entry['metadata']['id']
            embed = np.expand_dims(entry['embed'], axis=0)
            rtr_idx_list[idx] = np.random.choice(len(ice_forward), ice_num, replace=False).tolist()
            cos_score = []
            for ice_idx in rtr_idx_list[idx]:
                ice_embed = np.expand_dims(ice_forward[ice_idx]['embed'], axis=0)
                cos_score.append(float(np.array(cos(torch.from_numpy(ice_embed), torch.from_numpy(embed)))))
            rtr_score_list[idx] = cos_score
            
        return rtr_idx_list, rtr_score_list
    
    
