#!/usr/bin/env python3

import os
import sys


def main(*args):
    for file_path in args[1:]:
        pretty_print_file(file_path)


def pretty_print_file(file_path):
    if not os.path.exists(file_path):
        print(f'Cannot find file: {file_path}', file=sys.stderr)

    table = read_table(file_path)
    pretty_print_table(table)


def read_table(file_path):
    table = []
    delimiter = '\t'
    with open(file_path, 'r', encoding='utf-16-le') as file:
        for line in file:
            row = line.rstrip('\n').rstrip('\r').split(delimiter)
            table.append(row)
    return table


def pretty_print_table(table):
    assert len(table) > 0

    n_columns = max(len(row) for row in table)
    table = [
        [*row, *([''] * empty_cells_count)]
        for row in table[:]
        for empty_cells_count in [max(0, n_columns - len(row))]
    ]

    col_widths = {
        col_idx: max(len(row[col_idx]) for row in table)
        for col_idx in range(n_columns)
    }
    to_print_lines = [
        '+-' + '-+-'.join('-' * width for _, width in sorted(col_widths.items())) + '-+', '| ' +
        ' | '.join(f'{c:{col_widths[col_idx]}}' for col_idx, c in enumerate(table[0])) + ' |',
        '+-' + '-+-'.join('-' * width for _, width in sorted(col_widths.items())) + '-+',
        *(['| ' + ' | '.join(f'{c:{col_widths[col_idx]}}' for col_idx, c in enumerate(row)) + ' |' for row in table[1:]]),
        '+-' + '-+-'.join('-' * width for _, width in sorted(col_widths.items())) + '-+',
    ]

    for line in to_print_lines:
        print(line)


if __name__ == '__main__':
    sys.exit(main(*sys.argv))
