Skip to main content

poly_mcp/modules/
time.rs

1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use chrono::{Local, Utc, DateTime, Duration as ChronoDuration};
4use chrono_tz::Tz;
5use std::collections::HashMap;
6use std::sync::{Arc, Mutex};
7use tokio::time::{sleep as tokio_sleep, Duration};
8
9pub struct TimeModule {
10    scheduled_tasks: Arc<Mutex<HashMap<String, ScheduledTask>>>,
11    stopwatches: Arc<Mutex<HashMap<String, Stopwatch>>>,
12    timers: Arc<Mutex<HashMap<String, TimerEntry>>>,
13    alarms: Arc<Mutex<HashMap<String, Alarm>>>,
14}
15
16struct ScheduledTask {
17    id: String,
18    execute_at: DateTime<Utc>,
19    callback: String,
20    args: Value,
21    executed: bool,
22}
23
24#[derive(Clone, Debug)]
25struct Stopwatch {
26    name: String,
27    started_at: Option<DateTime<Utc>>,
28    elapsed_before_stop: i64, // milliseconds accumulated from previous start/stop cycles
29    laps: Vec<LapEntry>,
30    running: bool,
31}
32
33#[derive(Clone, Debug)]
34struct LapEntry {
35    lap_number: usize,
36    #[allow(dead_code)]
37    timestamp: DateTime<Utc>,
38    split_ms: i64,
39    total_ms: i64,
40}
41
42#[derive(Clone, Debug)]
43struct TimerEntry {
44    name: String,
45    duration_ms: i64,
46    started_at: DateTime<Utc>,
47}
48
49#[derive(Clone, Debug)]
50struct Alarm {
51    name: String,
52    alarm_time: DateTime<Utc>,
53    created_at: DateTime<Utc>,
54    triggered: bool,
55    message: Option<String>,
56}
57
58impl Default for TimeModule {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64impl TimeModule {
65    pub fn new() -> Self {
66        Self {
67            scheduled_tasks: Arc::new(Mutex::new(HashMap::new())),
68            stopwatches: Arc::new(Mutex::new(HashMap::new())),
69            timers: Arc::new(Mutex::new(HashMap::new())),
70            alarms: Arc::new(Mutex::new(HashMap::new())),
71        }
72    }
73
74    pub fn get_tools(&self) -> Vec<Value> {
75        vec![
76            json!({
77                "name": "time_now",
78                "description": "Get current timestamp in various formats",
79                "inputSchema": {
80                    "type": "object",
81                    "properties": {
82                        "format": {
83                            "type": "string",
84                            "enum": ["unix", "iso8601", "rfc3339", "rfc2822", "custom"],
85                            "description": "Timestamp format (default: iso8601)"
86                        },
87                        "custom_format": {
88                            "type": "string",
89                            "description": "Custom format string (when format=custom)"
90                        },
91                        "timezone": {
92                            "type": "string",
93                            "enum": ["local", "utc"],
94                            "description": "Timezone (default: local)"
95                        }
96                    }
97                }
98            }),
99            json!({
100                "name": "time_sleep",
101                "description": "Delay execution for a specified duration",
102                "inputSchema": {
103                    "type": "object",
104                    "properties": {
105                        "duration": {
106                            "type": "number",
107                            "description": "Duration in seconds"
108                        },
109                        "unit": {
110                            "type": "string",
111                            "enum": ["seconds", "milliseconds", "minutes", "hours"],
112                            "description": "Time unit (default: seconds)"
113                        }
114                    },
115                    "required": ["duration"]
116                }
117            }),
118            json!({
119                "name": "time_schedule",
120                "description": "Schedule a task for future execution (in-memory, process lifetime)",
121                "inputSchema": {
122                    "type": "object",
123                    "properties": {
124                        "task_id": {
125                            "type": "string",
126                            "description": "Unique task identifier"
127                        },
128                        "execute_in": {
129                            "type": "number",
130                            "description": "Seconds until execution"
131                        },
132                        "execute_at": {
133                            "type": "string",
134                            "description": "ISO8601 timestamp for execution"
135                        },
136                        "callback": {
137                            "type": "string",
138                            "description": "Callback identifier/name"
139                        },
140                        "args": {
141                            "type": "object",
142                            "description": "Arguments to pass to callback"
143                        },
144                        "action": {
145                            "type": "string",
146                            "enum": ["create", "cancel", "list", "status"],
147                            "description": "Action to perform (default: create)"
148                        }
149                    }
150                }
151            }),
152            json!({
153                "name": "time_timezone",
154                "description": "Convert timestamps between IANA timezones or list available timezone names",
155                "inputSchema": {
156                    "type": "object",
157                    "properties": {
158                        "action": {
159                            "type": "string",
160                            "enum": ["convert", "list"],
161                            "description": "Action to perform (default: convert)"
162                        },
163                        "timestamp": {
164                            "type": "string",
165                            "description": "ISO8601/RFC3339 timestamp to convert (default: current time)"
166                        },
167                        "from_tz": {
168                            "type": "string",
169                            "description": "Source timezone, e.g. 'America/New_York', 'UTC', 'Europe/London'"
170                        },
171                        "to_tz": {
172                            "type": "string",
173                            "description": "Target timezone"
174                        },
175                        "filter": {
176                            "type": "string",
177                            "description": "Filter timezone list by substring (for action=list)"
178                        }
179                    }
180                }
181            }),
182            json!({
183                "name": "time_stopwatch",
184                "description": "Manage named stopwatches for timing operations. Supports start, stop, lap, reset, status, and list actions.",
185                "inputSchema": {
186                    "type": "object",
187                    "properties": {
188                        "name": {
189                            "type": "string",
190                            "description": "Stopwatch name (default: 'default')"
191                        },
192                        "action": {
193                            "type": "string",
194                            "enum": ["start", "stop", "lap", "reset", "status", "list"],
195                            "description": "Action to perform (default: status)"
196                        }
197                    }
198                }
199            }),
200            json!({
201                "name": "time_timer",
202                "description": "Set countdown timers with names. Start a timer, check remaining time, cancel, or list all timers.",
203                "inputSchema": {
204                    "type": "object",
205                    "properties": {
206                        "name": {
207                            "type": "string",
208                            "description": "Timer name (default: 'default')"
209                        },
210                        "action": {
211                            "type": "string",
212                            "enum": ["start", "check", "cancel", "list"],
213                            "description": "Action to perform (default: check)"
214                        },
215                        "duration": {
216                            "type": "number",
217                            "description": "Duration value (required for start)"
218                        },
219                        "unit": {
220                            "type": "string",
221                            "enum": ["seconds", "minutes", "hours"],
222                            "description": "Time unit for duration (default: seconds)"
223                        }
224                    }
225                }
226            }),
227            json!({
228                "name": "time_alarm",
229                "description": "Set alarms for specific times. Check, list, or cancel alarms. Alarms are in-memory only.",
230                "inputSchema": {
231                    "type": "object",
232                    "properties": {
233                        "name": {
234                            "type": "string",
235                            "description": "Alarm name"
236                        },
237                        "action": {
238                            "type": "string",
239                            "enum": ["set", "check", "cancel", "list"],
240                            "description": "Action to perform (default: list)"
241                        },
242                        "time": {
243                            "type": "string",
244                            "description": "ISO8601/RFC3339 timestamp for alarm (for action=set)"
245                        },
246                        "in_seconds": {
247                            "type": "number",
248                            "description": "Alternative: set alarm N seconds from now"
249                        },
250                        "message": {
251                            "type": "string",
252                            "description": "Optional message associated with the alarm"
253                        }
254                    }
255                }
256            }),
257        ]
258    }
259
260    // ── Existing tools ──────────────────────────────────────────────────
261
262    pub async fn now(&self, args: Value) -> Result<Value> {
263        let format = args["format"].as_str().unwrap_or("iso8601");
264        let timezone = args["timezone"].as_str().unwrap_or("local");
265        let custom_format = args["custom_format"].as_str();
266
267        let (local_time, utc_time) = (Local::now(), Utc::now());
268
269        let time_to_use = match timezone {
270            "utc" => utc_time.with_timezone(&Utc),
271            _ => local_time.with_timezone(&Local).with_timezone(&Utc),
272        };
273
274        let formatted = match format {
275            "unix" => time_to_use.timestamp().to_string(),
276            "iso8601" => time_to_use.to_rfc3339(),
277            "rfc3339" => time_to_use.to_rfc3339(),
278            "rfc2822" => time_to_use.to_rfc2822(),
279            "custom" => {
280                if let Some(fmt) = custom_format {
281                    time_to_use.format(fmt).to_string()
282                } else {
283                    return Err(anyhow::anyhow!("custom_format required when format=custom"));
284                }
285            }
286            _ => time_to_use.to_rfc3339(),
287        };
288
289        Ok(json!({
290            "timestamp": formatted,
291            "unix": time_to_use.timestamp(),
292            "unix_millis": time_to_use.timestamp_millis(),
293            "unix_nanos": time_to_use.timestamp_nanos_opt(),
294            "timezone": timezone,
295            "format": format,
296            "local": local_time.to_rfc3339(),
297            "utc": utc_time.to_rfc3339()
298        }))
299    }
300
301    pub async fn sleep(&self, args: Value) -> Result<Value> {
302        let duration = args["duration"].as_f64().context("Missing 'duration' parameter")?;
303        let unit = args["unit"].as_str().unwrap_or("seconds");
304
305        let sleep_duration = match unit {
306            "milliseconds" => Duration::from_millis(duration as u64),
307            "minutes" => Duration::from_secs((duration * 60.0) as u64),
308            "hours" => Duration::from_secs((duration * 3600.0) as u64),
309            _ => Duration::from_secs(duration as u64),
310        };
311
312        let start = std::time::Instant::now();
313        tokio_sleep(sleep_duration).await;
314        let actual_duration = start.elapsed();
315
316        Ok(json!({
317            "success": true,
318            "requested_duration": duration,
319            "unit": unit,
320            "actual_duration_ms": actual_duration.as_millis(),
321            "actual_duration_secs": actual_duration.as_secs_f64()
322        }))
323    }
324
325    pub async fn schedule(&self, args: Value) -> Result<Value> {
326        let action = args["action"].as_str().unwrap_or("create");
327
328        match action {
329            "create" => self.schedule_create(args).await,
330            "cancel" => self.schedule_cancel(args).await,
331            "list" => self.schedule_list(args).await,
332            "status" => self.schedule_status(args).await,
333            _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
334        }
335    }
336
337    async fn schedule_create(&self, args: Value) -> Result<Value> {
338        let task_id = args["task_id"].as_str()
339            .context("Missing 'task_id' parameter")?
340            .to_string();
341
342        let callback = args["callback"].as_str()
343            .context("Missing 'callback' parameter")?
344            .to_string();
345
346        let task_args = args["args"].clone();
347
348        let execute_at = if let Some(execute_in) = args["execute_in"].as_f64() {
349            Utc::now() + ChronoDuration::seconds(execute_in as i64)
350        } else if let Some(timestamp_str) = args["execute_at"].as_str() {
351            DateTime::parse_from_rfc3339(timestamp_str)
352                .context("Invalid ISO8601 timestamp")?
353                .with_timezone(&Utc)
354        } else {
355            return Err(anyhow::anyhow!("Must provide either 'execute_in' or 'execute_at'"));
356        };
357
358        let task = ScheduledTask {
359            id: task_id.clone(),
360            execute_at,
361            callback: callback.clone(),
362            args: task_args,
363            executed: false,
364        };
365
366        let mut tasks = self.scheduled_tasks.lock().unwrap();
367        tasks.insert(task_id.clone(), task);
368
369        Ok(json!({
370            "success": true,
371            "task_id": task_id,
372            "execute_at": execute_at.to_rfc3339(),
373            "callback": callback,
374            "message": "Task scheduled (in-memory, will be lost on process restart)"
375        }))
376    }
377
378    async fn schedule_cancel(&self, args: Value) -> Result<Value> {
379        let task_id = args["task_id"].as_str().context("Missing 'task_id' parameter")?;
380
381        let mut tasks = self.scheduled_tasks.lock().unwrap();
382
383        if tasks.remove(task_id).is_some() {
384            Ok(json!({
385                "success": true,
386                "task_id": task_id,
387                "message": "Task cancelled"
388            }))
389        } else {
390            Err(anyhow::anyhow!("Task not found: {}", task_id))
391        }
392    }
393
394    async fn schedule_list(&self, _args: Value) -> Result<Value> {
395        let mut tasks = self.scheduled_tasks.lock().unwrap();
396        let now = Utc::now();
397
398        // Clean up old executed tasks (keep only last 24h)
399        let cutoff = now - ChronoDuration::hours(24);
400        tasks.retain(|_, t| !t.executed || t.execute_at > cutoff);
401
402        let task_list: Vec<Value> = tasks.values().map(|task| {
403            let time_until = task.execute_at.signed_duration_since(now);
404
405            json!({
406                "task_id": task.id,
407                "callback": task.callback,
408                "execute_at": task.execute_at.to_rfc3339(),
409                "executed": task.executed,
410                "seconds_until": time_until.num_seconds(),
411                "overdue": time_until.num_seconds() < 0
412            })
413        }).collect();
414
415        Ok(json!({
416            "tasks": task_list,
417            "count": task_list.len(),
418            "current_time": now.to_rfc3339()
419        }))
420    }
421
422    async fn schedule_status(&self, args: Value) -> Result<Value> {
423        let task_id = args["task_id"].as_str().context("Missing 'task_id' parameter")?;
424
425        let tasks = self.scheduled_tasks.lock().unwrap();
426
427        if let Some(task) = tasks.get(task_id) {
428            let now = Utc::now();
429            let time_until = task.execute_at.signed_duration_since(now);
430
431            Ok(json!({
432                "task_id": task.id,
433                "callback": task.callback,
434                "args": task.args,
435                "execute_at": task.execute_at.to_rfc3339(),
436                "executed": task.executed,
437                "seconds_until": time_until.num_seconds(),
438                "overdue": time_until.num_seconds() < 0,
439                "current_time": now.to_rfc3339()
440            }))
441        } else {
442            Err(anyhow::anyhow!("Task not found: {}", task_id))
443        }
444    }
445
446    // ── Timezone ────────────────────────────────────────────────────────
447
448    pub async fn timezone(&self, args: Value) -> Result<Value> {
449        let action = args["action"].as_str().unwrap_or("convert");
450
451        match action {
452            "convert" => self.timezone_convert(args).await,
453            "list" => self.timezone_list(args).await,
454            _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
455        }
456    }
457
458    async fn timezone_convert(&self, args: Value) -> Result<Value> {
459        let to_tz_str = args["to_tz"].as_str().context("Missing 'to_tz' parameter")?;
460        let to_tz: Tz = to_tz_str.parse()
461            .map_err(|_| anyhow::anyhow!("Invalid timezone: {}", to_tz_str))?;
462
463        let source_dt = if let Some(ts) = args["timestamp"].as_str() {
464            DateTime::parse_from_rfc3339(ts)
465                .context("Invalid timestamp (expected RFC3339/ISO8601)")?
466                .with_timezone(&Utc)
467        } else {
468            Utc::now()
469        };
470
471        let converted = if let Some(from_tz_str) = args["from_tz"].as_str() {
472            let from_tz: Tz = from_tz_str.parse()
473                .map_err(|_| anyhow::anyhow!("Invalid timezone: {}", from_tz_str))?;
474            let in_source = source_dt.with_timezone(&from_tz);
475            in_source.with_timezone(&to_tz)
476        } else {
477            source_dt.with_timezone(&to_tz)
478        };
479
480        Ok(json!({
481            "original": source_dt.to_rfc3339(),
482            "converted": converted.to_string(),
483            "to_tz": to_tz_str,
484            "from_tz": args["from_tz"].as_str().unwrap_or("UTC"),
485            "utc": source_dt.to_rfc3339(),
486            "unix": source_dt.timestamp()
487        }))
488    }
489
490    async fn timezone_list(&self, args: Value) -> Result<Value> {
491        let filter = args["filter"].as_str().unwrap_or("");
492
493        let timezones: Vec<&str> = if filter.is_empty() {
494            chrono_tz::TZ_VARIANTS.iter().map(|tz| tz.name()).collect()
495        } else {
496            let filter_lower = filter.to_lowercase();
497            chrono_tz::TZ_VARIANTS
498                .iter()
499                .map(|tz| tz.name())
500                .filter(|name| name.to_lowercase().contains(&filter_lower))
501                .collect()
502        };
503
504        Ok(json!({
505            "timezones": timezones,
506            "count": timezones.len(),
507            "filter": if filter.is_empty() { None } else { Some(filter) }
508        }))
509    }
510
511    // ── Stopwatch ───────────────────────────────────────────────────────
512
513    pub async fn stopwatch(&self, args: Value) -> Result<Value> {
514        let action = args["action"].as_str().unwrap_or("status");
515        let name = args["name"].as_str().unwrap_or("default");
516
517        match action {
518            "start" => self.stopwatch_start(name).await,
519            "stop" => self.stopwatch_stop(name).await,
520            "lap" => self.stopwatch_lap(name).await,
521            "reset" => self.stopwatch_reset(name).await,
522            "status" => self.stopwatch_status(name).await,
523            "list" => self.stopwatch_list().await,
524            _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
525        }
526    }
527
528    async fn stopwatch_start(&self, name: &str) -> Result<Value> {
529        let mut watches = self.stopwatches.lock().unwrap();
530        let now = Utc::now();
531
532        if let Some(sw) = watches.get_mut(name) {
533            if sw.running {
534                return Err(anyhow::anyhow!("Stopwatch '{}' is already running", name));
535            }
536            sw.started_at = Some(now);
537            sw.running = true;
538            Ok(json!({
539                "name": name,
540                "action": "resumed",
541                "elapsed_before_ms": sw.elapsed_before_stop,
542                "started_at": now.to_rfc3339()
543            }))
544        } else {
545            watches.insert(name.to_string(), Stopwatch {
546                name: name.to_string(),
547                started_at: Some(now),
548                elapsed_before_stop: 0,
549                laps: Vec::new(),
550                running: true,
551            });
552            Ok(json!({
553                "name": name,
554                "action": "started",
555                "started_at": now.to_rfc3339()
556            }))
557        }
558    }
559
560    async fn stopwatch_stop(&self, name: &str) -> Result<Value> {
561        let mut watches = self.stopwatches.lock().unwrap();
562        let sw = watches.get_mut(name)
563            .with_context(|| format!("Stopwatch '{}' not found", name))?;
564
565        if !sw.running {
566            return Err(anyhow::anyhow!("Stopwatch '{}' is not running", name));
567        }
568
569        let now = Utc::now();
570        let elapsed_this_run = now.signed_duration_since(sw.started_at.unwrap()).num_milliseconds();
571        sw.elapsed_before_stop += elapsed_this_run;
572        sw.started_at = None;
573        sw.running = false;
574
575        let total_ms = sw.elapsed_before_stop;
576
577        Ok(json!({
578            "name": name,
579            "action": "stopped",
580            "elapsed_ms": total_ms,
581            "elapsed_secs": total_ms as f64 / 1000.0,
582            "elapsed_formatted": format_duration_ms(total_ms),
583            "laps": sw.laps.len()
584        }))
585    }
586
587    async fn stopwatch_lap(&self, name: &str) -> Result<Value> {
588        let mut watches = self.stopwatches.lock().unwrap();
589        let sw = watches.get_mut(name)
590            .with_context(|| format!("Stopwatch '{}' not found", name))?;
591
592        if !sw.running {
593            return Err(anyhow::anyhow!("Stopwatch '{}' is not running", name));
594        }
595
596        let now = Utc::now();
597        let elapsed_this_run = now.signed_duration_since(sw.started_at.unwrap()).num_milliseconds();
598        let total_ms = sw.elapsed_before_stop + elapsed_this_run;
599
600        let last_lap_total = sw.laps.last().map(|l| l.total_ms).unwrap_or(0);
601        let split_ms = total_ms - last_lap_total;
602        let lap_number = sw.laps.len() + 1;
603
604        let lap = LapEntry {
605            lap_number,
606            timestamp: now,
607            split_ms,
608            total_ms,
609        };
610        sw.laps.push(lap);
611
612        Ok(json!({
613            "name": name,
614            "lap_number": lap_number,
615            "split_ms": split_ms,
616            "split_formatted": format_duration_ms(split_ms),
617            "total_ms": total_ms,
618            "total_formatted": format_duration_ms(total_ms),
619            "timestamp": now.to_rfc3339()
620        }))
621    }
622
623    async fn stopwatch_reset(&self, name: &str) -> Result<Value> {
624        let mut watches = self.stopwatches.lock().unwrap();
625        let removed = watches.remove(name).is_some();
626
627        Ok(json!({
628            "name": name,
629            "action": "reset",
630            "removed": removed
631        }))
632    }
633
634    async fn stopwatch_status(&self, name: &str) -> Result<Value> {
635        let watches = self.stopwatches.lock().unwrap();
636
637        if let Some(sw) = watches.get(name) {
638            let now = Utc::now();
639            let total_ms = if sw.running {
640                let elapsed_this_run = now.signed_duration_since(sw.started_at.unwrap()).num_milliseconds();
641                sw.elapsed_before_stop + elapsed_this_run
642            } else {
643                sw.elapsed_before_stop
644            };
645
646            let laps: Vec<Value> = sw.laps.iter().map(|lap| {
647                json!({
648                    "lap": lap.lap_number,
649                    "split_ms": lap.split_ms,
650                    "split_formatted": format_duration_ms(lap.split_ms),
651                    "total_ms": lap.total_ms,
652                    "total_formatted": format_duration_ms(lap.total_ms)
653                })
654            }).collect();
655
656            Ok(json!({
657                "name": name,
658                "running": sw.running,
659                "elapsed_ms": total_ms,
660                "elapsed_secs": total_ms as f64 / 1000.0,
661                "elapsed_formatted": format_duration_ms(total_ms),
662                "laps": laps,
663                "lap_count": sw.laps.len(),
664                "found": true
665            }))
666        } else {
667            Ok(json!({
668                "name": name,
669                "found": false
670            }))
671        }
672    }
673
674    async fn stopwatch_list(&self) -> Result<Value> {
675        let watches = self.stopwatches.lock().unwrap();
676        let now = Utc::now();
677
678        let list: Vec<Value> = watches.values().map(|sw| {
679            let total_ms = if sw.running {
680                let elapsed = now.signed_duration_since(sw.started_at.unwrap()).num_milliseconds();
681                sw.elapsed_before_stop + elapsed
682            } else {
683                sw.elapsed_before_stop
684            };
685
686            json!({
687                "name": sw.name,
688                "running": sw.running,
689                "elapsed_ms": total_ms,
690                "elapsed_formatted": format_duration_ms(total_ms),
691                "laps": sw.laps.len()
692            })
693        }).collect();
694
695        Ok(json!({
696            "stopwatches": list,
697            "count": list.len()
698        }))
699    }
700
701    // ── Timer ───────────────────────────────────────────────────────────
702
703    pub async fn timer(&self, args: Value) -> Result<Value> {
704        let action = args["action"].as_str().unwrap_or("check");
705        let name = args["name"].as_str().unwrap_or("default");
706
707        match action {
708            "start" => self.timer_start(name, &args).await,
709            "check" => self.timer_check(name).await,
710            "cancel" => self.timer_cancel(name).await,
711            "list" => self.timer_list().await,
712            _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
713        }
714    }
715
716    async fn timer_start(&self, name: &str, args: &Value) -> Result<Value> {
717        let duration = args["duration"].as_f64()
718            .context("Missing 'duration' parameter for start action")?;
719        let unit = args["unit"].as_str().unwrap_or("seconds");
720
721        let duration_ms = match unit {
722            "minutes" => (duration * 60_000.0) as i64,
723            "hours" => (duration * 3_600_000.0) as i64,
724            _ => (duration * 1000.0) as i64,
725        };
726
727        let now = Utc::now();
728        let entry = TimerEntry {
729            name: name.to_string(),
730            duration_ms,
731            started_at: now,
732        };
733
734        let mut timers = self.timers.lock().unwrap();
735        timers.insert(name.to_string(), entry);
736
737        let ends_at = now + ChronoDuration::milliseconds(duration_ms);
738
739        Ok(json!({
740            "name": name,
741            "action": "started",
742            "duration_ms": duration_ms,
743            "duration_formatted": format_duration_ms(duration_ms),
744            "started_at": now.to_rfc3339(),
745            "ends_at": ends_at.to_rfc3339()
746        }))
747    }
748
749    async fn timer_check(&self, name: &str) -> Result<Value> {
750        let timers = self.timers.lock().unwrap();
751        let timer = timers.get(name)
752            .with_context(|| format!("Timer '{}' not found", name))?;
753
754        let now = Utc::now();
755        let elapsed_ms = now.signed_duration_since(timer.started_at).num_milliseconds();
756        let remaining_ms = (timer.duration_ms - elapsed_ms).max(0);
757        let expired = elapsed_ms >= timer.duration_ms;
758        let percent = ((elapsed_ms as f64 / timer.duration_ms as f64) * 100.0).min(100.0);
759
760        let ends_at = timer.started_at + ChronoDuration::milliseconds(timer.duration_ms);
761
762        Ok(json!({
763            "name": name,
764            "expired": expired,
765            "remaining_ms": remaining_ms,
766            "remaining_secs": remaining_ms as f64 / 1000.0,
767            "remaining_formatted": format_duration_ms(remaining_ms),
768            "elapsed_ms": elapsed_ms,
769            "percent_complete": format!("{:.1}", percent),
770            "duration_ms": timer.duration_ms,
771            "started_at": timer.started_at.to_rfc3339(),
772            "ends_at": ends_at.to_rfc3339()
773        }))
774    }
775
776    async fn timer_cancel(&self, name: &str) -> Result<Value> {
777        let mut timers = self.timers.lock().unwrap();
778        let removed = timers.remove(name).is_some();
779
780        Ok(json!({
781            "name": name,
782            "action": "cancelled",
783            "removed": removed
784        }))
785    }
786
787    async fn timer_list(&self) -> Result<Value> {
788        let timers = self.timers.lock().unwrap();
789        let now = Utc::now();
790
791        let list: Vec<Value> = timers.values().map(|t| {
792            let elapsed_ms = now.signed_duration_since(t.started_at).num_milliseconds();
793            let remaining_ms = (t.duration_ms - elapsed_ms).max(0);
794            let expired = elapsed_ms >= t.duration_ms;
795
796            json!({
797                "name": t.name,
798                "expired": expired,
799                "remaining_ms": remaining_ms,
800                "remaining_formatted": format_duration_ms(remaining_ms),
801                "duration_ms": t.duration_ms
802            })
803        }).collect();
804
805        Ok(json!({
806            "timers": list,
807            "count": list.len()
808        }))
809    }
810
811    // ── Alarm ───────────────────────────────────────────────────────────
812
813    pub async fn alarm(&self, args: Value) -> Result<Value> {
814        let action = args["action"].as_str().unwrap_or("list");
815
816        match action {
817            "set" => self.alarm_set(args).await,
818            "check" => self.alarm_check(args).await,
819            "cancel" => self.alarm_cancel(args).await,
820            "list" => self.alarm_list().await,
821            _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
822        }
823    }
824
825    async fn alarm_set(&self, args: Value) -> Result<Value> {
826        let name = args["name"].as_str().context("Missing 'name' parameter")?;
827        let message = args["message"].as_str().map(|s| s.to_string());
828        let now = Utc::now();
829
830        let alarm_time = if let Some(ts) = args["time"].as_str() {
831            DateTime::parse_from_rfc3339(ts)
832                .context("Invalid timestamp (expected RFC3339/ISO8601)")?
833                .with_timezone(&Utc)
834        } else if let Some(secs) = args["in_seconds"].as_f64() {
835            now + ChronoDuration::milliseconds((secs * 1000.0) as i64)
836        } else {
837            return Err(anyhow::anyhow!("Must provide either 'time' or 'in_seconds'"));
838        };
839
840        let alarm = Alarm {
841            name: name.to_string(),
842            alarm_time,
843            created_at: now,
844            triggered: alarm_time <= now,
845            message: message.clone(),
846        };
847
848        let mut alarms = self.alarms.lock().unwrap();
849        alarms.insert(name.to_string(), alarm);
850
851        let seconds_until = alarm_time.signed_duration_since(now).num_seconds();
852
853        Ok(json!({
854            "name": name,
855            "action": "set",
856            "alarm_time": alarm_time.to_rfc3339(),
857            "seconds_until": seconds_until,
858            "message": message,
859            "already_triggered": alarm_time <= now
860        }))
861    }
862
863    async fn alarm_check(&self, args: Value) -> Result<Value> {
864        let name = args["name"].as_str().context("Missing 'name' parameter")?;
865
866        let mut alarms = self.alarms.lock().unwrap();
867        let alarm = alarms.get_mut(name)
868            .with_context(|| format!("Alarm '{}' not found", name))?;
869
870        let now = Utc::now();
871        let triggered = now >= alarm.alarm_time;
872        if triggered {
873            alarm.triggered = true;
874        }
875
876        let seconds_until = alarm.alarm_time.signed_duration_since(now).num_seconds();
877
878        Ok(json!({
879            "name": name,
880            "triggered": triggered,
881            "alarm_time": alarm.alarm_time.to_rfc3339(),
882            "seconds_until": seconds_until,
883            "message": alarm.message,
884            "created_at": alarm.created_at.to_rfc3339()
885        }))
886    }
887
888    async fn alarm_cancel(&self, args: Value) -> Result<Value> {
889        let name = args["name"].as_str().context("Missing 'name' parameter")?;
890
891        let mut alarms = self.alarms.lock().unwrap();
892        let removed = alarms.remove(name).is_some();
893
894        Ok(json!({
895            "name": name,
896            "action": "cancelled",
897            "removed": removed
898        }))
899    }
900
901    async fn alarm_list(&self) -> Result<Value> {
902        let mut alarms = self.alarms.lock().unwrap();
903        let now = Utc::now();
904
905        let list: Vec<Value> = alarms.values_mut().map(|a| {
906            if now >= a.alarm_time {
907                a.triggered = true;
908            }
909            let seconds_until = a.alarm_time.signed_duration_since(now).num_seconds();
910
911            json!({
912                "name": a.name,
913                "triggered": a.triggered,
914                "alarm_time": a.alarm_time.to_rfc3339(),
915                "seconds_until": seconds_until,
916                "message": a.message,
917                "created_at": a.created_at.to_rfc3339()
918            })
919        }).collect();
920
921        Ok(json!({
922            "alarms": list,
923            "count": list.len(),
924            "current_time": now.to_rfc3339()
925        }))
926    }
927}
928
929fn format_duration_ms(ms: i64) -> String {
930    let total_secs = ms / 1000;
931    let millis = ms % 1000;
932    let hours = total_secs / 3600;
933    let minutes = (total_secs % 3600) / 60;
934    let secs = total_secs % 60;
935
936    if hours > 0 {
937        format!("{}h {}m {}s", hours, minutes, secs)
938    } else if minutes > 0 {
939        format!("{}m {}s", minutes, secs)
940    } else if secs > 0 {
941        format!("{}.{:03}s", secs, millis)
942    } else {
943        format!("{}ms", ms)
944    }
945}