import market_trade.constants
import json


def get_lines_count(filepath):
    """
    This function gets filepath and returns count of the lines inside it (by default delimiter)
    :param filepath: pathlike, preffered to be pathlib
    :return: integer, coutn of the lines
    """
    with open(filepath, mode="r", encoding="utf-8") as counted_file:
        line_count = sum(1 for _ in counted_file)
    return line_count


if __name__ == '__main__':
    shares_maxsize_by_figi = {}

    for figi_dir in market_trade.constants.SHARES_TRADES_PATH.iterdir():

        # we check if the path is dir, because there are unwanted files present
        if figi_dir.is_dir():

            # compiling all the shares files to list
            shares_filepaths = list(figi_dir.iterdir())

            # getting maximum file by line count
            maxsize_shares_filepath = max(shares_filepaths, key=get_lines_count)

            # setting maximum file value
            shares_maxsize_by_figi[figi_dir.name] = get_lines_count(maxsize_shares_filepath)

    # sorting the liquidity stats by the size
    shares_sorted_by_liquidity = dict(sorted(shares_maxsize_by_figi.items(),
                                        key=lambda dict_item: dict_item[1],
                                        reverse=True))

    # saving them as a json stats file
    with open(market_trade.constants.SHARES_STATS_PATH, mode="w", encoding="utf-8") as stats_file:
        json.dump(shares_sorted_by_liquidity, stats_file, ensure_ascii=False)
