#include <exception>
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>

#include "time.h"
#include "api.h"

std::string readFile(const std::string& filePath) {
    std::ifstream file(filePath);
    if (!file.is_open()) {
        throw std::runtime_error("Cannot open file: " + filePath);
    }

    std::string content;
    std::string line;
    while (std::getline(file, line)) {
        content += line + '\n';
    }

    file.close();
    return content;
}


int main(int argc, char* argv[]) {
	std::string filePath;

	bool debug = false;
    if (argc == 3) {
		auto option = std::string(argv[1]);
		if (option == "--debug") {
			debug = true;	
		} else {
			std::cout << std::format("Unrecognized option: {}", option) << std::endl;
			return 1;
		}
		filePath = argv[2];
	} else if (argc == 2) {
		filePath = argv[1];
	} else {
        std::cerr << "Usage: " << argv[0] << " <file-path>\n";
        return 1;
    } 

    try {
		std::string fileContent = readFile(filePath);
		end = std::chrono::high_resolution_clock::now();
		showTime("I/O time");

		auto res = transpile(fileContent, debug);
		auto questions = res.value.questions;
		if (res.error.length() > 0) {
			std::cout << std::format(
				"{} ({}:{})\n",
				res.error,
				res.row,
				res.column
			);
			return 1;
		}

        for (Question* question: questions) {
            delete question;
        }

    } catch (std::exception &e) {
        std::cout << e.what() << std::endl;
        return 1;
    }

    return 0;
}
