use crate::agent::AgentError;
use crate::bus::OutboundMessage;
use crate::scheduler::ScheduledAgentTaskOptions;

use super::execution::{AgentExecutionService, ScheduledExecutionRequest};
use super::provider_config_service::ProviderConfigService;
use super::session_lifecycle::SessionLifecycleService;

#[derive(Clone)]
pub(crate) struct ScheduledAgentTaskService {
    lifecycle: SessionLifecycleService,
    provider_configs: ProviderConfigService,
    show_tool_results: bool,
}

impl ScheduledAgentTaskService {
    pub(crate) fn new(
        lifecycle: SessionLifecycleService,
        provider_configs: ProviderConfigService,
        show_tool_results: bool,
    ) -> Self {
        Self {
            lifecycle,
            provider_configs,
            show_tool_results,
        }
    }

    pub(crate) async fn run(
        &self,
        channel_name: &str,
        chat_id: &str,
        notification_chat_id: Option<&str>,
        prompt: &str,
        options: ScheduledAgentTaskOptions,
    ) -> Result<Vec<OutboundMessage>, AgentError> {
        // 根据 chat_id 自动选择 Session：
        // - scheduler/ 开头：使用定时任务专用 Session（独立实例，不与用户消息竞争锁）
        // - 其他：使用主 Session
        let session = self.lifecycle.active_session_for_chat_id(channel_name, chat_id).await?;
        let sender_id = options
            .sender_id
            .clone()
            .unwrap_or_else(|| "scheduler".to_string());
        let provider_config = self.provider_configs.select(options.agent.as_deref())?;

        AgentExecutionService::new(self.show_tool_results)
            .prepare_and_execute_scheduled_task(ScheduledExecutionRequest {
                session,
                channel_name,
                chat_id,
                notification_chat_id,
                prompt,
                sender_id: &sender_id,
                provider_config,
                system_prompt: options.system_prompt.as_deref(),
                metadata: &options.metadata,
                fresh_session: options.fresh_session,
            })
            .await
    }
}
