use log::Record;
use log4rs::encode::{Encode, Write};
use serde_json::json;

use crate::NEWLINE;

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct SLSEncoder;

impl SLSEncoder {
    /// Returns a new `SLSEncoder` with a default configuration.
    pub fn new() -> Self {
        SLSEncoder
    }
}

impl Default for SLSEncoder {
    fn default() -> Self {
        Self::new()
    }
}

impl Encode for SLSEncoder {
    fn encode(&self, w: &mut dyn Write, record: &Record) -> anyhow::Result<()> {
        let args_str = record.args().to_string();

        // 尝试解析为 JSON
        if let Ok(value) = serde_json::from_str::<serde_json::Value>(&args_str) {
            // 检查是否包含 __logs__ 字段
            if let Some(logs) = value.get("__logs__") {
                if let Some(log_array) = logs.as_array() {
                    // __logs__ 存在且是数组，遍历写入每条记录
                    for log_entry in log_array {
                        // 检查是否是有效的 JSON 对象
                        if log_entry.is_object() {
                            w.write_fmt(format_args!("{}", log_entry))?;
                            w.write_all(NEWLINE.as_bytes())?;
                        } else {
                            return Err(anyhow::anyhow!(
                                "[SLSEncoder] Invalid log entry in __logs__ array: expected object, got {:?}",
                                log_entry
                            ));
                        }
                    }
                    return Ok(());
                }
            }

            // 是 JSON 对象但没有 __logs__ 字段，直接使用该 JSON
            if value.is_object() {
                w.write_fmt(format_args!("{}", value))?;
                w.write_all(NEWLINE.as_bytes())?;
                return Ok(());
            }
        }

        // 普通消息（非 JSON 格式），保持原有逻辑包装到 message 字段
        let log_entry = json!({
            "message": record.args(),
        });

        w.write_fmt(format_args!("{}", log_entry))?;
        w.write_all(NEWLINE.as_bytes())?;
        Ok(())
    }
}
