import copy
import random


def shuffle_prompt(prompt, items, item_number, item_order):
    """
    Shuffles the previoisly queried items to avoid recency bias.

    Parameters
    ----------
    prompt : Str
        The initial prompt where the items are added.
    items : List
        A list of items to be shuffled.
    item_number : Int
        needed because the first two items can't be randomized.
    item_order : List
        The order in which items are queried. Needed for logging the item order. The function shuffles these to the same order as is used in the prompt.

    Returns
    -------
    prompt : TYPE
        The shuffled prompt.
    item_order : TYPE
        In what order the items are in the prompt.

    """
    item_order = copy.deepcopy(item_order)
    items_shuffled = []
    items_temp=copy.deepcopy(items)
    ## for the first two items, there can't be any randomization
    if item_number == 0: 
        prompt = prompt + items_temp[0] + "\"\n\nParticipant:"
    elif item_number == 1:
        prompt = prompt + items_temp[0] + items_temp[1] + "\"\n\nParticipant:"
    else:
        last_item = items_temp.pop(-1)       # Save and remove from the list the item to be queried
        last_item_for_item_order = item_order.pop(-1)       # Save and remove from the list the item to be queried
        order = random.sample(range(len(items_temp)), k=len(items_temp))   # random order
        items_shuffled = [items_temp[i] for i in order]
        item_order = [item_order[i] for i in order]
        #items_shuffled = random.sample(items_temp, len(items_temp)) 
        n_items = len(items_temp)
        for i in range(n_items):
            prompt = prompt + items_shuffled[i]
        # Finally add the final item for the next query
        prompt = prompt + last_item + "\"\n\nParticipant:"
        item_order.append(last_item_for_item_order)
    
    return prompt, item_order