#include <gtest/gtest.h>
#include "probe.h"
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <sstream>
#include <regex>
#include <source_location>
#include <chrono>
#include "quill/LogMacros.h"

std::string getLastLine(const std::string& filename) {
    std::ifstream file(filename);
    std::string line, lastLine;

    if (!file.is_open()) {
        throw std::runtime_error("Could not open file");
    }

    while (std::getline(file, line)) {
        lastLine = line;
    }

    return lastLine;  // Returns the last non-empty line
}

std::string stripTimestamps(const std::string& logLine) {
    std::regex logPattern(R"(\d+:\d+:\d+\.\d+\s+\[\d+\]\s+probeTest\.cpp:\d+\s+LOG_INFO\s+[A-Za-z]*\s+(.*))");
    std::smatch match;
    if (std::regex_match(logLine, match, logPattern) && match.size() > 1) {
        return match[1].str();  // Extract log message after timestamp
    }
    return logLine;  // Return as-is if pattern doesn't match
}


class probeTest : public ::testing::Test {};

TEST_F(probeTest, DefaultConstructorTest) {
    EXPECT_NO_THROW(Probe::LogManager::getInstance());
}

TEST_F(probeTest, waitTest) {
    auto start = std::chrono::high_resolution_clock::now();
    Probe::wait(1);
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed = end - start;
    EXPECT_LE(elapsed.count(), 1.1);
}

TEST_F(probeTest, getLoggerTest) {
    Probe::LogManager& logManager = Probe::LogManager::getInstance();
    std::string loggerName = "log";
    quill::Logger* logger = logManager.getLogger(loggerName);
    EXPECT_NE(logger, nullptr);
    LOG_INFO(logger, "This is a test message");
    // Wait for the log to be written by calling getLastLine until it is non empty
    std::string lastLine;
    while (lastLine.empty()) {
        lastLine = getLastLine("4DSSE.log");
    }
    EXPECT_EQ(stripTimestamps(lastLine), "This is a test message");
}

TEST_F(probeTest, newFileLoggerTest) {
    Probe::LogManager& logManager = Probe::LogManager::getInstance();
    const std::string loggerName = "newLog";
    const std::string filename = "newLog.log";
    quill::Logger* logger = logManager.newFileLogger(filename, loggerName);
    EXPECT_NE(logger, nullptr);
    LOG_INFO(logger, "This is a new test message");
    // Wait for the log to be written by calling getLastLine until it is non empty
    std::string lastLine;
    while (lastLine.empty()) {
        lastLine = getLastLine(filename);
    }
    EXPECT_EQ(stripTimestamps(lastLine), "This is a new test message");
}

TEST_F(probeTest, getLoggerNames) {
    Probe::LogManager& logManager = Probe::LogManager::getInstance();
    std::vector<std::string> loggerNames = logManager.getLoggerNames();
    EXPECT_EQ(loggerNames.size(), 3);
    EXPECT_EQ(loggerNames.at(0), "log");
    EXPECT_EQ(loggerNames.at(1), "newLog");
    EXPECT_EQ(loggerNames.at(2), "stdout");
}
