#include "client_config.h"
#include <filesystem>
#include <cstdlib>

namespace scar {

ClientConfig::ClientConfig()
    : last_server_(DEFAULT_SERVER), last_port_(DEFAULT_PORT) {
    config_ = std::make_unique<JsonConfig>(getConfigPath());
}

std::string ClientConfig::getConfigPath() {
    std::string config_dir;
    
#ifdef _WIN32
    const char* appdata = std::getenv("APPDATA");
    if (appdata) {
        config_dir = std::string(appdata) + "/scarchat";
    } else {
        config_dir = "scarchat";
    }
#else
    const char* xdg_config = std::getenv("XDG_CONFIG_HOME");
    if (xdg_config) {
        config_dir = std::string(xdg_config) + "/scarchat";
    } else {
        const char* home = std::getenv("HOME");
        if (home) {
            config_dir = std::string(home) + "/.config/scarchat";
        } else {
            config_dir = ".config/scarchat";
        }
    }
#endif
    
    // Ensure directory exists
    std::filesystem::create_directories(config_dir);
    
    return config_dir + "/client.json";
}

void ClientConfig::load() {
    if (config_->load()) {
        last_username_ = config_->get<std::string>("last_username", "");
        last_server_ = config_->get<std::string>("last_server", DEFAULT_SERVER);
        last_port_ = config_->get<uint16_t>("last_port", DEFAULT_PORT);
        jwt_token_ = config_->get<std::string>("jwt_token", "");
    }
}

void ClientConfig::save() {
    config_->set("last_username", last_username_);
    config_->set("last_server", last_server_);
    config_->set("last_port", last_port_);
    config_->set("jwt_token", jwt_token_);
    config_->save();
}

void ClientConfig::setLastUsername(const std::string& username) {
    last_username_ = username;
}

void ClientConfig::setLastServer(const std::string& server) {
    last_server_ = server;
}

void ClientConfig::setLastPort(uint16_t port) {
    last_port_ = port;
}

void ClientConfig::setJwtToken(const std::string& token) {
    jwt_token_ = token;
}

} // namespace scar
