// Patched from https://raw.githubusercontent.com/etkecc/baibot/v1.13.0/src/conversation/matrix/entity.rs
// FlowKraft Patch: Added max_messages field and with_max_messages method for SEND_N_NEWEST_MESSAGES feature

use chrono::{DateTime, Utc};
use regex::Regex;

use mxlink::matrix_sdk::ruma::OwnedUserId;
use mxlink::matrix_sdk::ruma::events::room::message::ImageMessageEventContent;
use mxlink::mime::Mime;

#[derive(Clone)]
pub struct MatrixMessage {
    pub sender_id: OwnedUserId,
    pub content: MatrixMessageContent,
    pub mentioned_users: Vec<OwnedUserId>,
    pub timestamp: DateTime<Utc>,
}

#[derive(Clone)]
pub enum MatrixMessageContent {
    Text(String),
    Notice(String),
    Image(ImageMessageEventContent, Mime, Vec<u8>),
}

#[derive(Clone)]
pub struct MatrixMessageProcessingParams {
    pub(crate) bot_user_id: OwnedUserId,

    /// The prefixes that will be stripped when processing the messages in the context (thread or reply chain),
    /// which are found to be mentioning the bot user (`bot_user_id`).
    pub(crate) bot_user_prefixes_to_strip: Vec<String>,

    /// The prefixes that will be stripped when processing the 1st message in the context (thread or reply chain).
    pub(crate) first_message_prefixes_to_strip: Vec<String>,

    /// A list of users whose messages are allowed.
    /// If None, all messages are allowed.
    /// If Some, only messages from the allowed users (and the bot itself, `bot_user_id`) are allowed.
    pub(crate) allowed_users: Option<Vec<Regex>>,

    /// FlowKraft Patch: Maximum number of messages to include in context.
    /// If None, all messages are included.
    /// If Some(n), only the n newest messages are included.
    /// This is useful for Letta integration where Letta manages its own conversation memory.
    pub(crate) max_messages: Option<usize>,
}

impl MatrixMessageProcessingParams {
    pub fn new(bot_user_id: OwnedUserId, allowed_users: Option<Vec<Regex>>) -> Self {
        Self {
            bot_user_id,
            bot_user_prefixes_to_strip: vec![],
            first_message_prefixes_to_strip: vec![],
            allowed_users,
            max_messages: None,
        }
    }

    pub fn with_bot_user_prefixes_to_strip(mut self, value: Vec<String>) -> Self {
        self.bot_user_prefixes_to_strip = value;
        self
    }

    pub fn with_first_message_prefixes_to_strip(mut self, value: Vec<String>) -> Self {
        self.first_message_prefixes_to_strip = value;
        self
    }

    /// FlowKraft Patch: Set the maximum number of messages to include in context.
    /// When set, only the n newest messages will be sent to the LLM.
    pub fn with_max_messages(mut self, value: Option<usize>) -> Self {
        self.max_messages = value;
        self
    }
}
