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