ticktickrs 0.1.4

A CLI Tool for TickTick tasks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Natural language date parsing utilities
//!
//! Provides functionality to parse dates from various formats including:
//! - Natural language: "today", "tomorrow", "next week"
//! - Relative: "in 3 days", "in 2 hours"
//! - Time specifications: "tomorrow at 2pm"
//! - ISO 8601 formats

use chrono::{DateTime, Duration, Local, NaiveTime, TimeZone, Utc};
use chrono_tz::Tz;
use thiserror::Error;

/// Errors that can occur during date parsing
#[derive(Debug, Error)]
pub enum DateParseError {
    #[error(
        "Could not parse date: '{0}'. Try formats like 'tomorrow', '2025-01-15', or 'in 3 days'."
    )]
    InvalidFormat(String),

    #[error("Invalid timezone: '{0}'")]
    #[allow(dead_code)] // Used by parse_date_with_timezone
    InvalidTimezone(String),

    #[error("Date is in the past: '{0}'")]
    #[allow(dead_code)] // Used by parse_future_date
    PastDate(String),
}

/// Parse a natural language date string into a UTC DateTime
///
/// Supports various formats:
/// - "today", "tomorrow", "yesterday"
/// - "next week", "next month"
/// - "in 3 days", "in 2 hours", "in 30 minutes"
/// - "tomorrow at 2pm", "friday at 14:00"
/// - ISO 8601: "2025-01-15", "2025-01-15T14:00:00Z"
///
/// # Arguments
/// * `input` - The date string to parse
///
/// # Returns
/// * `Ok(DateTime<Utc>)` - The parsed date in UTC
/// * `Err(DateParseError)` - If the date could not be parsed
pub fn parse_date(input: &str) -> Result<DateTime<Utc>, DateParseError> {
    let input = input.trim();
    let input_lower = input.to_lowercase();

    if input.is_empty() {
        return Err(DateParseError::InvalidFormat("empty string".to_string()));
    }

    // Handle natural language expressions that dateparser doesn't support
    let now = Utc::now();
    let today_start = now.date_naive().and_hms_opt(0, 0, 0).unwrap().and_utc();

    // Check for simple relative expressions
    if input_lower == "today" {
        return Ok(today_start);
    }

    if input_lower == "tomorrow" {
        return Ok(today_start + Duration::days(1));
    }

    if input_lower == "yesterday" {
        return Ok(today_start - Duration::days(1));
    }

    if input_lower == "next week" {
        return Ok(today_start + Duration::weeks(1));
    }

    if input_lower == "next month" {
        return Ok(today_start + Duration::days(30));
    }

    // Parse "in X days/hours/minutes" format
    if let Some(rest) = input_lower.strip_prefix("in ") {
        if let Some(result) = parse_relative_time(rest, now) {
            return Ok(result);
        }
    }

    // Try dateparser for ISO dates and other formats
    dateparser::parse(input).map_err(|_| DateParseError::InvalidFormat(input.to_string()))
}

/// Parse relative time expressions like "3 days", "2 hours", "30 minutes"
fn parse_relative_time(input: &str, base: DateTime<Utc>) -> Option<DateTime<Utc>> {
    let parts: Vec<&str> = input.split_whitespace().collect();
    if parts.len() < 2 {
        return None;
    }

    let amount: i64 = parts[0].parse().ok()?;
    let unit = parts[1].to_lowercase();

    match unit.as_str() {
        "day" | "days" => Some(base + Duration::days(amount)),
        "week" | "weeks" => Some(base + Duration::weeks(amount)),
        "hour" | "hours" => Some(base + Duration::hours(amount)),
        "minute" | "minutes" | "min" | "mins" => Some(base + Duration::minutes(amount)),
        "month" | "months" => Some(base + Duration::days(amount * 30)),
        _ => None,
    }
}

/// Parse a date string with a specific timezone
///
/// # Arguments
/// * `input` - The date string to parse
/// * `timezone` - The timezone name (e.g., "America/New_York", "Europe/London")
///
/// # Returns
/// * `Ok(DateTime<Utc>)` - The parsed date converted to UTC
/// * `Err(DateParseError)` - If parsing or timezone conversion fails
#[allow(dead_code)] // Available for external use
pub fn parse_date_with_timezone(
    input: &str,
    timezone: &str,
) -> Result<DateTime<Utc>, DateParseError> {
    let tz: Tz = timezone
        .parse()
        .map_err(|_| DateParseError::InvalidTimezone(timezone.to_string()))?;

    let input = input.trim();

    // First try to parse as a datetime with dateparser
    if let Ok(dt) = dateparser::parse(input) {
        return Ok(dt);
    }

    // If that fails, try parsing as a date-only and combine with timezone
    if let Ok(date) = chrono::NaiveDate::parse_from_str(input, "%Y-%m-%d") {
        let naive_dt = date.and_time(NaiveTime::from_hms_opt(0, 0, 0).unwrap());
        let local_dt = tz
            .from_local_datetime(&naive_dt)
            .single()
            .ok_or_else(|| DateParseError::InvalidFormat(input.to_string()))?;
        return Ok(local_dt.with_timezone(&Utc));
    }

    Err(DateParseError::InvalidFormat(input.to_string()))
}

/// Parse a date and ensure it's in the future
///
/// # Arguments
/// * `input` - The date string to parse
///
/// # Returns
/// * `Ok(DateTime<Utc>)` - The parsed date if it's in the future
/// * `Err(DateParseError::PastDate)` - If the date is in the past
#[allow(dead_code)] // Available for external use
pub fn parse_future_date(input: &str) -> Result<DateTime<Utc>, DateParseError> {
    let date = parse_date(input)?;

    if date < Utc::now() {
        return Err(DateParseError::PastDate(input.to_string()));
    }

    Ok(date)
}

/// Get the local timezone name
///
/// Returns the system's local timezone if available, otherwise "UTC"
#[allow(dead_code)] // Available for external use
pub fn local_timezone() -> String {
    // Try to get the TZ environment variable first
    if let Ok(tz) = std::env::var("TZ") {
        return tz;
    }

    // Default to the local timezone offset description
    Local::now().format("%Z").to_string()
}

/// Format a DateTime for display
///
/// # Arguments
/// * `dt` - The datetime to format
/// * `timezone` - Optional timezone for display (defaults to UTC)
///
/// # Returns
/// A formatted date string like "2025-01-15 14:00:00 UTC"
#[allow(dead_code)] // Available for external use
pub fn format_datetime(dt: &DateTime<Utc>, timezone: Option<&str>) -> String {
    if let Some(tz_str) = timezone {
        if let Ok(tz) = tz_str.parse::<Tz>() {
            let local_dt = dt.with_timezone(&tz);
            return local_dt.format("%Y-%m-%d %H:%M:%S %Z").to_string();
        }
    }

    dt.format("%Y-%m-%d %H:%M:%S UTC").to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_iso_date() {
        // Use a future date with explicit UTC time to avoid timezone issues
        let result = parse_date("2030-06-15T00:00:00Z");
        assert!(result.is_ok());
        let dt = result.unwrap();
        assert_eq!(dt.date_naive().to_string(), "2030-06-15");
    }

    #[test]
    fn test_parse_iso_datetime() {
        let result = parse_date("2025-01-15T14:30:00Z");
        assert!(result.is_ok());
        let dt = result.unwrap();
        assert_eq!(
            dt.format("%Y-%m-%dT%H:%M:%S").to_string(),
            "2025-01-15T14:30:00"
        );
    }

    #[test]
    fn test_parse_natural_language_today() {
        let result = parse_date("today");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let today = Utc::now().date_naive();
        assert_eq!(dt.date_naive(), today);
    }

    #[test]
    fn test_parse_natural_language_tomorrow() {
        let result = parse_date("tomorrow");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let tomorrow = Utc::now().date_naive() + chrono::Duration::days(1);
        assert_eq!(dt.date_naive(), tomorrow);
    }

    #[test]
    fn test_parse_relative_in_days() {
        let result = parse_date("in 3 days");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let expected = Utc::now().date_naive() + chrono::Duration::days(3);
        assert_eq!(dt.date_naive(), expected);
    }

    #[test]
    fn test_parse_empty_string() {
        let result = parse_date("");
        assert!(result.is_err());
        match result {
            Err(DateParseError::InvalidFormat(s)) => assert_eq!(s, "empty string"),
            _ => panic!("Expected InvalidFormat error"),
        }
    }

    #[test]
    fn test_parse_invalid_string() {
        let result = parse_date("not a date at all xyz");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_with_timezone() {
        let result = parse_date_with_timezone("2025-01-15", "America/New_York");
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_invalid_timezone() {
        let result = parse_date_with_timezone("2025-01-15", "Invalid/Timezone");
        assert!(result.is_err());
        match result {
            Err(DateParseError::InvalidTimezone(tz)) => assert_eq!(tz, "Invalid/Timezone"),
            _ => panic!("Expected InvalidTimezone error"),
        }
    }

    #[test]
    fn test_format_datetime_utc() {
        let dt = Utc.with_ymd_and_hms(2025, 1, 15, 14, 30, 0).unwrap();
        let formatted = format_datetime(&dt, None);
        assert_eq!(formatted, "2025-01-15 14:30:00 UTC");
    }

    #[test]
    fn test_format_datetime_with_timezone() {
        let dt = Utc.with_ymd_and_hms(2025, 1, 15, 19, 30, 0).unwrap();
        let formatted = format_datetime(&dt, Some("America/New_York"));
        // 19:30 UTC is 14:30 EST
        assert!(formatted.contains("2025-01-15"));
        assert!(formatted.contains("14:30:00"));
    }

    #[test]
    fn test_local_timezone() {
        // Just verify it returns a non-empty string
        let tz = local_timezone();
        assert!(!tz.is_empty());
    }

    #[test]
    fn test_date_parse_error_display() {
        let err = DateParseError::InvalidFormat("bad date".to_string());
        assert!(err.to_string().contains("bad date"));
        assert!(err.to_string().contains("Try formats like"));

        let err = DateParseError::InvalidTimezone("Bad/TZ".to_string());
        assert!(err.to_string().contains("Bad/TZ"));

        let err = DateParseError::PastDate("yesterday".to_string());
        assert!(err.to_string().contains("past"));
    }

    // === Additional edge case tests for Phase 13 ===

    #[test]
    fn test_parse_yesterday() {
        let result = parse_date("yesterday");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let yesterday = Utc::now().date_naive() - chrono::Duration::days(1);
        assert_eq!(dt.date_naive(), yesterday);
    }

    #[test]
    fn test_parse_next_week() {
        let result = parse_date("next week");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let next_week = Utc::now().date_naive() + chrono::Duration::weeks(1);
        assert_eq!(dt.date_naive(), next_week);
    }

    #[test]
    fn test_parse_next_month() {
        let result = parse_date("next month");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let next_month = Utc::now().date_naive() + chrono::Duration::days(30);
        assert_eq!(dt.date_naive(), next_month);
    }

    #[test]
    fn test_parse_in_hours() {
        let before = Utc::now();
        let result = parse_date("in 2 hours");
        assert!(result.is_ok());
        let dt = result.unwrap();
        // Should be approximately 2 hours from now
        let diff = dt - before;
        assert!(diff.num_hours() >= 1 && diff.num_hours() <= 2);
    }

    #[test]
    fn test_parse_in_minutes() {
        let before = Utc::now();
        let result = parse_date("in 30 minutes");
        assert!(result.is_ok());
        let dt = result.unwrap();
        // Should be approximately 30 minutes from now
        let diff = dt - before;
        assert!(diff.num_minutes() >= 29 && diff.num_minutes() <= 30);
    }

    #[test]
    fn test_parse_in_weeks() {
        let result = parse_date("in 2 weeks");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let expected = Utc::now().date_naive() + chrono::Duration::weeks(2);
        assert_eq!(dt.date_naive(), expected);
    }

    #[test]
    fn test_parse_in_months() {
        let result = parse_date("in 3 months");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let expected = Utc::now().date_naive() + chrono::Duration::days(90);
        assert_eq!(dt.date_naive(), expected);
    }

    #[test]
    fn test_parse_case_insensitive() {
        // All these should work the same
        assert!(parse_date("TODAY").is_ok());
        assert!(parse_date("Today").is_ok());
        assert!(parse_date("TOMORROW").is_ok());
        assert!(parse_date("Tomorrow").is_ok());
        assert!(parse_date("IN 3 DAYS").is_ok());
        assert!(parse_date("In 3 Days").is_ok());
    }

    #[test]
    fn test_parse_whitespace_handling() {
        // Leading/trailing whitespace should be trimmed
        let result = parse_date("  tomorrow  ");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let tomorrow = Utc::now().date_naive() + chrono::Duration::days(1);
        assert_eq!(dt.date_naive(), tomorrow);
    }

    #[test]
    fn test_parse_singular_units() {
        // Test singular forms of units
        assert!(parse_date("in 1 day").is_ok());
        assert!(parse_date("in 1 week").is_ok());
        assert!(parse_date("in 1 hour").is_ok());
        assert!(parse_date("in 1 minute").is_ok());
        assert!(parse_date("in 1 month").is_ok());
    }

    #[test]
    fn test_parse_min_abbreviation() {
        // Test min/mins abbreviation
        let before = Utc::now();
        let result = parse_date("in 15 min");
        assert!(result.is_ok());
        let dt = result.unwrap();
        let diff = dt - before;
        assert!(diff.num_minutes() >= 14 && diff.num_minutes() <= 15);

        let result = parse_date("in 15 mins");
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_future_date_valid() {
        // A date far in the future should pass
        let result = parse_future_date("in 30 days");
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_future_date_past() {
        // Yesterday should fail future date validation
        let result = parse_future_date("yesterday");
        assert!(result.is_err());
        match result {
            Err(DateParseError::PastDate(_)) => {}
            _ => panic!("Expected PastDate error"),
        }
    }

    #[test]
    fn test_parse_date_with_timezone_datetime() {
        // Test parsing a full datetime with timezone context
        let result = parse_date_with_timezone("2025-06-15T14:30:00Z", "America/Los_Angeles");
        assert!(result.is_ok());
    }

    #[test]
    fn test_format_datetime_invalid_timezone_fallback() {
        // Invalid timezone should fall back to UTC
        let dt = Utc.with_ymd_and_hms(2025, 1, 15, 14, 30, 0).unwrap();
        let formatted = format_datetime(&dt, Some("Invalid/TZ"));
        assert_eq!(formatted, "2025-01-15 14:30:00 UTC");
    }

    #[test]
    fn test_parse_incomplete_relative_time() {
        // "in" without enough parts should fail
        let result = parse_date("in 3");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_invalid_relative_unit() {
        // Invalid unit should fail
        let result = parse_date("in 3 foobar");
        assert!(result.is_err());
    }
}