import csv
import os
import sys

import tabulate


def main():
    try:
        file_name = sys.argv[1]
    except IndexError:
        print("Too few command-line arguments")
        sys.exit(1)
    if len(sys.argv) > 2:
        print("Too many command-line arguments")
        sys.exit(1)
    if not os.path.isfile(file_name):  # Or try opening and catch FileNotFoundError
        print(f"File does not exist")
        sys.exit(1)
    if not file_name.endswith('.csv'):
        print(f"Not a CSV file")
        sys.exit(1)
    grid = get_grid_from_csv(file_name)
    print(grid)


def get_grid_from_csv(file_name: str) -> str:
    headers = None
    table = []
    with open(file_name, 'r') as file_object:
        reader = csv.DictReader(file_object)
        for row in reader:
            if headers is None:
                headers = list(row.keys())
            table.append(tuple(row[field] for field in row))
    return tabulate.tabulate(table, headers, tablefmt="grid")

if __name__ == "__main__":
    main()
