#include <gtest/gtest.h>
#include <cstdlib>
#include <string>
#include <array>
#include <memory>

const std::string SCRIPT_PATH = "/Users/einand/Code/test/cpp/print_hej";

std::string run_script(const std::string& args = "") {
    std::string cmd = SCRIPT_PATH;
    if (!args.empty()) {
        cmd += " " + args;
    }
    
    std::array<char, 128> buffer;
    std::string result;
    std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose);
    
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }
    
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        result += buffer.data();
    }
    
    // Trim newline
    if (!result.empty() && result.back() == '\n') {
        result.pop_back();
    }
    
    return result;
}

TEST(PiTest, Test10Decimals) {
    std::string result = run_script("10");
    std::string expected = "3.1415926535";
    EXPECT_EQ(result, expected);
}

TEST(PiTest, Test5Decimals) {
    std::string result = run_script("5");
    std::string expected = "3.14159";
    EXPECT_EQ(result, expected);
}

TEST(PiTest, Test1Decimal) {
    std::string result = run_script("1");
    std::string expected = "3.1";
    EXPECT_EQ(result, expected);
}

TEST(PiTest, Test100Decimals) {
    std::string result = run_script("100");
    std::string expected = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679";
    EXPECT_EQ(result, expected);
}

TEST(PiTest, TestDefault100Decimals) {
    std::string result = run_script();
    std::string expected = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679";
    EXPECT_EQ(result, expected);
}

TEST(PiTest, Test10000Decimals) {
    std::string result = run_script("10000");
    // Check length: "3." + 10000 digits = 10002 characters
    EXPECT_EQ(result.length(), 10002);
    EXPECT_TRUE(result.substr(0, 7) == "3.14159");
}

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}