#include <cassert>
#include <filesystem>
#include <fstream>
#include <iostream>

#include "solver/solver.h"

using std::filesystem::path;

int main(int argc, char** argv) {
  if (argc != 4) {
    std::cout << "Usage: ./test_case_partition TEST_CASE "
                 "UNSOLVED_PATH ERROR_PATH"
              << std::endl;
    return 1;
  }

  std::string filename = path(argv[1]).filename();
  std::ifstream input{argv[1]};
  if (!input) {
    std::cout << "Couldn't open " << argv[1] << std::endl;
    return 1;
  }
  std::string unsolvedpath = path(argv[2]) / filename;
  std::ofstream unsolved{unsolvedpath};
  if (!unsolved) {
    std::cout << "Couldn't open " << argv[2] << std::endl;
    return 1;
  }
  std::string errorpath = path(argv[3]) / filename;
  std::ofstream error{errorpath};
  if (!error) {
    std::cout << "Couldn't open " << argv[3] << std::endl;
    return 1;
  }

  uint32_t solvedcnt = 0;
  uint32_t unsolvedcnt = 0;
  uint32_t errorcnt = 0;

  while (input) {
    std::string input_line;
    input >> input_line;
    if (input_line.starts_with("quizzes") || input_line.length() == 0) {
      continue;
    }
    size_t comma_pos = input_line.find(",");
    std::string test_case = input_line.substr(0, comma_pos);
    std::string solution = input_line.substr(comma_pos + 1);
    Solver solver(test_case);
    if (!solver.Solve()) {
      unsolved << input_line << std::endl;
      unsolvedcnt++;
    } else if (solver.State() != solution) {
      error << input_line << std::endl;
      errorcnt++;
    } else {
      solvedcnt++;
    }
  }
  unsolved.close();
  error.close();

  std::cout << "Solved: " << solvedcnt << "\nUnsolved: " << unsolvedcnt
            << "\nError: " << errorcnt << std::endl;

  if (unsolvedcnt == 0) {
    std::filesystem::remove(unsolvedpath);
  }
  if (errorcnt == 0) {
    std::filesystem::remove(errorpath);
  }
}
