from typing import Sequence
import json


def _load_pair_dirs(pair: str, dirs: Sequence[str]):
    """
    Load pair data from disk split into multiple ordered directories.

    This is a simplified version of Market.load_pair_dirs that doesn't do sparse tick expansion.

    Arguments:
        pair:  The currency pair to load data for.
        dirs:  A list of ordered directories containing the split data for the pair*.

    Returns:
        (tuple):  A tuple containing:
            (str):       The pair that was passed, for joining on async tasks.
            list(dict):  A list of the loaded pair data.

    *Directories are assumed to be in sequential order with respect to the data, otherwise large gaps will appear in
    the loaded data.
    """

    ticks = []

    for dirname in dirs:
        filename = dirname + pair + '.json'

        try:
            with open(filename) as file:
                new_ticks = json.load(file)
        except FileNotFoundError:
            continue

        if new_ticks is None:
            continue

        if ticks:
            last_time = ticks[-1]['T']
            next_time = 0.0
            start_index = 0

            for start_index, tick in enumerate(new_ticks):
                next_time = tick['T']
                if next_time > last_time:
                    new_ticks = new_ticks[start_index:]
                    break

            if next_time <= last_time:
                continue

        ticks.extend(new_ticks)

    return (pair, ticks)