import csv


def read_crubadan_language_model(pairs, config, gram_type):
    """
    Read a Crubadan language model for a (language name, ISO code) pair.

    Args:
        pairs: a list of (name, code) pairs to construct models for
        config: model parameters
        gram_type: what type of gram to use - 'character' or 'word'
    Returns:
        list of tuples of ngrams, or None if no language model exists for
        the given name-ISO pairing
    """
    if gram_type != 'character' and gram_type != 'word':
        raise ValueError("argument 'gram_type' not 'character' or 'word'")


    base_path = config['locations']['crubadan-language-model']

    table = open(config['locations']['crubadan-directory-index'], encoding='utf8')
    reader = csv.reader(table)
    header = next(reader) # discard header row

    dir_map = {}
    for row in reader:
        name = row[0]
        iso = row[1]
        directory = row[2].strip()
        dir_map[(name, iso)] = directory
    table.close()

    if gram_type == 'character':
        file_basename = {
            3: "-chartrigrams.txt"
        }.get(int(config['parameters']['crubadan-char-size']))
    else:
        file_basename = {
            1: "-words.txt",
            2: "-wordbigrams.txt"
        }.get(int(config['parameters']['crubadan-word-size']))

    all_lms = {}
    for lang_name, iso_code in pairs:
        try:
            this_dir = dir_map[(lang_name, iso_code)]
            crubadan_code = this_dir.split("_")[1]
            with open("{}/{}/{}{}".format(base_path, this_dir, crubadan_code, file_basename), encoding='utf8') as f:
                lines = f.readlines()
        except (FileNotFoundError, KeyError, IndexError):
            continue

        lm = set()
        for line in lines:
            if line.strip() == '':
                continue
            line = line.split()[:-1]
            feature = tuple(line[0]) if gram_type == 'character' else tuple(line)
            lm.add(feature)
        all_lms[(lang_name, iso_code)] = lm
    return all_lms