#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "game.h"
#include "game_aux.h"
#include "game_struct.h"
#include "game_tools.h"

int main(int argc, char* argv[]) {
  // Check if the inputs are valid
  if (argc != 3 && argc != 4) {
    printf(
        "Usage ./game_solve <option> <input> [<output>]\n"
        "\t-s: solve the game\n"
        "\t-c: get the number of solutions\n");
    return EXIT_FAILURE;
  }
  if (strcmp(argv[1], "-s") != 0 && strcmp(argv[1], "-c") != 0) {
    printf("%s is not a valid option: it should be -s or -c.\n", argv[1]);
    return EXIT_FAILURE;
  }
  // Load game
  game g = game_load(argv[2]);
  if (g == NULL) {
    fprintf(stderr, "The game pointer is null.");
    return EXIT_FAILURE;
  }
  // Main algorithm
  if (strcmp(argv[1], "-s") == 0) {
    if (!game_solve(g)) {
      printf("Sorry, we can't solve this game.\n");
      game_delete(g);
      return EXIT_FAILURE;
    } else {
      game_print(g);
      if (argc == 4) {
        game_save(g, argv[3]);
        printf("Solution saved at %s!\n", argv[3]);
      }
    }
  } else {
    uint nb_sols = game_nb_solutions(g);
    printf("Number of solution(s): %d\n", nb_sols);
    if (argc == 4) {
      FILE* output = fopen(argv[3], "w");
      if (output == NULL) {
        fprintf(stderr, "Can't open/create the output file %s.\n", argv[3]);
        return EXIT_FAILURE;
      }
      fprintf(output, "%d\n", nb_sols);
      printf("Result saved at %s!\n", argv[3]);
      fclose(output);
    }
  }
  game_delete(g);
  return EXIT_SUCCESS;
}