#!/usr/bin/env python3
# coding:utf-8

from sexp import SParser
from idmap import IdMap
import argparse
import sys

parser = argparse.ArgumentParser()

# 位置引数
parser.add_argument('--grammar', action='store')
parser.add_argument('--katuyou', action='store')
parser.add_argument('--output', action='store', default='-')

args = parser.parse_args()


def process(out):
    idmap = IdMap()

    out.write("// clang-format off\n")
    out.write("// This file is generated by /scripts/grammar_id_mapping.py\n")
    out.write("// Do not edit it manually!\n\n\n")

    out.write("#include \"jumandic_ids.h\"\n\n")

    out.write("namespace jumanpp {\n")
    out.write("namespace jumandic {\n")

    if args.grammar:
        with open(args.grammar, "r", encoding='utf-8') as grammarf:
            idmap.parse_grammar(grammarf.read())
        out.write("const JumandicTuple posInfo[] = {\n")
        for (key1, key2), val in sorted(idmap.pos_spos2id.items(), key=lambda x: idmap.pos2id[x[0][0]] * 1000 + x[1]):
            out.write("  {StringPiece{\"%s\"}, StringPiece{\"%s\"}, %d, %d},\n" % (key1, key2, idmap.pos2id[key1], val))
        out.write("};\n\n")
        out.write("const u32 posInfoCount = %dU;\n\n" % len(idmap.pos_spos2id.items()))

    if args.katuyou:
        with open(args.katuyou, "r", encoding='utf-8') as katuyouf:
            idmap.parse_katuyou(katuyouf.read())
        out.write("const JumandicTuple conjInfo[] = {\n")
        for (key1, key2), val in sorted(idmap.type_form2id.items(), key=lambda x: idmap.type2id[x[0][0]] * 1000 + x[1]):
            out.write("  {StringPiece{\"%s\"}, StringPiece{\"%s\"}, %d, %d},\n" % (key1, key2, idmap.type2id[key1], val))
        out.write("};\n\n")
        out.write("const u32 conjInfoCount = %dU;\n\n" % len(idmap.type_form2id.items()))

    out.write("} // namespace jumandic\n")
    out.write("} // namespace jumanpp\n")

if __name__ == "__main__":
    if args.output != '-':
        with open(args.output, 'w', encoding='utf-8') as ofile:
            process(ofile)
    else:
        process(sys.stdout)
