"""
Utility functions to manipulate files in the project.
"""
import random

def number_of_lines(file: str) -> int:
    """Return the number of lines in a file (given by filename)."""
    return sum(1 for line in open(file, 'rb'))

def sample_lines(filename: str, k: int =1):
    """Return a sample of k lines of a file (given by filename)."""# {{{
    selected_lines = random.sample(range(number_of_lines(filename)), k=k)
    sample: list[str] = [''] * k
    sample_hd_idx = 0
    with open(filename, encoding="utf8") as file:
        for num, line in enumerate(file):
            if num in selected_lines:
                # remove the trailing \n
                sample[sample_hd_idx] = line[:-1]
                sample_hd_idx += 1
    return sample# }}}

def random_line(filename: str):
    """Select one line randomly from a file (given by filename)."""
    return sample_lines(filename, k=1)[0]
