#pragma once

#include <string>
#include <vector>
#include <unordered_map>
#include <mutex>
#include <chrono>
#include <atomic>

namespace node669427 {

struct Session {
    std::string ip;
    double trust_score = 50.0;
    int strikes = 0;
    uint64_t request_count = 0;
    std::chrono::system_clock::time_point first_seen;
    std::chrono::system_clock::time_point last_seen;
    std::vector<std::string> path_history;
    bool blocked = false;
};

struct SecurityEvent {
    std::string type;
    std::string source_ip;
    std::string severity;
    std::string timestamp;
    std::string details;
};

struct SecurityMetrics {
    uint64_t total_requests = 0;
    uint64_t blocked_requests = 0;
    uint64_t active_sessions = 0;
    double avg_trust_score = 50.0;
};

class SecurityEngine {
public:
    SecurityEngine();

    void recordRequest(const std::string& ip, const std::string& path);
    void logEvent(const std::string& type, const std::string& source_ip,
                  const std::string& severity, const std::string& details = "");
    bool isBlocked(const std::string& ip) const;
    double getTrustScore(const std::string& ip) const;

    std::string getEvents() const;
    std::string getSessionStatus(const std::string& ip) const;
    SecurityMetrics getMetrics() const;

    void decayScores();
    void run();
    void stop();

private:
    std::unordered_map<std::string, Session> sessions_;
    mutable std::mutex sessions_mutex_;

    std::vector<SecurityEvent> events_;
    mutable std::mutex events_mutex_;
    static constexpr size_t MAX_EVENTS = 10000;

    std::atomic<uint64_t> total_requests_{0};
    std::atomic<uint64_t> blocked_requests_{0};
    std::atomic<bool> running_{true};

    void detectAnomaly(Session& session, const std::string& path);
    void addStrike(const std::string& ip);
};

} // namespace node669427
