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
//! Work interval calculation and productivity analysis for daily reports.
//!
//! Provides core logic for analyzing work patterns and generating detailed reports
//! about productivity, work intervals, and break patterns.
//!
//! ## Features
//!
//! - **Work Interval Analysis**: Convert workday and pause data into continuous work periods
//! - **Productivity Metrics**: Calculate efficiency ratios and work pattern analysis
//! - **Short Interval Detection**: Identify and analyze brief work periods that may indicate interruptions
//! - **Interval Filtering**: Filter out short intervals for cleaner reporting (display-level, no database changes)
//! - **Report Generation**: Comprehensive breakdown of workdays with productivity analysis
//!
//! ## Usage
//!
//! ```rust
//! use kasl::libs::report::{calculate_work_intervals, filter_short_intervals, WorkInterval};
//! use kasl::db::workdays::Workday;
//! use kasl::libs::pause::Pause;
//! use chrono::Local;
//!
//! let workday = Workday {
//! id: 1,
//! date: Local::now().date_naive(),
//! start: Local::now().naive_local(),
//! end: Some(Local::now().naive_local()),
//! };
//!
//! let pauses: Vec<Pause> = vec![/* pause data */];
//! let intervals = calculate_work_intervals(&workday, &pauses);
//!
//! // Filter short intervals for cleaner reporting
//! let (filtered_intervals, filter_info) = filter_short_intervals(&intervals, 30);
//! ```
use cratePause;
use crate::;
use Result;
use ;
/// Represents a single continuous work interval between breaks.
///
/// This structure captures a period of uninterrupted work time, providing
/// the foundation for productivity analysis and reporting. Each interval
/// represents a focused work session bounded by either the workday start/end
/// or pause periods.
///
/// ## Interval Boundaries
///
/// Work intervals are defined by:
/// - **Start Time**: When focused work began (workday start or end of previous pause)
/// - **End Time**: When focused work ended (start of next pause or workday end)
/// - **Duration**: Total time spent in focused work during this period
///
/// ## Pause Association
///
/// Each interval can be associated with the pause that follows it:
/// - **Some(index)**: Index of the pause that ended this work interval
/// - **None**: This interval extends to the end of the workday
///
/// This association enables:
/// - Analysis of work-break patterns
/// - Identification of interruption causes
/// - Optimization recommendations for pause timing
///
/// ## Usage Context
///
/// Work intervals are used for:
/// - Productivity calculation and analysis
/// - Generating detailed work reports
/// - Identifying optimization opportunities
/// - Visualizing work patterns in charts and graphs
/// Information about short intervals detected in a workday.
///
/// This structure provides comprehensive analysis of work intervals that
/// fall below the minimum duration threshold. It includes both statistical
/// information about the impact of short intervals and actionable
/// recommendations for optimization.
///
/// ## Analysis Components
///
/// ### Statistical Information
/// - **Count**: Number of short intervals detected
/// - **Total Duration**: Cumulative time spent in short work periods
/// - **Individual Intervals**: Specific intervals with their details
///
/// ### Optimization Recommendations
/// - **Pauses to Remove**: Specific pauses that could be eliminated
/// - **Merge Opportunities**: Intervals that could be combined
/// - **Productivity Impact**: Potential time savings from optimization
///
/// ## Usage Context
///
/// This analysis is used for:
/// - Generating optimization recommendations in reports
/// - Identifying patterns of work fragmentation
/// - Calculating potential productivity improvements
/// - Providing actionable feedback to users
/// Calculates work intervals for a given workday based on pause records.
///
/// This function performs the core algorithm for converting raw workday and
/// pause data into a structured collection of work intervals. It handles the
/// complexity of time calculations, pause filtering, and interval boundary
/// determination to produce accurate work period analysis.
///
/// ## Algorithm Overview
///
/// 1. **Initialization**: Start with workday boundaries and empty interval list
/// 2. **Pause Filtering**: Remove incomplete pauses and sort chronologically
/// 3. **Interval Generation**: Create work periods between consecutive pauses
/// 4. **Boundary Handling**: Handle workday start/end as interval boundaries
/// 5. **Duration Calculation**: Compute accurate durations for each interval
///
/// ## Pause Processing
///
/// The function handles various pause scenarios:
/// - **Complete Pauses**: Have both start and end times
/// - **Incomplete Pauses**: Missing end times (filtered out)
/// - **Overlapping Pauses**: Handled through chronological sorting
/// - **Out-of-bounds Pauses**: Pauses outside workday boundaries
///
/// ## Edge Cases Handled
///
/// - **No Pauses**: Single interval covering entire workday
/// - **Workday Boundaries**: Pauses at start/end of workday
/// - **Consecutive Pauses**: Multiple pauses with no work time between
/// - **Invalid Times**: Pauses with end time before start time
///
/// # Arguments
///
/// * `workday` - The workday record containing start and end times
/// * `pauses` - Collection of pause records for the workday
///
/// # Returns
///
/// A vector of `WorkInterval` objects representing continuous work periods.
///
/// # Examples
///
/// ```rust
/// use kasl::libs::report::calculate_work_intervals;
/// use kasl::db::workdays::Workday;
/// use kasl::libs::pause::Pause;
/// use chrono::{Local, Duration};
///
/// let start_time = Local::now().naive_local();
/// let end_time = start_time + Duration::hours(8);
/// let lunch_start = start_time + Duration::hours(4);
/// let lunch_end = lunch_start + Duration::minutes(30);
/// let lunch_duration = Duration::minutes(30);
///
/// let workday = Workday {
/// id: 1,
/// date: start_time.date(),
/// start: start_time,
/// end: Some(end_time),
/// // ... other fields
/// };
///
/// let pauses = vec![
/// Pause {
/// id: 1,
/// start: lunch_start,
/// end: Some(lunch_end),
/// duration: Some(lunch_duration),
/// protected: false,
/// },
/// // ... more pauses
/// ];
///
/// let intervals = calculate_work_intervals(&workday, &pauses);
/// println!("Generated {} work intervals", intervals.len());
/// ```
///
/// # Performance Considerations
///
/// - **Time Complexity**: O(n log n) due to pause sorting
/// - **Space Complexity**: O(n) for interval storage
/// - **Memory Usage**: Minimal allocation during processing
///
/// Resolves the effective end of a workday that has no recorded end time.
///
/// A workday stays open when the daemon was killed or the machine slept before
/// `kasl end` ran. "Now" is only a sensible stand-in while the day is still
/// today; for any earlier date it would stretch the day across every hour since,
/// which is how an unclosed August day reported 8425 hours. For a past date the
/// day is closed at the last evidence of activity - the end of its final pause,
/// or its start when nothing else is known.
/// Analyzes work intervals to identify short periods that may indicate poor productivity.
///
/// This function performs comprehensive analysis of work intervals to identify
/// periods that fall below the minimum duration threshold. It provides both
/// statistical analysis and actionable optimization recommendations to help
/// users improve their work patterns and productivity.
///
/// ## Analysis Process
///
/// 1. **Threshold Filtering**: Identify intervals shorter than minimum duration
/// 2. **Statistical Calculation**: Compute total count and cumulative duration
/// 3. **Optimization Analysis**: Identify pauses that could be removed
/// 4. **Recommendation Generation**: Provide specific improvement suggestions
///
/// ## Optimization Logic
///
/// Short intervals are typically created by pauses that interrupt focused work:
/// - **Pause Identification**: Find pauses that create short intervals
/// - **Merge Opportunities**: Identify intervals that could be combined
/// - **Impact Assessment**: Calculate potential productivity improvements
///
/// ## Return Value Analysis
///
/// - **Some(info)**: Short intervals detected, optimization possible
/// - **None**: No short intervals found, work patterns are optimal
///
/// # Arguments
///
/// * `intervals` - Collection of work intervals to analyze
/// * `min_minutes` - Minimum acceptable interval duration in minutes
///
/// # Returns
///
/// `Some(ShortIntervalsInfo)` if short intervals are found, `None` otherwise.
///
/// # Examples
///
/// ```rust
/// use kasl::libs::report::{analyze_short_intervals, WorkInterval};
///
/// let intervals = vec![/* work intervals */];
/// let min_duration = 30; // 30-minute minimum
///
/// match analyze_short_intervals(&intervals, min_duration) {
/// Some(analysis) => {
/// println!("Found {} short intervals", analysis.count);
/// println!("Total fragmented time: {:?}", analysis.total_duration);
/// println!("Optimization: remove pauses {:?}", analysis.pauses_to_remove);
/// },
/// None => {
/// println!("No short intervals detected - work patterns are optimal");
/// }
/// }
/// ```
///
/// # Optimization Recommendations
///
/// The function provides specific recommendations:
/// - **Pause Removal**: Eliminate unnecessary short breaks
/// - **Break Consolidation**: Combine multiple short breaks
/// - **Timing Adjustment**: Reschedule breaks to preserve focus periods
/// Filters out short work intervals from the provided interval list.
///
/// This function removes work intervals that are shorter than the specified
/// minimum duration, providing cleaner reporting by eliminating brief
/// interruptions that don't represent meaningful work periods. This is the
/// new approach for handling short intervals - filtering at display time
/// instead of modifying the database.
///
/// ## Filtering Logic
///
/// - Intervals shorter than `min_minutes` are excluded from the result
/// - Remaining intervals maintain their original timing and properties
/// - No database changes are made - this is purely a display/API filter
/// - Used by both `kasl report` (display) and `kasl report --send` (API submission)
///
/// ## Return Value
///
/// Returns a tuple containing:
/// - **Filtered intervals**: Only intervals meeting the minimum duration
/// - **Filtered intervals info**: Analysis of what was filtered out (if any)
///
/// # Arguments
///
/// * `intervals` - Original work intervals to filter
/// * `min_minutes` - Minimum duration in minutes for intervals to keep
///
/// # Returns
///
/// Returns `(filtered_intervals, filtered_info)` where:
/// - `filtered_intervals` contains only intervals >= min_minutes
/// - `filtered_info` contains details about filtered intervals (None if nothing was filtered)
///
/// # Examples
///
/// ```rust
/// use kasl::libs::report::{calculate_work_intervals, filter_short_intervals};
/// use kasl::db::workdays::Workday;
/// use kasl::libs::pause::Pause;
/// use chrono::Local;
///
/// let workday = Workday {
/// id: 1,
/// date: Local::now().date_naive(),
/// start: Local::now().naive_local(),
/// end: Some(Local::now().naive_local()),
/// };
/// let pauses: Vec<Pause> = vec![];
///
/// let intervals = calculate_work_intervals(&workday, &pauses);
/// let (filtered, info) = filter_short_intervals(&intervals, 30);
///
/// if let Some(info) = info {
/// println!("Filtered {} short intervals", info.count);
/// }
/// ```
/// Process daily work report data using pre-calculated intervals.
///
/// This function handles the data processing for daily work reports, calculating
/// productivity metrics and work durations. It leverages the centralized `Productivity`
/// module for consistent calculations across the application.
///
/// ## Calculation Method
///
/// The function uses two different approaches for different metrics:
/// - **Filtered Duration**: Summed directly from provided intervals (for display purposes)
/// - **Productivity**: Calculated using the comprehensive `Productivity::calculate_productivity()`
/// method which properly handles all pause types, breaks, and overlaps
///
/// This separation allows for interval-based filtering (for clean reports) while maintaining
/// accurate productivity calculations that account for all time categories.
///
/// ## Data Consistency
///
/// By using `Productivity::new()`, this function automatically:
/// - Loads the same data used throughout the application
/// - Applies consistent calculation logic
/// - Handles all edge cases and data integrity issues
///
/// # Arguments
///
/// * `workday` - The workday record containing start/end times
/// * `intervals` - Pre-calculated and optionally filtered work intervals for duration calculation
///
/// # Returns
///
/// Returns a tuple containing:
/// - **Filtered Duration**: Sum of provided work intervals (may exclude short intervals)
/// - **Productivity**: Comprehensive productivity percentage using centralized calculation
///
/// # Examples
///
/// ```rust,no_run
/// # fn f() -> anyhow::Result<()> {
/// use kasl::libs::report::{report_with_intervals, WorkInterval};
/// use kasl::libs::formatter::format_duration;
/// use kasl::db::workdays::Workday;
/// use chrono::Local;
///
/// let workday = Workday {
/// id: 1,
/// date: Local::now().date_naive(),
/// start: Local::now().naive_local(),
/// end: Some(Local::now().naive_local()),
/// };
/// let filtered_intervals: Vec<WorkInterval> = vec![];
///
/// let (duration, productivity) = report_with_intervals(&workday, &filtered_intervals)?;
/// println!("Work time: {}, Productivity: {:.1}%", format_duration(&duration), productivity);
/// # Ok(())
/// # }
/// ```