#!/usr/bin/env python3
#
# SPDX-License-Identifier: MIT
#
# Copyright (C) 2023 Ying-Chun Liu (PaulLiu) <paulliu@debian.org>
#

import re
import sys
import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("dictfile",
                        help="Dictionary file.")

    args = parser.parse_args()
    
    dictfile = args.dictfile
    
    main_re = re.compile(r"([^ ]+)[ ]([^ ]+)[ ]([\[].*[\]])[ ][/](.*)[/]")
    fi = open(dictfile, "r")

    dictData = {}

    while (True):
        line = fi.readline()
        if not line:
            break
        line = line.strip()
        if (len(line) > 0 and line[0] == '#'):
                continue
        match = main_re.search(line)
        if (match is None):
            print("Error", file=sys.stderr)
            sys.exit(1)

        explain = match.group(4)
        explains = explain.split("/")

        if (match.group(1) in dictData):
            dictData[match.group(1)].append(match.group(3))
            dictData[match.group(1)].extend(explains)
        else:
            dictData[match.group(1)] = [ match.group(3) ]
            dictData[match.group(1)].extend(explains)
        if (match.group(1) != match.group(2)):
            if (match.group(2) in dictData):
                dictData[match.group(2)].append(match.group(3))
                dictData[match.group(2)].extend(explains)
            else:
                dictData[match.group(2)] = [ match.group(3) ]
                dictData[match.group(2)].extend(explains)

    print("")
    print("")

    for key in dictData.keys():
        print(key)
        for i in range(len(dictData[key])):
            s = dictData[key][i]
            print(" ", end="")
            print(s)
