#pragma once

#include <cstdlib>
#include <fstream>
#include <string>
#include <unordered_map>

namespace config {

// Loads a .env file into the process environment (and returns the map).
// Lines starting with '#' and blank lines are skipped.
// No shell expansion, no quoting -- matches Node's dotenv behavior.
inline std::unordered_map<std::string, std::string> load(const std::string& path = ".env") {
    std::unordered_map<std::string, std::string> vars;
    std::ifstream file(path);
    if (!file.is_open()) return vars;

    std::string line;
    while (std::getline(file, line)) {
        // Trim leading whitespace
        size_t start = line.find_first_not_of(" \t\r\n");
        if (start == std::string::npos) continue;
        line = line.substr(start);

        if (line.empty() || line[0] == '#') continue;

        size_t eq = line.find('=');
        if (eq == std::string::npos) continue;

        std::string key = line.substr(0, eq);
        std::string val = line.substr(eq + 1);

        // Trim trailing whitespace from value
        size_t end = val.find_last_not_of(" \t\r\n");
        if (end != std::string::npos) val = val.substr(0, end + 1);

        // Strip surrounding quotes
        if (val.size() >= 2 &&
            ((val.front() == '"' && val.back() == '"') ||
             (val.front() == '\'' && val.back() == '\''))) {
            val = val.substr(1, val.size() - 2);
        }

        setenv(key.c_str(), val.c_str(), 0);  // don't overwrite existing
        vars[key] = val;
    }
    return vars;
}

// Read a string env var with a fallback default.
inline std::string get(const char* key, const char* def = "") {
    const char* val = std::getenv(key);
    return val ? val : def;
}

// Read an integer env var with a fallback default.
inline int get_int(const char* key, int def = 0) {
    const char* val = std::getenv(key);
    if (!val) return def;
    try { return std::stoi(val); }
    catch (...) { return def; }
}

} // namespace config
