#import "Basic";
#import "File";
#import "Compiler";
#import "Metaprogram_Plugins";

plugins: [..] *Metaprogram_Plugin;

build :: () {
	w := compiler_create_workspace("Ink Build");
	if !w {
		print("Workspace creation failed.\n");
		return;
	}

	EXECUTABLE_NAME :: "ink";
	MAIN_FILE :: "Ink.jai";

	options := get_build_options(w);

	options.write_added_strings = true;

	args := options.compile_time_command_line;

	intercept_flags: Intercept_Flags;
	plugin_start_index := -1;

	for arg : args {
		if arg == {
			case "check"; {
				options.output_type = .NO_OUTPUT;
			}
		}

		it := args[it_index];

		if !it continue;

		if it[0] == #char "+" {
			plugin_start_index = it_index;
		}
	}

	plugins_to_create: [..] Plugin_To_Create;
	tracy : Plugin_To_Create;
	tracy.name = "tracy";
	array_add(*plugins_to_create, tracy);
	// got_error := false;
	// if plugin_start_index >= 0 {
	// 	success:, plugins_to_create = parse_plugin_arguments(args, plugin_start_index);
	// 	if !success got_error = true;
	// }

	// if got_error {
	// 	exit(1);
	// }

	success := init_plugins(plugins_to_create, *plugins, w);
    if !success {
        log_error("A plugin init() failed. Exiting.\n");
        exit(0);
    }

	new_path: [..] string;
	array_add(*new_path, ..options.import_path);
	array_add(*new_path, "modules");
	// array_add(*new_path, "modules/shader_parsing");
	options.import_path = new_path;
	options.output_executable_name = EXECUTABLE_NAME;

	wd := get_working_directory();

	set_build_options(options, w);

	for plugins {
		if it.before_intercept it.before_intercept(it, *intercept_flags);
	}

	compiler_begin_intercept(w, intercept_flags);

	for plugins      if it.add_source it.add_source(it);

	add_build_file(MAIN_FILE, w);

	// Call message_loop(), which is a routine of ours below that will receive the messages.
    message_loop(w);

	compiler_end_intercept(w);

	for plugins if it.finish   it.finish  (it);
    for plugins if it.shutdown it.shutdown(it);

	print("\nDone!\n\n");

	set_build_options_dc(.{do_output=false, write_added_strings=false});
}

message_loop :: (w: Workspace) {
    while true {
        // We ask the compiler for the next message. If one is not available,
        // we will wait until it becomes available.
        message := compiler_wait_for_message();
        // Pass the message to all plugins.
        for plugins if it.message it.message(it, message);

        if message.kind == .COMPLETE break;
    }
}

#run, stallable build();
