import random


def hsk_grabber(
    target_hsk: float, search_str: str = "", deviation: float = 0.2, limit: int = 10
):
    """
    Finds HSK sentences at `target_hsk` level, with a ± deviation of `deviation`.

    Search for sentences that contain words (space-separated) with `search_str` and set a sentence output limit with `limit`.
    """
    sentences = []
    with open("data/sentences.tsv", "r", encoding="utf-8") as file:
        for line in file.read().splitlines()[1:]:
            line = line.split("\t")
            in_line = True
            for char in search_str.split(" "):
                if char not in line[0]:
                    in_line = False

            if in_line == True:
                if (
                    float(line[3]) < target_hsk + deviation
                    and float(line[3]) > target_hsk - deviation
                ):
                    sentences.append((line[0], line[1], line[2], line[3]))

    random.shuffle(sentences)

    return sentences[:limit]