#include <compiler/lexer/lexer.h>
#include <stdio.h>
#include <stdlib.h>
#include <utils/file.h>

#include "compiler/code_generator/code_generator.h"
#include "compiler/parser/parser.h"
#include "utils/time.h"
#include "utils/types.h"
#include "vm/runner/runner.h"

static const char *codes[] = {
    "print(\"\");",
};

bool run(char const *restrict code) {
  bool ranSuccess = false;
  const Nodes nodes = lexer(code);
  ParsedNode *parsedNode = parser(nodes);
  if (parsedNode != NULL) {
    Instructions instructions = codeGenerator(parsedNode);
    if (instructions.size != ERROR_SIZE) {
      ranSuccess = runner(instructions);
      deleteInstructions(instructions);
    }
    deleteParsedNode(parsedNode);
  }
  deleteNodes(nodes);
  return ranSuccess;
}

Clock runWithPrint(char const *restrict code) {
  Clock sum = 0;
  Clock diff = 0;
  printf("----code:\n%s\n----\n", code);
  Clock start = getTimeInNano();
  const Nodes nodes = lexer(code);
  diff += getTimeInNano() - start;
  sum += diff;
  printNodes(nodes);
  printf("----lexing in %ldns\n", diff);
  start = getTimeInNano();
  ParsedNode *parsedNode = parser(nodes);
  diff = getTimeInNano() - start;
  sum += diff;
  printf("----parsing in %ldns\n", diff);
  if (parsedNode != NULL) {
    printParsedNode(parsedNode);
    start = getTimeInNano();
    Instructions instructions = codeGenerator(parsedNode);
    if (instructions.size != ERROR_SIZE) {
      diff = getTimeInNano() - start;
      sum += diff;
      printf("----code_generator in %ldns\n", diff);
      printInstructions(instructions);
      start = getTimeInNano();
      bool ranSuccess = runner(instructions);
      diff = getTimeInNano() - start;
      sum += diff;
      printf("----runner in %ldns\n", diff);
      printf("ran sucessfully = %s\n", ranSuccess ? "true" : "false");
      printf("----sum %ldns\n", sum);
      deleteInstructions(instructions);
    }
    deleteParsedNode(parsedNode);
  }
  deleteNodes(nodes);
  return sum;
}

Clock process() {
  Clock sumAll = 0;
  for (size_t i = 0; i < sizeof(codes) / sizeof(char *); ++i) {
    Clock start = getTimeInNano();
    run(codes[i]);
    sumAll += getTimeInNano() - start;
  }
  return sumAll;
}

void runBenchmark() {
  Clock sum = 0;
  const int times = 10000;
  for (int i = 0; i < times; ++i) {
    sum += process();
  }
  printf("\n\navg = %fns", ((float)sum) / times);
}

int main(int argc, char *argv[]) {
  /*runBenchmark();*/
  if (argc < 2) {
    fprintf(stderr, "no file");
    return 1;
  }
  char *code = read_whole_file(argv[1]);
  const bool ret = run(code);
  free(code);
  if (ret) {
    return 0;
  } else {
    return 1;
  }
}