use crate::core::config::AppConfig;
use crate::core::message::{Envelope, Message};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::sync::{mpsc, Arc};

/// 单项能力测试结果
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapabilityTestResult {
    pub capability: String,
    pub passed: bool,
    pub message: String,
}

/// 所有功能都通过实现此 trait 接入系统
pub trait Plugin: Send {
    /// 唯一标识 (如 "video", "http", "ble")
    fn id(&self) -> &str;

    /// 插件信息
    fn info(&self) -> PluginInfo;

    /// 声明启动所需的插件依赖
    fn dependencies(&self) -> Vec<String> {
        vec![]
    }

    /// 声明插件支持的功能列表（默认空）
    fn capabilities(&self) -> Vec<String> {
        vec![]
    }

    /// 运行自测，返回每项功能的测试结果
    /// 默认实现：所有声明的 capability 均标记为通过
    fn self_test(&mut self) -> Vec<CapabilityTestResult> {
        self.capabilities()
            .into_iter()
            .map(|c| CapabilityTestResult {
                capability: c,
                passed: true,
                message: "no test defined".into(),
            })
            .collect()
    }

    /// 初始化：获取发送通道，声明订阅的消息类型
    fn init(&mut self, ctx: PluginContext) -> Result<()>;

    /// 启动（可在此 spawn 线程/任务）
    fn start(&mut self) -> Result<()>;

    /// 接收来自其他插件或管理层的消息
    fn handle_message(&mut self, msg: Message) -> Result<()>;

    /// 优雅停止
    fn stop(&mut self) -> Result<()>;
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginInfo {
    pub name: String,
    pub version: String,
    pub description: String,
    pub platform: Platform,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Platform {
    Any,
    Linux,
    LinuxArm64,
}

/// 传给插件的上下文
pub struct PluginContext {
    /// 向管理层发消息
    pub tx: mpsc::Sender<Envelope>,
    /// 共享配置（只读）
    pub config: Arc<AppConfig>,
}
