use async_trait::async_trait;

use crate::command::context::CommandContext;
use crate::command::handler::{CommandHandler, CommandMetadata};
use crate::command::response::{CommandError, CommandResponse, MessageKind};
use crate::command::Command;
use crate::gateway::cancel_manager::CancelManager;

/// 处理 StopExecution 命令：按话题取消当前正在执行的 Agent。
pub struct StopExecutionCommandHandler {
    cancel_manager: CancelManager,
}

impl StopExecutionCommandHandler {
    pub fn new(cancel_manager: CancelManager) -> Self {
        Self { cancel_manager }
    }
}

#[async_trait]
impl CommandHandler for StopExecutionCommandHandler {
    fn can_handle(&self, cmd: &Command) -> bool {
        matches!(cmd, Command::StopExecution)
    }

    fn metadata(&self) -> Option<CommandMetadata> {
        Some(CommandMetadata {
            name: "stop",
            description: "停止当前话题正在执行的 Agent",
            usage: "/stop",
        })
    }

    async fn handle(
        &self,
        _cmd: Command,
        ctx: CommandContext,
    ) -> Result<CommandResponse, CommandError> {
        let topic_id = match ctx.topic_id.as_deref() {
            Some(id) => id,
            None => {
                return Ok(CommandResponse::success(ctx.request_id)
                    .with_message(MessageKind::Notification, "当前没有活跃的话题，无法停止"));
            }
        };

        let cancelled = self.cancel_manager.cancel_by_topic(topic_id).await;

        if cancelled {
            Ok(CommandResponse::success(ctx.request_id)
                .with_message(MessageKind::Notification, "正在停止当前任务..."))
        } else {
            Ok(CommandResponse::success(ctx.request_id)
                .with_message(MessageKind::Notification, "当前没有正在执行的任务"))
        }
    }
}
