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
use getset::{Getters, MutGetters, Setters};
use serde_derive::{Deserialize, Serialize};
use std::collections::BTreeMap;
use strum_macros::EnumString;
use tabled::{
    builder::Builder,
    settings::{object::Columns, Alignment, Modify, Padding, Panel, Settings, Style},
};

use typed_builder::TypedBuilder;

use crate::{
    ActivityGroup, ActivityItem, ActivityKind, PaceDateTime, PaceDuration, TimeRangeOptions,
};

/// The kind of review format
/// Default: `console`
///
/// Options: `console`, `html`, `markdown`, `plain-text`
#[derive(Debug, Deserialize, Serialize, Clone, Copy, Default, EnumString, PartialEq, Eq)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum ReviewFormatKind {
    #[default]
    Console,
    Json,
    Html,
    Csv,
    #[cfg_attr(feature = "clap", clap(alias("md")))]
    #[serde(rename = "md")]
    Markdown,
    #[cfg_attr(feature = "clap", clap(alias("txt")))]
    #[serde(rename = "txt")]
    PlainText,
}

/// Represents a category for summarizing activities.
// We use a string to allow for user-defined categories for now,
// but we may want to change this to an enum in the future.
pub type SummaryCategories = (String, String);

pub type SummaryGroupByCategory = BTreeMap<SummaryCategories, SummaryActivityGroup>;

/// Represents a summary of activities and insights for a specified review period.
#[derive(
    Debug, TypedBuilder, Serialize, Getters, Setters, MutGetters, Clone, Eq, PartialEq, Default,
)]
#[getset(get = "pub", get_mut = "pub", set = "pub")]
pub struct ReviewSummary {
    /// The time range of the review period.
    time_range: TimeRangeOptions,

    /// Total time spent on all activities within the review period.
    total_time_spent: PaceDuration,

    /// Total time spent on intermissions within the review period.
    total_break_duration: PaceDuration,

    /// Summary of activities grouped by a category or another relevant identifier.
    summary_groups_by_category: SummaryGroupByCategory,
    // TODO: Highlights extracted from the review data, offering insights into user productivity.
    // highlights: Highlights,

    // TODO: Suggestions for the user based on the review, aimed at improving productivity or time management.
    // suggestions: Vec<String>,
}

impl ReviewSummary {
    #[must_use]
    pub fn new(
        time_range: TimeRangeOptions,
        summary_groups_by_category: SummaryGroupByCategory,
    ) -> Self {
        let total_time_spent = PaceDuration::from_seconds(
            summary_groups_by_category
                .values()
                .map(|group| group.total_duration().as_secs())
                .sum(),
        );

        let total_break_duration = PaceDuration::from_seconds(
            summary_groups_by_category
                .values()
                .map(|group| group.total_break_duration().as_secs())
                .sum(),
        );

        Self {
            time_range,
            total_time_spent,
            total_break_duration,
            summary_groups_by_category,
        }
    }
}

// TODO!: Refine the display of the review summary
impl std::fmt::Display for ReviewSummary {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut builder = Builder::new();

        builder.push_record(vec![
            "Category",
            "Description",
            "Duration (Sessions)",
            "Breaks (Amount)",
        ]);

        for ((category, subcategory), summary_group) in &self.summary_groups_by_category {
            builder.push_record(vec![
                category,
                "",
                &summary_group.total_duration().to_string(),
                &summary_group.total_break_duration().to_string(),
            ]);

            for (description, activity_group) in summary_group.activity_groups_by_description() {
                builder.push_record(vec![
                    subcategory,
                    description,
                    format!(
                        "{} ({})",
                        &activity_group.adjusted_duration().to_string(),
                        &activity_group.activity_sessions().len()
                    )
                    .as_str(),
                    format!(
                        "{} ({})",
                        &activity_group.intermission_duration().to_string(),
                        &activity_group.intermission_count().to_string()
                    )
                    .as_str(),
                ]);
            }
        }

        builder.push_record(vec![
            "Total",
            "",
            &self.total_time_spent.to_string(),
            &self.total_break_duration.to_string(),
        ]);

        let table_config = Settings::default()
            .with(Panel::header(format!(
                "Your activity insights for the period:\n\n{}",
                self.time_range
            )))
            .with(Padding::new(1, 1, 0, 0))
            .with(Style::modern_rounded())
            .with(Modify::new(Columns::new(2..)).with(Alignment::right()))
            .with(Modify::new(Columns::new(0..=1)).with(Alignment::center()));

        let table = builder.build().with(table_config).to_string();
        write!(f, "{table}")?;

        Ok(())
    }
}

/// A group of activities for a summary category.
#[derive(
    Debug, TypedBuilder, Serialize, Getters, Setters, MutGetters, Clone, Eq, PartialEq, Default,
)]
#[getset(get = "pub")]
pub struct SummaryActivityGroup {
    /// The total time spent on all activities within the group.
    total_duration: PaceDuration,

    /// The total time spent on breaks within the group.
    total_break_duration: PaceDuration,

    /// The total amount of breaks within the group.
    total_break_count: usize,

    /// The groups of activities for a summary category
    activity_groups_by_description: BTreeMap<String, ActivityGroup>,
}

impl SummaryActivityGroup {
    #[must_use]
    pub fn with_activity_group(activity_group: ActivityGroup) -> Self {
        Self {
            total_break_count: *activity_group.intermission_count(),
            total_break_duration: *activity_group.intermission_duration(),
            total_duration: *activity_group.adjusted_duration(),
            activity_groups_by_description: BTreeMap::from([(
                activity_group.description().to_owned(),
                activity_group,
            )]),
        }
    }

    /// Add an activity group to the summary group.
    pub fn add_activity_group(&mut self, activity_group: ActivityGroup) {
        self.total_duration += *activity_group.adjusted_duration();

        self.total_break_duration += *activity_group.intermission_duration();

        _ = self
            .activity_groups_by_description
            .entry(activity_group.description().to_owned())
            .or_insert(activity_group);
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.activity_groups_by_description.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.activity_groups_by_description.is_empty()
    }
}

/// Highlights from the review period, providing quick insights into key metrics.
#[derive(
    Debug, TypedBuilder, Serialize, Getters, Setters, MutGetters, Clone, Eq, PartialEq, Default,
)]
#[getset(get = "pub", get_mut = "pub", set = "pub")]
pub struct Highlights {
    /// The day with the highest productive hours.
    pub most_productive_day: PaceDateTime,

    /// The kind of activity most frequently logged.
    pub most_frequent_activity_kind: ActivityKind,

    /// The category or activity where the most time was spent.
    pub most_time_spent_on: ActivityItem,
}