// AppConfig 实现 — 极简 INI 解析
#include "common/app_config.h"

#include "common/log.h"

#include <algorithm>
#include <cstdlib>
#include <fstream>

namespace {
std::string trim(const std::string& s) {
    size_t b = s.find_first_not_of(" \t\r\n");
    if (b == std::string::npos) return "";
    size_t e = s.find_last_not_of(" \t\r\n");
    return s.substr(b, e - b + 1);
}
}  // namespace

bool AppConfig::Load(const std::string& path) {
    std::ifstream f(path);
    if (!f) {
        HW_ERR("config: 无法打开 %s", path.c_str());
        return false;
    }
    std::string section;
    std::string line;
    int line_no = 0;
    while (std::getline(f, line)) {
        line_no++;
        // 去注释(行内 # 之后)
        size_t hash = line.find('#');
        if (hash != std::string::npos) line = line.substr(0, hash);
        line = trim(line);
        if (line.empty()) continue;

        if (line.front() == '[' && line.back() == ']') {
            section = trim(line.substr(1, line.size() - 2));
            continue;
        }
        size_t eq = line.find('=');
        if (eq == std::string::npos) {
            HW_WARN("config: %s:%d 格式错误(缺 '='), 跳过: %s", path.c_str(), line_no,
                    line.c_str());
            continue;
        }
        if (section.empty()) {
            HW_WARN("config: %s:%d 在段外出现 key, 跳过", path.c_str(), line_no);
            continue;
        }
        data_[section][trim(line.substr(0, eq))] = trim(line.substr(eq + 1));
    }
    HW_LOG("config: 已加载 %s (%zu 段)", path.c_str(), data_.size());
    return true;
}

bool AppConfig::Has(const std::string& section, const std::string& key) const {
    auto s = data_.find(section);
    return s != data_.end() && s->second.count(key) > 0;
}

std::string AppConfig::GetStr(const std::string& section, const std::string& key,
                              const std::string& def) const {
    auto s = data_.find(section);
    if (s == data_.end()) return def;
    auto k = s->second.find(key);
    return k == s->second.end() ? def : k->second;
}

int AppConfig::GetInt(const std::string& section, const std::string& key, int def) const {
    std::string v = GetStr(section, key);
    return v.empty() ? def : atoi(v.c_str());
}

float AppConfig::GetFloat(const std::string& section, const std::string& key, float def) const {
    std::string v = GetStr(section, key);
    return v.empty() ? def : (float)atof(v.c_str());
}

bool AppConfig::GetBool(const std::string& section, const std::string& key, bool def) const {
    std::string v = GetStr(section, key);
    if (v.empty()) return def;
    return v == "1" || v == "true" || v == "yes" || v == "on";
}

std::vector<std::string> AppConfig::Sections(const std::string& prefix) const {
    std::vector<std::string> out;
    for (const auto& kv : data_) {
        if (kv.first.compare(0, prefix.size(), prefix) == 0) out.push_back(kv.first);
    }
    std::sort(out.begin(), out.end());
    return out;
}
