import os
import argparse

parser = argparse.ArgumentParser(description='Inline the auto-complete PEG grammar files')
parser.add_argument(
    '--print', action='store_true', help='Print the grammar instead of writing to a file', default=False
)
parser.add_argument(
    '--grammar-file',
    action='store_true',
    help='Write the grammar to a .gram file instead of a C++ header',
    default=False,
)

args = parser.parse_args()

autocomplete_dir = 'extension/autocomplete'
grammar_dir = os.path.join(autocomplete_dir, 'grammar')
target_file = os.path.join(autocomplete_dir, 'include', 'inlined_grammar.hpp')

contents = ""
for file in os.listdir(grammar_dir):
    if not file.endswith('.gram'):
        raise Exception(f"File {file} does not end with .gram")
    with open(os.path.join(grammar_dir, file), 'r') as f:
        contents += f.read() + "\n"

if args.print:
    print(contents)
    exit(0)


if args.grammar_file:
    grammar_file = target_file.replace('.hpp', '.gram')
    with open(grammar_file, 'w+') as f:
        f.write(contents)
    exit(0)


def get_grammar_bytes(contents, add_null_terminator=True):
    result_text = ""
    for line in contents.split('\n'):
        if len(line) == 0:
            continue
        result_text += "\t\"" + line.replace('\\', '\\\\').replace('"', '\\"') + "\\n\"\n"
    return result_text


with open(target_file, 'w+') as f:
    f.write(
        '''/* THIS FILE WAS AUTOMATICALLY GENERATED BY inline_grammar.py */

namespace duckdb {

const char INLINED_PEG_GRAMMAR[] = {
'''
        + get_grammar_bytes(contents)
        + '''
};

} // namespace duckdb
'''
    )
