use std::sync::Arc;

use async_trait::async_trait;

use crate::storage::Storage;

use super::traits::{Tool, ToolResult};

/// Safe, bounded maintenance operations used by the built-in monitor job.
pub struct RoutineMaintenanceTool {
    storage: Arc<Storage>,
    timeline_retention_days: u64,
}

impl RoutineMaintenanceTool {
    pub fn new(storage: Arc<Storage>, timeline_retention_days: u64) -> Self {
        Self {
            storage,
            timeline_retention_days,
        }
    }
}

#[async_trait]
impl Tool for RoutineMaintenanceTool {
    fn name(&self) -> &str {
        "routine_maintenance"
    }

    fn description(&self) -> &str {
        "Run PicoBot's safe routine maintenance: remove timeline memories older than the configured retention period. It never deletes long-term knowledge memories."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({"type": "object", "properties": {}})
    }

    async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
        let removed = self
            .storage
            .cleanup_old_timelines(self.timeline_retention_days)
            .await?;
        Ok(ToolResult {
            success: true,
            output: format!(
                "Routine maintenance completed: removed {removed} timeline memories older than {} days; knowledge memories were not modified.",
                self.timeline_retention_days
            ),
            error: None,
        })
    }
}
