use std::sync::Arc;

use agent_client_protocol::schema as acp;
use chrono::{Local, Utc};
use gpui::{App, SharedString, Task};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::{AgentTool, ToolCallEventStream, ToolInput};

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[schemars(inline)]
pub enum Timezone {
    /// Use UTC for the datetime.
    #[serde(alias = "UTC", alias = "Utc")]
    Utc,
    /// Use local time for the datetime.
    #[serde(alias = "LOCAL", alias = "Local")]
    Local,
}

/// Returns the current datetime in RFC 3339 format.
/// Only use this tool when the user specifically asks for it or the current task would benefit from knowing the current datetime.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct NowToolInput {
    /// The timezone to use for the datetime.
    timezone: Timezone,
}

pub struct NowTool;

impl AgentTool for NowTool {
    type Input = NowToolInput;
    type Output = String;

    const NAME: &'static str = "now";

    fn kind() -> acp::ToolKind {
        acp::ToolKind::Other
    }

    fn initial_title(
        &self,
        _input: Result<Self::Input, serde_json::Value>,
        _cx: &mut App,
    ) -> SharedString {
        "Get current time".into()
    }

    fn run(
        self: Arc<Self>,
        input: ToolInput<Self::Input>,
        _event_stream: ToolCallEventStream,
        cx: &mut App,
    ) -> Task<Result<String, String>> {
        cx.spawn(async move |_cx| {
            let input = input
                .recv()
                .await
                .map_err(|e| format!("Failed to receive tool input: {e}"))?;
            let now = match input.timezone {
                Timezone::Utc => Utc::now().to_rfc3339(),
                Timezone::Local => Local::now().to_rfc3339(),
            };
            Ok(format!("The current datetime is {now}."))
        })
    }
}
