eventix 0.5.0

High-level calendar & recurrence crate with timezone-aware scheduling, exceptions, and ICS import/export
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
//! Gap and overlap validation for calendar events
//!
//! This module provides functionality to detect gaps between events,
//! find overlapping events, and analyze schedule density - features
//! not commonly found in other calendar libraries.

use crate::calendar::Calendar;
use crate::error::Result;
use chrono::{DateTime, Duration};
use chrono_tz::Tz;

/// Represents a time gap between two events
#[derive(Debug, Clone)]
pub struct TimeGap {
    /// Start of the gap
    pub start: DateTime<Tz>,
    /// End of the gap
    pub end: DateTime<Tz>,
    /// Duration of the gap
    pub duration: Duration,
    /// Event before this gap (if any)
    pub before_event: Option<String>,
    /// Event after this gap (if any)
    pub after_event: Option<String>,
}

impl TimeGap {
    /// Create a new time gap
    pub fn new(
        start: DateTime<Tz>,
        end: DateTime<Tz>,
        before_event: Option<String>,
        after_event: Option<String>,
    ) -> Self {
        let duration = end.signed_duration_since(start);
        Self {
            start,
            end,
            duration,
            before_event,
            after_event,
        }
    }

    /// Get duration in minutes
    pub fn duration_minutes(&self) -> i64 {
        self.duration.num_minutes()
    }

    /// Get duration in hours
    pub fn duration_hours(&self) -> i64 {
        self.duration.num_hours()
    }

    /// Check if this gap is at least a certain duration
    pub fn is_at_least(&self, min_duration: Duration) -> bool {
        self.duration >= min_duration
    }
}

/// Represents an overlap between two or more events
#[derive(Debug, Clone)]
pub struct EventOverlap {
    /// Start of the overlap
    pub start: DateTime<Tz>,
    /// End of the overlap
    pub end: DateTime<Tz>,
    /// Duration of the overlap
    pub duration: Duration,
    /// Events involved in this overlap
    pub events: Vec<String>,
}

impl EventOverlap {
    /// Create a new event overlap
    pub fn new(start: DateTime<Tz>, end: DateTime<Tz>, events: Vec<String>) -> Self {
        let duration = end.signed_duration_since(start);
        Self {
            start,
            end,
            duration,
            events,
        }
    }

    /// Get duration in minutes
    pub fn duration_minutes(&self) -> i64 {
        self.duration.num_minutes()
    }

    /// Number of overlapping events
    pub fn event_count(&self) -> usize {
        self.events.len()
    }
}

/// Schedule density metrics
#[derive(Debug, Clone)]
pub struct ScheduleDensity {
    /// Total time span analyzed
    pub total_duration: Duration,
    /// Total time occupied by events
    pub busy_duration: Duration,
    /// Total free time
    pub free_duration: Duration,
    /// Percentage of time occupied (0.0 - 100.0)
    pub occupancy_percentage: f64,
    /// Number of events
    pub event_count: usize,
    /// Number of gaps
    pub gap_count: usize,
    /// Number of overlaps
    pub overlap_count: usize,
}

impl ScheduleDensity {
    /// Check if the schedule is considered busy (>60% occupied)
    pub fn is_busy(&self) -> bool {
        self.occupancy_percentage > 60.0
    }

    /// Check if the schedule is considered light (<30% occupied)
    pub fn is_light(&self) -> bool {
        self.occupancy_percentage < 30.0
    }

    /// Check if the schedule has any overlaps
    pub fn has_conflicts(&self) -> bool {
        self.overlap_count > 0
    }
}

/// Find all gaps between events in a time range
///
/// # Examples
///
/// ```
/// use eventix::{Calendar, Event, gap_validation};
/// use eventix::timezone::parse_datetime_with_tz;
/// use chrono::Duration;
///
/// let mut cal = Calendar::new("Test");
///
/// let event1 = Event::builder()
///     .title("Meeting 1")
///     .start("2025-11-01 09:00:00", "UTC")
///     .duration_hours(1)
///     .build()
///     .unwrap();
///
/// let event2 = Event::builder()
///     .title("Meeting 2")
///     .start("2025-11-01 11:00:00", "UTC")
///     .duration_hours(1)
///     .build()
///     .unwrap();
///
/// cal.add_event(event1);
/// cal.add_event(event2);
///
/// let tz = eventix::timezone::parse_timezone("UTC").unwrap();
/// let start = parse_datetime_with_tz("2025-11-01 08:00:00", tz).unwrap();
/// let end = parse_datetime_with_tz("2025-11-01 18:00:00", tz).unwrap();
///
/// let gaps = gap_validation::find_gaps(&cal, start, end, Duration::minutes(30)).unwrap();
/// assert!(gaps.len() > 0);
/// ```
pub fn find_gaps(
    calendar: &Calendar,
    start: DateTime<Tz>,
    end: DateTime<Tz>,
    min_gap_duration: Duration,
) -> Result<Vec<TimeGap>> {
    if start >= end {
        return Err(crate::error::EventixError::ValidationError(
            "Start time must be before end time".to_string(),
        ));
    }
    if min_gap_duration < Duration::zero() {
        return Err(crate::error::EventixError::ValidationError(
            "min_gap_duration cannot be negative".to_string(),
        ));
    }

    let mut occurrences = calendar.events_between(start, end)?;

    // Filter out inactive events (e.g. Cancelled)
    occurrences.retain(|e| e.event.is_active());

    // Sort by start time
    occurrences.sort_by_key(|o| o.occurrence_time);

    let mut gaps = Vec::new();
    let mut current_time = start;
    let mut last_event_title: Option<String> = None;

    for occurrence in occurrences.iter() {
        let event_start = occurrence.occurrence_time;

        // Check if there's a gap before this event
        if event_start > current_time {
            let gap = TimeGap::new(
                current_time,
                event_start,
                last_event_title.clone(),
                Some(occurrence.title().to_string()),
            );

            if gap.duration >= min_gap_duration {
                gaps.push(gap);
            }
        }

        // Move current time to end of this event
        let event_end = occurrence.end_time();
        if event_end > current_time {
            current_time = event_end;
            last_event_title = Some(occurrence.title().to_string());
        }
    }

    // Check for gap at the end
    if end > current_time {
        let gap = TimeGap::new(current_time, end, last_event_title, None);
        if gap.duration >= min_gap_duration {
            gaps.push(gap);
        }
    }

    Ok(gaps)
}

/// Find all overlapping events in a time range
///
/// # Examples
///
/// ```
/// use eventix::{Calendar, Event, gap_validation};
/// use eventix::timezone::parse_datetime_with_tz;
///
/// let mut cal = Calendar::new("Test");
///
/// let event1 = Event::builder()
///     .title("Meeting 1")
///     .start("2025-11-01 09:00:00", "UTC")
///     .duration_hours(2)
///     .build()
///     .unwrap();
///
/// let event2 = Event::builder()
///     .title("Meeting 2")
///     .start("2025-11-01 10:00:00", "UTC")
///     .duration_hours(1)
///     .build()
///     .unwrap();
///
/// cal.add_event(event1);
/// cal.add_event(event2);
///
/// let tz = eventix::timezone::parse_timezone("UTC").unwrap();
/// let start = parse_datetime_with_tz("2025-11-01 08:00:00", tz).unwrap();
/// let end = parse_datetime_with_tz("2025-11-01 18:00:00", tz).unwrap();
///
/// let overlaps = gap_validation::find_overlaps(&cal, start, end).unwrap();
/// assert_eq!(overlaps.len(), 1);
/// ```
pub fn find_overlaps(
    calendar: &Calendar,
    start: DateTime<Tz>,
    end: DateTime<Tz>,
) -> Result<Vec<EventOverlap>> {
    if start >= end {
        return Err(crate::error::EventixError::ValidationError(
            "Start time must be before end time".to_string(),
        ));
    }

    use std::collections::BTreeSet;

    let mut occurrences = calendar.events_between(start, end)?;

    // Filter out inactive events
    occurrences.retain(|e| e.event.is_active());

    // Filter out zero-duration events (where start == end)
    // With zero duration, the END checkpoint is processed as a no-op (event not yet active),
    // then START adds the event to the active set where it is never removed,
    // causing false-positive overlaps with all subsequent events.
    occurrences.retain(|occ| occ.occurrence_time != occ.end_time());

    // Early return for trivial cases (moved after zero-duration filter)
    if occurrences.len() < 2 {
        return Ok(Vec::new());
    }

    // Sweep Line Algorithm: O(N log N) instead of O(N²)
    //
    // Create checkpoints for each event's start and end.
    // We use a tuple: (time, is_end, index)
    // - is_end=true (1) means this is an END checkpoint
    // - is_end=false (0) means this is a START checkpoint
    //
    // CRITICAL: When times are equal, process ENDS before STARTS.
    // This prevents false positives for "touching" events.
    // Example: Event A ends at 10:00, Event B starts at 10:00
    // - If we process B's start before A's end, we'd think they overlap
    // - By processing A's end first, A is removed before B is added
    let mut checkpoints: Vec<(DateTime<Tz>, bool, usize)> =
        Vec::with_capacity(occurrences.len() * 2);
    for (i, occ) in occurrences.iter().enumerate() {
        checkpoints.push((occ.occurrence_time, false, i)); // START checkpoint
        checkpoints.push((occ.end_time(), true, i)); // END checkpoint
    }

    // Sort by: (1) time ascending, (2) END before START at equal timestamps.
    // Rust's bool ordering: false < true, so we reverse to place true (END) first.
    checkpoints.sort_by(|a, b| {
        a.0.cmp(&b.0).then_with(|| b.1.cmp(&a.1)) // reverse: END (true) before START (false)
    });

    let mut active: BTreeSet<usize> = BTreeSet::new();
    let mut overlaps = Vec::new();

    for (_time, is_end, idx) in checkpoints {
        if is_end {
            // Event ending - remove from active set
            active.remove(&idx);
        } else {
            // Event starting - check for overlaps with all currently active events
            for &active_idx in &active {
                let e1 = &occurrences[idx];
                let e2 = &occurrences[active_idx];

                // Calculate the actual overlap region
                let overlap_start = e1.occurrence_time.max(e2.occurrence_time);
                let overlap_end = e1.end_time().min(e2.end_time());

                overlaps.push(EventOverlap::new(
                    overlap_start,
                    overlap_end,
                    vec![e1.title().to_string(), e2.title().to_string()],
                ));
            }
            // Add this event to the active set
            active.insert(idx);
        }
    }

    Ok(overlaps)
}

/// Calculate schedule density metrics
///
/// # Examples
///
/// ```
/// use eventix::{Calendar, Event, gap_validation};
/// use eventix::timezone::parse_datetime_with_tz;
///
/// let mut cal = Calendar::new("Test");
///
/// let event = Event::builder()
///     .title("Meeting")
///     .start("2025-11-01 09:00:00", "UTC")
///     .duration_hours(2)
///     .build()
///     .unwrap();
///
/// cal.add_event(event);
///
/// let tz = eventix::timezone::parse_timezone("UTC").unwrap();
/// let start = parse_datetime_with_tz("2025-11-01 08:00:00", tz).unwrap();
/// let end = parse_datetime_with_tz("2025-11-01 18:00:00", tz).unwrap();
///
/// let density = gap_validation::calculate_density(&cal, start, end).unwrap();
/// assert!(density.occupancy_percentage > 0.0);
/// ```
pub fn calculate_density(
    calendar: &Calendar,
    start: DateTime<Tz>,
    end: DateTime<Tz>,
) -> Result<ScheduleDensity> {
    if start >= end {
        return Err(crate::error::EventixError::ValidationError(
            "Start time must be before end time".to_string(),
        ));
    }

    let total_duration = end.signed_duration_since(start);
    let mut occurrences = calendar.events_between(start, end)?;

    // Filter out inactive events
    occurrences.retain(|e| e.event.is_active());

    // Calculate busy time by merging overlapping intervals to avoid
    // double-counting shared time (which would make free_duration negative).
    occurrences.sort_by_key(|o| o.occurrence_time);
    let mut busy_duration = Duration::zero();
    let mut current_end: Option<DateTime<Tz>> = None;

    for occurrence in occurrences.iter() {
        let event_start = occurrence.occurrence_time.max(start);
        let event_end = occurrence.end_time().min(end);
        if event_end <= event_start {
            continue;
        }

        match current_end {
            None => {
                current_end = Some(event_end);
                busy_duration += event_end.signed_duration_since(event_start);
            }
            Some(prev_end) => {
                if event_start >= prev_end {
                    // No overlap — add full duration
                    busy_duration += event_end.signed_duration_since(event_start);
                    current_end = Some(event_end);
                } else if event_end > prev_end {
                    // Partial overlap — add only the extension past prev_end
                    busy_duration += event_end.signed_duration_since(prev_end);
                    current_end = Some(event_end);
                }
                // else: fully contained in previous interval, no additional busy time
            }
        }
    }

    let free_duration = total_duration - busy_duration;
    let occupancy_percentage =
        (busy_duration.num_seconds() as f64 / total_duration.num_seconds() as f64) * 100.0;

    let gaps = find_gaps(calendar, start, end, Duration::minutes(0))?;
    let overlaps = find_overlaps(calendar, start, end)?;

    Ok(ScheduleDensity {
        total_duration,
        busy_duration,
        free_duration,
        occupancy_percentage,
        event_count: occurrences.len(),
        gap_count: gaps.len(),
        overlap_count: overlaps.len(),
    })
}

/// Find the longest available gap in a time range
///
/// Returns the longest continuous gap that could fit a meeting.
pub fn find_longest_gap(
    calendar: &Calendar,
    start: DateTime<Tz>,
    end: DateTime<Tz>,
) -> Result<Option<TimeGap>> {
    let gaps = find_gaps(calendar, start, end, Duration::minutes(0))?;
    Ok(gaps.into_iter().max_by_key(|g| g.duration))
}

/// Find all gaps of at least a specified duration
///
/// Useful for finding time slots for meetings of a specific length.
pub fn find_available_slots(
    calendar: &Calendar,
    start: DateTime<Tz>,
    end: DateTime<Tz>,
    required_duration: Duration,
) -> Result<Vec<TimeGap>> {
    find_gaps(calendar, start, end, required_duration)
}

/// Check if a time slot is available (no conflicts)
pub fn is_slot_available(
    calendar: &Calendar,
    slot_start: DateTime<Tz>,
    slot_end: DateTime<Tz>,
) -> Result<bool> {
    if slot_start >= slot_end {
        return Err(crate::error::EventixError::ValidationError(
            "Slot start time must be before end time".to_string(),
        ));
    }

    for event in calendar.get_events() {
        if !event.is_active() {
            continue;
        }

        let duration = event.duration();
        if duration <= Duration::zero() {
            continue;
        }

        let query_start = slot_start - duration;
        let occurrences = event.occurrences_between(query_start, slot_end, 100_000)?;

        for occurrence in occurrences {
            let event_end = occurrence + duration;

            // Check for any overlap between event and slot
            if occurrence < slot_end && slot_start < event_end {
                return Ok(false);
            }
        }
    }

    Ok(true)
}

/// Suggest alternative times for a conflicting event
///
/// Finds available slots near the requested time.
///
/// # Examples
///
/// ```
/// use eventix::{Calendar, Event, gap_validation};
/// use eventix::timezone::parse_datetime_with_tz;
/// use chrono::Duration;
///
/// let mut cal = Calendar::new("Test");
/// let tz = eventix::timezone::parse_timezone("UTC").unwrap();
///
/// // Existing event 9-10
/// let event = Event::builder()
///     .title("Meeting")
///     .start("2025-11-01 09:00:00", "UTC")
///     .duration_hours(1)
///     .build()
///     .unwrap();
/// cal.add_event(event);
///
/// // Attempt to schedule 9:30-10:30 (conflict)
/// let requested = parse_datetime_with_tz("2025-11-01 09:30:00", tz).unwrap();
///
/// // Find alternatives within +/- 4 hours
/// let alternatives = gap_validation::suggest_alternatives(
///     &cal,
///     requested,
///     Duration::hours(1), // 1 hour duration
///     Duration::hours(4)  // Search window
/// ).unwrap();
///
/// assert!(alternatives.len() > 0);
/// ```
pub fn suggest_alternatives(
    calendar: &Calendar,
    requested_start: DateTime<Tz>,
    duration: Duration,
    search_window: Duration,
) -> Result<Vec<DateTime<Tz>>> {
    if duration <= Duration::zero() {
        return Err(crate::error::EventixError::ValidationError(
            "Duration must be greater than zero".to_string(),
        ));
    }
    if search_window <= Duration::zero() {
        return Err(crate::error::EventixError::ValidationError(
            "Search window must be greater than zero".to_string(),
        ));
    }

    let search_start = requested_start - search_window;
    let search_end = requested_start + search_window;

    let gaps = find_gaps(calendar, search_start, search_end, duration)?;

    let mut suggestions = Vec::new();
    for gap in gaps {
        // Check if the requested duration fits in this gap
        if gap.duration >= duration {
            // Suggest the start of the gap
            suggestions.push(gap.start);

            // Also suggest slots within the gap if it's large enough
            let mut slot_start = gap.start + Duration::hours(1);
            while slot_start + duration <= gap.end {
                suggestions.push(slot_start);
                slot_start += Duration::hours(1);
            }
        }
    }

    suggestions.sort();
    Ok(suggestions)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::len_zero)]
    use super::*;
    use crate::timezone::parse_datetime_with_tz;
    use crate::Calendar;
    use crate::Event;

    fn create_test_calendar() -> Result<Calendar> {
        let mut cal = Calendar::new("Test Calendar");

        let event1 = Event::builder()
            .title("Morning Meeting")
            .start("2025-11-01 09:00:00", "UTC")
            .duration_hours(1)
            .build()?;

        let event2 = Event::builder()
            .title("Lunch")
            .start("2025-11-01 12:00:00", "UTC")
            .duration_hours(1)
            .build()?;

        let event3 = Event::builder()
            .title("Afternoon Meeting")
            .start("2025-11-01 15:00:00", "UTC")
            .duration_hours(2)
            .build()?;

        cal.add_event(event1);
        cal.add_event(event2);
        cal.add_event(event3);

        Ok(cal)
    }

    #[test]
    fn test_find_gaps() {
        let cal = create_test_calendar().unwrap();
        let tz = crate::timezone::parse_timezone("UTC").unwrap();
        let start = parse_datetime_with_tz("2025-11-01 08:00:00", tz).unwrap();
        let end = parse_datetime_with_tz("2025-11-01 18:00:00", tz).unwrap();

        let gaps = find_gaps(&cal, start, end, Duration::minutes(30)).unwrap();

        // Should find gaps: 8-9am, 10am-12pm, 1-3pm, 5-6pm
        assert!(gaps.len() >= 3);
    }

    #[test]
    fn test_find_overlaps_no_conflict() {
        let cal = create_test_calendar().unwrap();
        let tz = crate::timezone::parse_timezone("UTC").unwrap();
        let start = parse_datetime_with_tz("2025-11-01 08:00:00", tz).unwrap();
        let end = parse_datetime_with_tz("2025-11-01 18:00:00", tz).unwrap();

        let overlaps = find_overlaps(&cal, start, end).unwrap();

        // No overlapping events in our test calendar
        assert_eq!(overlaps.len(), 0);
    }

    #[test]
    fn test_find_overlaps_with_conflict() {
        let mut cal = Calendar::new("Test");

        let event1 = Event::builder()
            .title("Meeting 1")
            .start("2025-11-01 09:00:00", "UTC")
            .duration_hours(2)
            .build()
            .unwrap();

        let event2 = Event::builder()
            .title("Meeting 2")
            .start("2025-11-01 10:00:00", "UTC")
            .duration_hours(1)
            .build()
            .unwrap();

        cal.add_event(event1);
        cal.add_event(event2);

        let tz = crate::timezone::parse_timezone("UTC").unwrap();
        let start = parse_datetime_with_tz("2025-11-01 08:00:00", tz).unwrap();
        let end = parse_datetime_with_tz("2025-11-01 18:00:00", tz).unwrap();

        let overlaps = find_overlaps(&cal, start, end).unwrap();

        assert_eq!(overlaps.len(), 1);
        assert_eq!(overlaps[0].duration_minutes(), 60);
    }

    #[test]
    fn test_calculate_density() {
        let cal = create_test_calendar().unwrap();
        let tz = crate::timezone::parse_timezone("UTC").unwrap();
        let start = parse_datetime_with_tz("2025-11-01 08:00:00", tz).unwrap();
        let end = parse_datetime_with_tz("2025-11-01 18:00:00", tz).unwrap();

        let density = calculate_density(&cal, start, end).unwrap();

        assert_eq!(density.event_count, 3);
        assert!(density.occupancy_percentage > 0.0);
        assert!(density.occupancy_percentage < 100.0);
        assert_eq!(density.overlap_count, 0);
    }

    #[test]
    fn test_is_slot_available() {
        let cal = create_test_calendar().unwrap();
        let tz = crate::timezone::parse_timezone("UTC").unwrap();

        // Available slot
        let slot_start = parse_datetime_with_tz("2025-11-01 10:00:00", tz).unwrap();
        let slot_end = parse_datetime_with_tz("2025-11-01 11:00:00", tz).unwrap();
        assert!(is_slot_available(&cal, slot_start, slot_end).unwrap());

        // Conflicting slot
        let conflict_start = parse_datetime_with_tz("2025-11-01 09:30:00", tz).unwrap();
        let conflict_end = parse_datetime_with_tz("2025-11-01 10:30:00", tz).unwrap();
        assert!(!is_slot_available(&cal, conflict_start, conflict_end).unwrap());
    }

    #[test]
    fn test_find_longest_gap() {
        let cal = create_test_calendar().unwrap();
        let tz = crate::timezone::parse_timezone("UTC").unwrap();
        let start = parse_datetime_with_tz("2025-11-01 08:00:00", tz).unwrap();
        let end = parse_datetime_with_tz("2025-11-01 18:00:00", tz).unwrap();

        let longest = find_longest_gap(&cal, start, end).unwrap();

        assert!(longest.is_some());
        let gap = longest.unwrap();
        assert!(gap.duration_minutes() >= 120); // At least 2 hours
    }

    #[test]
    fn test_find_available_slots() {
        let cal = create_test_calendar().unwrap();
        let tz = crate::timezone::parse_timezone("UTC").unwrap();
        let start = parse_datetime_with_tz("2025-11-01 08:00:00", tz).unwrap();
        let end = parse_datetime_with_tz("2025-11-01 18:00:00", tz).unwrap();

        // Find slots for 1-hour meeting
        let slots = find_available_slots(&cal, start, end, Duration::hours(1)).unwrap();

        assert!(slots.len() > 0);
        for slot in slots {
            assert!(slot.duration >= Duration::hours(1));
        }
    }

    #[test]
    fn test_suggest_alternatives() {
        let cal = create_test_calendar().unwrap();
        let tz = crate::timezone::parse_timezone("UTC").unwrap();

        // Try to schedule during morning meeting (conflict)
        let requested = parse_datetime_with_tz("2025-11-01 09:30:00", tz).unwrap();

        let alternatives =
            suggest_alternatives(&cal, requested, Duration::hours(1), Duration::hours(4)).unwrap();

        assert!(alternatives.len() > 0);
    }

    #[test]
    fn test_schedule_density_busy() {
        let mut cal = Calendar::new("Busy");

        // Create a packed schedule
        for hour in 9..17 {
            let event = Event::builder()
                .title(format!("Meeting {}", hour))
                .start(&format!("2025-11-01 {:02}:00:00", hour), "UTC")
                .duration_minutes(45)
                .build()
                .unwrap();
            cal.add_event(event);
        }

        let tz = crate::timezone::parse_timezone("UTC").unwrap();
        let start = parse_datetime_with_tz("2025-11-01 09:00:00", tz).unwrap();
        let end = parse_datetime_with_tz("2025-11-01 17:00:00", tz).unwrap();

        let density = calculate_density(&cal, start, end).unwrap();

        assert!(density.is_busy());
        assert!(density.occupancy_percentage > 60.0);
    }

    #[test]
    fn test_calculate_density_with_overlapping_events() {
        let mut cal = Calendar::new("Overlapping");

        // Event A: 09:00 - 11:00 (2 hours)
        cal.add_event(
            Event::builder()
                .title("Event A")
                .start("2025-11-01 09:00:00", "UTC")
                .duration_hours(2)
                .build()
                .unwrap(),
        );

        // Event B: 10:00 - 12:00 (2 hours, overlaps A by 1 hour)
        cal.add_event(
            Event::builder()
                .title("Event B")
                .start("2025-11-01 10:00:00", "UTC")
                .duration_hours(2)
                .build()
                .unwrap(),
        );

        let tz = crate::timezone::parse_timezone("UTC").unwrap();
        let start = parse_datetime_with_tz("2025-11-01 09:00:00", tz).unwrap();
        let end = parse_datetime_with_tz("2025-11-01 12:00:00", tz).unwrap();

        let density = calculate_density(&cal, start, end).unwrap();

        // Actual wall-clock busy time: 09:00 - 12:00 = 3 hours (the merged interval)
        // NOT 4 hours (2+2 with double-counting)
        assert_eq!(density.busy_duration.num_hours(), 3);

        // free = total - busy = 3h - 3h = 0
        assert_eq!(density.free_duration.num_seconds(), 0);

        // 100% occupied (fully busy window)
        assert!((density.occupancy_percentage - 100.0).abs() < 0.1);

        // Overlaps are still detected independently
        assert_eq!(density.overlap_count, 1);
    }
}