#include "Config.hpp"
#include "../platform/PathUtils.hpp"

#include <fstream>
#include <iostream>

namespace GModTeach {
namespace Core {

bool AppConfig::IsValid() const {
    std::error_code ec;
    return !gmadLsDir.empty() && 
           !gmodDir.empty() && 
           std::filesystem::exists(gmadLsDir, ec) && 
           std::filesystem::is_directory(gmadLsDir, ec) &&
           std::filesystem::exists(gmodDir, ec) && 
           std::filesystem::is_directory(gmodDir, ec);
}

std::filesystem::path ConfigManager::GetDefaultConfigPath() {
    return Platform::PathUtils::GetExecutableDirectory() / "config.ini";
}

bool ConfigManager::Load(const std::filesystem::path& iniPath, AppConfig& outConfig) {
    std::ifstream stream(iniPath);
    if (!stream.is_open()) {
        return false;
    }

    std::string line;
    while (std::getline(stream, line)) {
        line = Platform::PathUtils::Trim(line);
        if (line.empty() || line[0] == '#' || line[0] == ';') {
            continue;
        }

        const auto eqPos = line.find('=');
        if (eqPos == std::string::npos) {
            continue;
        }

        std::string key = Platform::PathUtils::Trim(line.substr(0, eqPos));
        std::string value = Platform::PathUtils::Trim(line.substr(eqPos + 1));

        if (value.size() >= 2 && ((value.front() == '"' && value.back() == '"') || 
                                  (value.front() == '\'' && value.back() == '\''))) {
            value = value.substr(1, value.size() - 2);
        }

        if (key == "GMAD-LS") {
            outConfig.gmadLsDir = std::filesystem::path(value);
        } else if (key == "GMOD-DIR") {
            outConfig.gmodDir = std::filesystem::path(value);
        }
    }

    return outConfig.IsValid();
}

bool ConfigManager::Save(const std::filesystem::path& iniPath, const AppConfig& config) {
    std::ofstream stream(iniPath, std::ios::trunc);
    if (!stream.is_open()) {
        std::cerr << "[ERROR] Could not open config file for writing: " << iniPath << "\n";
        return false;
    }

    stream << "# GMoD-TeachGMAD Configuration File\n";
    stream << "GMAD-LS=" << config.gmadLsDir.string() << "\n";
    stream << "GMOD-DIR=" << config.gmodDir.string() << "\n";
    return true;
}

bool ConfigManager::Reset(const std::filesystem::path& iniPath) {
    std::error_code ec;
    return std::filesystem::remove(iniPath, ec);
}

} 
} 
