#!/usr/bin/env python3
# SPDX-License-Identifier: WTFPL

# - takes a malformed ASCII-drawn table as stdin or file, for example:
#    +-----+-----+
#    | foo | bar |
#    +-----+-----+
#    | a long cell | short |
#    | x | longer cell ? |
#    +--+--+
#
# - outputs a well-formed table:
#    +-------------+---------------+
#    |     foo     |      bar      |
#    +-------------+---------------+
#    | a long cell |     short     |
#    |      x      | longer cell ? |
#    +-------------+---------------+

# /// script
# dependencies = ["prettytable"]
# ///

from fileinput import input
import re
import sys

from prettytable import PrettyTable, HEADER


replacements = {
    '─=': '-',
    '│': '|',
    '┘┐└┌├┬┼┴┤': '+',
}
box_chars = ''.join(replacements.keys()) + ''.join(replacements.values())
box_chars_regex = re.compile(r'[%s\s]+' % re.escape(box_chars))


table_regex = re.compile(
    r"""
    ^
    \s*(
        [-─=]+
        | [+|│┌└├] [+-┬┼┴─\s]* [+|│┤┘┐]
        | [|│] .* [|│]
    )\s*
    $
    """,
    re.X
)


def dump_table(rows, table_conf=None):
    if not rows:
        return

    table = PrettyTable()
    if table_conf:
        table_conf(table)

    header, rows = rows[0], rows[1:]

    assert not header[0]
    assert not header[-1]
    table.field_names = header[1:-1]
    for row in rows:
        assert not row[0]
        assert not row[-1]
        table.add_row(row[1:-1])
    print(table)


conf = None
if len(sys.argv) > 1 and sys.argv[1] == "--markdown":
    del sys.argv[1]

    def conf(table):
        table.hrules = HEADER
        table.junction_char = "|"


rows = []
for line in input():
    if not table_regex.fullmatch(line):
        dump_table(rows, conf)
        rows = []
        print(line, end='')
        continue

    if box_chars_regex.fullmatch(line):
        continue

    line = line.rstrip()

    row = [el.strip() for el in re.split('[│|]', line)]
    rows.append(row)
dump_table(rows, conf)
