#pragma once

#include <fstream>
#include <mutex>
#include <string>
#include <chrono>
#include <iomanip>
#include <sstream>

class Logger {
public:
    static Logger& instance() {
        static Logger inst;
        return inst;
    }

    void set_file(const std::string& path) {
        std::lock_guard<std::mutex> lock(mutex_);
        if (ofs_.is_open())
            ofs_.close();
        ofs_.open(path, std::ios::out | std::ios::app);
    }

    void log(const char* level, const std::string& msg) {
        std::lock_guard<std::mutex> lock(mutex_);
        if (!ofs_.is_open())
            return;

        ofs_ << timestamp()
             << " [" << level << "] "
             << msg << "\n";
        ofs_.flush();
    }

private:
    Logger() = default;

    std::string timestamp() {
        using namespace std::chrono;
        auto now = system_clock::now();
        auto t = system_clock::to_time_t(now);

        std::tm tm{};
        localtime_r(&t, &tm);

        std::ostringstream oss;
        oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
        return oss.str();
    }

    std::ofstream ofs_;
    std::mutex mutex_;
};
