import json
import random


def pop_random(lst):
    """Randomly pop an element from a list."""
    idx = random.randrange(0, len(lst))
    return lst.pop(idx)


def random_pairs(lst):
    """Returns random unique pairs from list."""
    pairs = []
    while len(lst) > 1:
        rand1 = pop_random(lst)
        rand2 = pop_random(lst)
        pair = rand1, rand2
        pairs.append(pair)

    return pairs


def write_jsonl(lst, path):
    """Writes list of dictionaries to a jsonl file."""
    with open(path, "w", encoding="utf-8") as f:
        for entry in lst:
            json.dump(entry, f)
            f.write("\n")


def read_jsonl(path):
    """Reads jsonl file and returns a list of dicts."""
    data = []
    with open(path, "r") as f:
        for entry in f:
            data.append(json.loads(entry))

    return data
