from pathlib import Path


def load_texmfbd(lsR, ctanDict):
    """
    Create a dictionnary from the ls-R database from the LaTeX installation

    :param lsR: The path to the TEXMF/ls-R
    :param ctanDict: A dictionnary built from the CTAN package list

    :return: a tuple (lsRdb, allfiles)
        - lsRdb is a dictionnary mapping for every package in ctanDict all the .sty, .cls, .def
          files listed under that dictionnary in lsR
        - allfiles is an array of all the .sty, .cls, .def files listed in lsR
    """
    lsRdb = {}
    pkg = None
    pkgfiles = []
    allfiles = []
    allpkgs = ctanDict.keys()
    with open(lsR) as fd:
        for line in fd:
            line = line.rstrip('\n')
            if line.startswith('./doc') or line.startswith('./source'):
                # Skip source and doc entries
                continue
            if line.endswith(':') and line.startswith('./'):
                # Enter a new package
                pkg = None
                for part in reversed(Path(line[0:-1]).parts):
                    if part in allpkgs:
                        pkg = part
                        break
                pkgfiles = []
            if pkg is None:
                continue
            if line != '':
                pkgfile = Path(line)
                if pkgfile.suffix in ['.sty', '.def', '.cls']:
                    pkgfiles.append(pkgfile.name)
                    allfiles.append(pkgfile.name)
            else:
                if len(pkgfiles) > 0:
                    if pkg not in lsRdb:
                        lsRdb[pkg] = []
                    lsRdb[pkg].extend(pkgfiles)
                pkg = None
    return (lsRdb, allfiles)