#pragma once

#include <cstdint>
#include <string>
#include <vector>
#include <unordered_map>
#include <chrono>
#include <sstream>
#include <iomanip>
#include "chat/MultilingualProfanityFilter.hpp"

namespace FreeExile {

enum class ChatChannelType : uint8_t {
    WORLD = 1,
    ZONE = 2,
    GUILD = 3,
    PARTY = 4,
    WHISPER = 5,
    SYSTEM = 6,
    RECRUIT = 7,
    FEEDBACK = 8
};

struct ItemSnapshotData {
    std::string item_uuid;
    std::string item_name;
    int32_t rarity;      // 1: Phàm, 2: Linh, 3: Cực, 4: Thần, 5: Thái Cổ
    int32_t element;     // 1: Kim, 2: Mộc, 3: Thủy, 4: Hỏa, 5: Thổ
    int32_t quality;     // 0-20%
    std::string crafter_name;
    std::string hmac_signature;
};

struct BroadcastChatMessage {
    std::string message_id;
    int64_t sender_id;
    std::string sender_name;
    ChatChannelType channel;
    int64_t target_id;
    std::string content;
    std::vector<ItemSnapshotData> linked_items;
    int64_t timestamp_ms;
    bool is_censored;
    int32_t risk_score;
};

class ChatManager {
private:
    MultilingualProfanityFilter filter;
    std::unordered_map<int64_t, int64_t> last_world_chat_ms; // Rate limit tracker
    std::unordered_map<std::string, ItemSnapshotData> item_snapshots; // Redis snapshot cache simulation
    std::string server_hmac_secret = "FREEEXILE_SECRET_SIGNING_KEY_2026";

    // Fast deterministic HMAC simulation for testing / standalone
    std::string generate_signature(const std::string& item_uuid, const std::string& name, int32_t rarity) const {
        uint64_t hash = 14695981039346656037ULL;
        std::string raw = item_uuid + ":" + name + ":" + std::to_string(rarity) + ":" + server_hmac_secret;
        for (char c : raw) {
            hash ^= static_cast<uint64_t>(c);
            hash *= 1099511628211ULL;
        }
        std::stringstream ss;
        ss << std::hex << hash;
        return "sig_" + ss.str();
    }

public:
    ChatManager() = default;

    /**
     * Creates a cryptographically signed Item Link Snapshot for chat flexing.
     * Prevents clients from spoofing fake items in chat!
     */
    ItemSnapshotData create_item_link_snapshot(
        const std::string& item_uuid,
        const std::string& name,
        int32_t rarity,
        int32_t element,
        int32_t quality,
        const std::string& crafter
    ) {
        std::string signature = generate_signature(item_uuid, name, rarity);
        ItemSnapshotData snap = {
            item_uuid,
            name,
            rarity,
            element,
            quality,
            crafter,
            signature
        };
        item_snapshots[item_uuid] = snap;
        return snap;
    }

    bool verify_item_snapshot(const std::string& item_uuid, const std::string& claimed_signature) const {
        auto it = item_snapshots.find(item_uuid);
        if (it != item_snapshots.end()) {
            return it->second.hmac_signature == claimed_signature;
        }
        return false;
    }

    struct SendResult {
        bool success;
        std::string error_message;
        BroadcastChatMessage message;
    };

    /**
     * Processes, filters, and routes an incoming chat message.
     */
    SendResult process_message(
        int64_t sender_id,
        const std::string& sender_name,
        ChatChannelType channel,
        int64_t target_id,
        const std::string& raw_content,
        const std::vector<std::string>& item_uuids_to_link,
        int64_t current_time_ms
    ) {
        // 1. Rate Limiting for World Channel (15s Cooldown)
        if (channel == ChatChannelType::WORLD) {
            auto it = last_world_chat_ms.find(sender_id);
            if (it != last_world_chat_ms.end()) {
                int64_t elapsed = current_time_ms - it->second;
                if (elapsed < 15000) {
                    return { false, "Kênh Thế Giới yêu cầu giãn cách 15 giây chống spam!", {} };
                }
            }
            last_world_chat_ms[sender_id] = current_time_ms;
        }

        // 2. Multilingual Profanity & RMT Filtering (0ms)
        auto filter_res = filter.filter_message(raw_content);

        // Auto-mute high-risk RMT bots (Score >= 60)
        if (filter_res.risk_score >= 60) {
            return { false, "Tin nhắn chứa nội dung quảng bá giao dịch tiền thật hoặc thông tin liên lạc bị cấm!", {} };
        }

        // 3. Resolve and attach cryptographic Item Snapshots
        std::vector<ItemSnapshotData> attached_items;
        for (const auto& uuid : item_uuids_to_link) {
            auto it = item_snapshots.find(uuid);
            if (it != item_snapshots.end()) {
                attached_items.push_back(it->second);
            }
        }

        // 4. Construct broadcast message
        std::string msg_id = "msg_" + std::to_string(current_time_ms) + "_" + std::to_string(sender_id);
        BroadcastChatMessage broadcast_msg = {
            msg_id,
            sender_id,
            sender_name,
            channel,
            target_id,
            filter_res.filtered_content,
            attached_items,
            current_time_ms,
            filter_res.contains_profanity,
            filter_res.risk_score
        };

        return { true, "", broadcast_msg };
    }
};

} // namespace FreeExile
