#!/usr/bin/env python

import sys
import os
import types
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import bach
import bach.parser, bach.macro_expander, bach.builtin_macros, bach.compiler
import bach.bach_stl.functions
import bach.bach_stl
from bach.bach_stl import load_stl, include

BACH_STL_BASE = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "bach", "bach_stl")
BACH_FILES = ['macros', 'collections']

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print('bach <filename>.bach')
    else:
        filename = sys.argv[1]
        with open(filename, 'r') as f:
            source = f.read()
        bach.bach_stl.CURRENT_FILE_DIR = os.path.dirname(filename)

        bach_source = include(*[os.path.join(BACH_STL_BASE, b) for b in BACH_FILES])
        source = bach_source + '\n' + source

        sexp = bach.parser.Parser(source).parse()
        # print(sexp.code[1][1][0])
        expanded = bach.macro_expander.MacroExpander(bach.builtin_macros.BUILTIN_MACROS, bach.builtin_macros.USER_DEFINED_MACROS).macro_expand(sexp)
                
        stl = load_stl() # a code obj with the stl functions
        bach.compiler.Compiler().compile_and_save(expanded, '%spyc' % filename[:-4], stl=stl)
        
        print(expanded.__dict__)
        print('end')

