kasl-cli 1.0.2

Work activity tracker CLI: automatic workday and break detection, task management with Jira/GitLab integration, productivity reports and exports
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
//! Task management command.
//!
//! Provides comprehensive task management functionality for creating, editing, deleting, and organizing tasks.
//!
//! ## Features
//!
//! - **CRUD Operations**: Create, read, update, and delete individual tasks
//! - **Batch Operations**: Mass editing and deletion of multiple tasks
//! - **External Integration**: Import tasks from GitLab commits and Jira issues
//! - **Advanced Filtering**: View tasks by date, completion status, tags, or IDs
//! - **Template System**: Create tasks from predefined templates
//!
//! ## Usage
//!
//! ```bash
//! # Create a task interactively, or with values up front
//! kasl task
//! kasl task add --name "Review code" --comment "Check PR #123"
//!
//! # List tasks with different filters
//! kasl task list                      # Today's tasks
//! kasl task list --all                # Every task
//! kasl task list --tag urgent         # Tasks carrying a tag
//! kasl task show 42                   # Specific tasks by id
//!
//! # Edit and remove
//! kasl task edit 42                   # Edit one task
//! kasl task edit                      # Pick several interactively
//! kasl task remove 1 2 3
//! kasl task remove --today
//!
//! # Import from external services
//! kasl task find                      # Find tasks from GitLab/Jira
//! kasl task add --template "bug-fix"  # Create from template
//! ```

use crate::{
    api::{gitlab::GitLab, jira::Jira},
    db::tasks::Tasks,
    db::templates::Templates,
    libs::{
        config::Config,
        messages::Message,
        prompt::{ensure_interactive, is_interactive},
        stdin_drain::drain_available_stdin_lines,
        task::{Task, TaskFilter, collapse_whitespace, is_ignored_name, normalize_task_name},
        view::View,
    },
    msg_error, msg_info, msg_print, msg_success, msg_warning,
};
use anyhow::Result;
use chrono::Local;
use clap::{Args, Subcommand};
use dialoguer::{Confirm, Input, MultiSelect, Select, theme::ColorfulTheme};
use indicatif::{ProgressBar, ProgressStyle};
use std::collections::{HashMap, HashSet};
use std::time::Duration;

/// Enumeration for identifying task suggestion sources.
///
/// This enum helps distinguish between different sources of task suggestions
/// during the interactive task finding process, allowing for appropriate
/// handling and user feedback for each source type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum TaskSource {
    /// Previously created but incomplete local tasks
    Incomplete,
    /// Commits from GitLab repositories for the current day
    Gitlab,
    /// Completed issues from Jira for the current day
    Jira,
}

/// Candidate discovered from a single source before UI presentation.
#[derive(Debug, Clone)]
struct DiscoveryItem {
    source: TaskSource,
    task: Task,
    /// Short GitLab commit SHA when available (display only)
    short_sha: Option<String>,
}

impl TaskSource {
    /// Lower value = higher priority when deduplicating by normalized name.
    fn priority(self) -> u8 {
        match self {
            TaskSource::Incomplete => 0,
            TaskSource::Jira => 1,
            TaskSource::Gitlab => 2,
        }
    }
}

fn format_discovery_item(item: &DiscoveryItem) -> String {
    match item.source {
        TaskSource::Incomplete => {
            format!("{}{}%", item.task.name, item.task.completeness.unwrap_or(0))
        }
        TaskSource::Jira => format!("{}", item.task.name),
        TaskSource::Gitlab => match &item.short_sha {
            Some(sha) => format!("{} ({})", item.task.name, sha),
            None => format!("{}", item.task.name),
        },
    }
}

/// Keeps one item per normalized name, preferring Incomplete > Jira > GitLab.
fn dedup_discovery_items(items: Vec<DiscoveryItem>) -> Vec<DiscoveryItem> {
    let mut best: HashMap<String, DiscoveryItem> = HashMap::new();

    for item in items {
        let key = normalize_task_name(&item.task.name);
        match best.get(&key) {
            Some(existing) if existing.source.priority() <= item.source.priority() => {}
            _ => {
                best.insert(key, item);
            }
        }
    }

    let mut result: Vec<DiscoveryItem> = best.into_values().collect();
    result.sort_by(|a, b| a.source.priority().cmp(&b.source.priority()).then_with(|| a.task.name.cmp(&b.task.name)));
    result
}

/// Command-line arguments for task management.
///
/// Task operations are subcommands (`add`, `list`, `show`, `edit`, `remove`,
/// `find`). Running `kasl task` with no subcommand creates a task
/// interactively, which is the most frequent daily action.
#[derive(Debug, Args)]
pub struct TaskArgs {
    #[command(subcommand)]
    command: Option<TaskCommand>,
}

/// Available task operations.
#[derive(Debug, Subcommand)]
enum TaskCommand {
    /// Add a task
    #[command(about = "Add a task")]
    Add(AddArgs),

    /// List tasks
    #[command(about = "List tasks")]
    List(ListArgs),

    /// Show tasks by id
    #[command(about = "Show tasks by id")]
    Show {
        /// Task ids to show
        #[arg(value_name = "ID", required = true, num_args = 1..)]
        id: Vec<i32>,
    },

    /// Edit a task
    #[command(about = "Edit a task by id, or several interactively")]
    Edit {
        /// Task id to edit; omit to pick several interactively
        #[arg(value_name = "ID")]
        id: Option<i32>,
    },

    /// Remove tasks
    #[command(about = "Remove tasks by id, or all of today's")]
    Remove(RemoveArgs),

    /// Find incomplete and external tasks to import
    #[command(about = "Find incomplete tasks and import from GitLab/Jira")]
    Find,
}

/// Arguments for creating a task.
#[derive(Debug, Args, Default)]
pub struct AddArgs {
    /// Task name
    #[arg(short, long)]
    name: Option<String>,

    /// Task comment or description
    #[arg(long)]
    comment: Option<String>,

    /// Completion percentage (0-100)
    #[arg(short, long)]
    completeness: Option<i32>,

    /// Comma-separated tags to assign
    #[arg(long)]
    tags: Option<String>,

    /// Create from a named template
    #[arg(long, short = 't')]
    template: Option<String>,

    /// Pick a template interactively
    #[arg(long, short = 'l')]
    from_template: bool,
}

/// Arguments for listing tasks.
#[derive(Debug, Args)]
pub struct ListArgs {
    /// List tasks from every date, not just today
    #[arg(short, long)]
    all: bool,

    /// Only tasks carrying this tag
    #[arg(long)]
    tag: Option<String>,
}

/// Arguments for removing tasks.
#[derive(Debug, Args)]
pub struct RemoveArgs {
    /// Task ids to remove
    #[arg(value_name = "ID", num_args = 1..)]
    id: Vec<i32>,

    /// Remove every task recorded for today
    #[arg(long)]
    today: bool,

    /// Remove without asking for confirmation
    #[arg(long, short = 'y')]
    yes: bool,
}

/// Main entry point for the comprehensive task management command.
///
/// This function serves as a large dispatcher that handles the various task management
/// operations based on provided command-line flags. It supports everything from simple
/// task creation to complex batch operations and external service integrations.
///
/// ## Operation Modes
///
/// The function handles these primary modes:
///
/// 1. **Deletion Operations**: Remove tasks individually or in bulk
/// 2. **Editing Operations**: Modify existing tasks individually or in batches
/// 3. **Template Operations**: Create tasks from predefined templates
/// 4. **Display Operations**: Show tasks with various filtering options
/// 5. **Discovery Operations**: Find and import tasks from multiple sources
/// 6. **Creation Operations**: Create new tasks manually or interactively
///
/// ## External Integrations
///
/// When find mode is activated, the function integrates with:
/// - **GitLab API**: Fetches today's commits as potential completed tasks
/// - **Jira API**: Retrieves completed issues for the current day
/// - **Local Database**: Finds incomplete tasks that can be continued
///
/// ## Safety Features
///
/// Destructive operations include multiple safety measures:
/// - Preview of changes before applying
/// - Multiple confirmation prompts for bulk operations
/// - Detailed information about affected items
/// - Option to cancel operations at multiple points
///
/// # Arguments
///
/// * `task_args` - Parsed command-line arguments specifying the operation to perform
///
/// # Returns
///
/// Returns `Ok(())` on successful operation completion, or an error if the
/// requested operation fails due to validation, database, or network issues.
///
/// # Examples
///
/// ```bash
/// # Create a simple task
/// kasl task --name "Review pull request" --completeness 0
///
/// # Create task with tags
/// kasl task --name "Fix login bug" --tags "urgent,backend,bug"
///
/// # Find and import tasks from external sources
/// kasl task --find
///
/// # Show all tasks with specific tag
/// kasl task --show --tag urgent
///
/// # Edit multiple tasks interactively
/// kasl task --edit-interactive
///
/// # Create task from template
/// kasl task --template daily-standup
///
/// # Delete specific tasks (with confirmation)
/// kasl task --delete 1 2 3
/// ```
pub async fn cmd(task_args: TaskArgs) -> Result<()> {
    let date = Local::now();

    match task_args.command {
        Some(TaskCommand::Add(args)) => {
            // Template creation is a form of adding, so it lives here too.
            if let Some(template_name) = args.template {
                return handle_create_from_template(template_name).await;
            }
            if args.from_template {
                return handle_create_from_template_interactive().await;
            }
            handle_task_creation(args).await
        }
        Some(TaskCommand::List(args)) => {
            let filter = if args.all {
                TaskFilter::All
            } else if let Some(tag) = args.tag {
                TaskFilter::ByTag(tag)
            } else {
                TaskFilter::Date(date.date_naive())
            };
            show_tasks(filter)
        }
        Some(TaskCommand::Show { id }) => show_tasks(TaskFilter::ByIds(id)),
        Some(TaskCommand::Edit { id }) => match id {
            Some(id) => handle_edit_by_id(id).await,
            None => handle_edit_interactive().await,
        },
        Some(TaskCommand::Remove(args)) => {
            if args.today {
                handle_delete_today(args.yes).await
            } else if args.id.is_empty() {
                msg_error!(Message::NoTaskIdsProvided);
                Ok(())
            } else {
                handle_delete_by_ids(args.id, args.yes).await
            }
        }
        Some(TaskCommand::Find) => handle_task_discovery(date).await,
        // Bare `kasl task` creates a task interactively - the daily entry point.
        None => handle_task_creation(AddArgs::default()).await,
    }
}

/// Fetches and renders tasks for the given filter.
fn show_tasks(filter: TaskFilter) -> Result<()> {
    let tasks = Tasks::new()?.fetch(filter)?;
    if tasks.is_empty() {
        msg_error!(Message::TaskNotFound);
        return Ok(());
    }
    View::tasks(&tasks)?;
    Ok(())
}

/// Handles intelligent task discovery from multiple sources.
///
/// Aggregates incomplete local tasks, today's GitLab commits, and completed Jira
/// issues into a single filtered MultiSelect. Shows a spinner while fetching,
/// deduplicates near-identical names, and prioritizes incomplete tasks above
/// external imports.
///
/// # Arguments
///
/// * `date` - Current date/time for filtering today's external content
async fn handle_task_discovery(date: chrono::DateTime<Local>) -> Result<()> {
    // Discovery ends in a MultiSelect of what to import.
    ensure_interactive("`kasl task find` is interactive and needs a terminal")?;

    let date_naive = date.date_naive();
    let mut config = Config::read()?;
    let gitlab_config = config.gitlab.clone();
    let jira_config = config.jira.clone();
    let ignore_names = config.effective_ignore_names();

    let spinner = ProgressBar::new_spinner();
    spinner.set_style(
        ProgressStyle::with_template("{spinner:.cyan} {msg}")
            .unwrap_or_else(|_| ProgressStyle::default_spinner())
            .tick_strings(&["", "", "", "", "", "", "", "", "", ""]),
    );
    spinner.enable_steady_tick(Duration::from_millis(80));
    spinner.set_message(Message::TasksDiscoverySearchingIncomplete.to_string());

    let incomplete_tasks = Tasks::new()?.fetch(TaskFilter::Incomplete)?;
    let today_tasks = Tasks::new()?.fetch(TaskFilter::Date(date_naive))?;
    let today_names: HashSet<String> = today_tasks.iter().map(|t| normalize_task_name(&t.name)).collect();

    spinner.set_message(Message::TasksDiscoveryFetchingExternal.to_string());

    let (commits_result, jira_result) = tokio::join!(
        async {
            match gitlab_config {
                Some(cfg) => GitLab::new(&cfg).get_today_commits().await,
                None => Ok(Vec::new()),
            }
        },
        async {
            match jira_config {
                Some(cfg) => {
                    let mut jira = Jira::new(&cfg);
                    jira.get_completed_issues(&date_naive).await
                }
                None => Ok(Vec::new()),
            }
        },
    );

    spinner.finish_and_clear();

    let commits = match commits_result {
        Ok(c) => c,
        Err(e) => {
            msg_warning!(Message::GitlabFetchFailed(e.to_string()));
            Vec::new()
        }
    };
    let jira_issues = match jira_result {
        Ok(issues) => issues,
        Err(e) => {
            msg_warning!(Message::JiraFetchFailed(e.to_string()));
            Vec::new()
        }
    };

    let mut candidates: Vec<DiscoveryItem> = Vec::new();

    for task in incomplete_tasks {
        if is_ignored_name(&task.name, &ignore_names) {
            continue;
        }
        if today_names.contains(&normalize_task_name(&task.name)) {
            continue;
        }
        candidates.push(DiscoveryItem {
            source: TaskSource::Incomplete,
            task,
            short_sha: None,
        });
    }

    for issue in jira_issues {
        let name = format!("{} {}", issue.key, issue.fields.summary);
        if is_ignored_name(&name, &ignore_names) {
            continue;
        }
        if today_names.contains(&normalize_task_name(&name)) {
            continue;
        }
        candidates.push(DiscoveryItem {
            source: TaskSource::Jira,
            task: Task::new(&name, "", Some(100)),
            short_sha: None,
        });
    }

    for commit in commits {
        if is_ignored_name(&commit.message, &ignore_names) {
            continue;
        }
        if today_names.contains(&normalize_task_name(&commit.message)) {
            continue;
        }
        let short_sha = if commit.sha.len() >= 7 {
            Some(commit.sha[..7].to_string())
        } else if commit.sha.is_empty() {
            None
        } else {
            Some(commit.sha.clone())
        };
        candidates.push(DiscoveryItem {
            source: TaskSource::Gitlab,
            task: Task::new(&commit.message, "", Some(100)),
            short_sha,
        });
    }

    let items = dedup_discovery_items(candidates);

    if items.is_empty() {
        msg_error!(Message::TasksNotFoundSad);
        return Ok(());
    }

    let incomplete_count = items.iter().filter(|i| i.source == TaskSource::Incomplete).count();
    let jira_count = items.iter().filter(|i| i.source == TaskSource::Jira).count();
    let gitlab_count = items.iter().filter(|i| i.source == TaskSource::Gitlab).count();

    msg_print!(
        Message::TasksDiscoverySummary {
            incomplete: incomplete_count,
            jira: jira_count,
            gitlab: gitlab_count,
        },
        true
    );

    // Build one MultiSelect: incomplete first, optional separator, then the rest.
    let mut labels: Vec<String> = Vec::new();
    let mut index_map: Vec<Option<usize>> = Vec::new();

    for (idx, item) in items.iter().enumerate() {
        if item.source == TaskSource::Incomplete {
            labels.push(format_discovery_item(item));
            index_map.push(Some(idx));
        }
    }

    let has_rest = items.iter().any(|i| i.source != TaskSource::Incomplete);
    if incomplete_count > 0 && has_rest {
        labels.push(Message::TasksDiscoverySeparator.to_string());
        index_map.push(None);
    }

    for (idx, item) in items.iter().enumerate() {
        if item.source != TaskSource::Incomplete {
            labels.push(format_discovery_item(item));
            index_map.push(Some(idx));
        }
    }

    let selected = MultiSelect::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::PromptSelectTasksToImport.to_string())
        .items(&labels)
        .interact()
        .unwrap_or_default();

    for sel in selected {
        let Some(item_idx) = index_map.get(sel).copied().flatten() else {
            continue; // separator or out of range
        };
        let Some(item) = items.get(item_idx) else {
            continue;
        };

        let mut task = item.task.clone();

        if item.source == TaskSource::Incomplete {
            msg_print!(Message::SelectingTask(task.name.clone()));

            if task.task_id.is_none() || task.task_id.is_some_and(|id| id == 0) {
                task.task_id = task.id;
            }

            let default_completeness = (task.completeness.unwrap_or(0) + 1).min(100);
            task.completeness = Some(
                Input::with_theme(&ColorfulTheme::default())
                    .allow_empty(true)
                    .with_prompt(Message::PromptTaskCompleteness.to_string())
                    .default(default_completeness)
                    .interact_text()
                    .unwrap(),
            );
        }

        let _ = Tasks::new()?.insert(&task);
    }

    // Optional: add selected discovery items to the persistent ignore list.
    let ignore_selected = MultiSelect::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::PromptSelectTasksToIgnore.to_string())
        .items(&labels)
        .interact()
        .unwrap_or_default();

    if !ignore_selected.is_empty() {
        let mut names_to_ignore = Vec::new();
        for sel in ignore_selected {
            let Some(item_idx) = index_map.get(sel).copied().flatten() else {
                continue;
            };
            if let Some(item) = items.get(item_idx) {
                names_to_ignore.push(item.task.name.clone());
            }
        }

        if !names_to_ignore.is_empty() {
            let added = config.add_ignore_names(&names_to_ignore)?;
            if added > 0 {
                msg_success!(Message::TaskDiscoveryIgnoreNamesAdded(added));
            }
        }
    }

    Ok(())
}

/// Prompts for a task name and absorbs leftover multi-line paste from stdin.
fn prompt_task_name_interactive() -> String {
    let raw = crate::libs::stdin_drain::read_pastable_line(&Message::PromptTaskName.to_string()).unwrap_or_default();
    let name = collapse_whitespace(&raw);
    if raw.lines().filter(|l| !l.trim().is_empty()).count() > 1 {
        msg_info!(Message::TaskNameMergedFromPaste);
    }
    if !name.is_empty() {
        println!("{}", name);
    }
    name
}

/// Returns true for bare issue keys like `PROJ-42` (typical first line of a ticket paste).
fn looks_like_issue_key(name: &str) -> bool {
    let name = name.trim();
    if name.is_empty() || name.chars().any(|c| c.is_whitespace()) {
        return false;
    }
    let Some((prefix, rest)) = name.split_once('-') else {
        return false;
    };
    !prefix.is_empty() && prefix.chars().all(|c| c.is_ascii_alphanumeric()) && !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit())
}

/// Handles manual task creation with interactive prompts.
///
/// This function manages the standard task creation workflow, collecting
/// task information either from command-line arguments or interactive prompts.
/// It also handles tag assignment and provides immediate feedback about
/// the created task.
///
/// # Arguments
///
/// * `task_args` - Command-line arguments containing optional task information
async fn handle_task_creation(task_args: AddArgs) -> Result<()> {
    // Anything not supplied on the command line is asked for, so a missing name
    // means prompting - which must not happen with no one at the terminal.
    if task_args.name.is_none() {
        ensure_interactive("task name is required; pass --name outside an interactive terminal")?;
    }

    // Collect task information (from args or interactive prompts)
    let name_from_args = task_args.name.is_some();
    let comment_from_args = task_args.comment.is_some();

    let mut name = match task_args.name {
        Some(n) => collapse_whitespace(&n),
        None => prompt_task_name_interactive(),
    };

    // Only the name is required. With a name supplied but no comment or
    // completeness, the remaining prompts are skipped rather than attempted:
    // `task add --name X` has to work from a script, where there is nobody to
    // answer them.
    let interactive = is_interactive();

    let mut comment = match task_args.comment {
        Some(c) => collapse_whitespace(&c),
        None if !interactive => String::new(),
        None => {
            let raw: String = Input::with_theme(&ColorfulTheme::default())
                .allow_empty(true)
                .with_prompt(Message::PromptTaskComment.to_string())
                .interact_text()
                .unwrap();
            collapse_whitespace(&raw)
        }
    };

    // Fallback: multi-line paste often lands as name=KEY + comment=summary when stdin
    // drain is unavailable (native console). Rejoin and ask for a real comment again.
    if interactive && !name_from_args && !comment_from_args && looks_like_issue_key(&name) && !comment.is_empty() {
        name = collapse_whitespace(&format!("{} {}", name, comment));
        msg_info!(Message::TaskNameMergedFromPaste);
        let raw: String = Input::with_theme(&ColorfulTheme::default())
            .allow_empty(true)
            .with_prompt(Message::PromptTaskComment.to_string())
            .interact_text()
            .unwrap();
        comment = collapse_whitespace(&raw);
    }

    // Discard any remaining paste leftovers before completeness.
    let _ = drain_available_stdin_lines();

    let completeness = match task_args.completeness {
        Some(c) => c,
        None if !interactive => 100,
        None => Input::with_theme(&ColorfulTheme::default())
            .allow_empty(true)
            .with_prompt(Message::PromptTaskCompleteness.to_string())
            .default(100)
            .interact_text()
            .unwrap(),
    };

    // Create and insert the task
    let task = Task::new(&name, &comment, Some(completeness));
    let new_task = Tasks::new()?.insert(&task)?.update_id()?.get()?;
    View::tasks(&new_task)?;

    // Handle tag assignment if provided
    if let Some(tags_str) = task_args.tags {
        let tag_names: Vec<String> = tags_str.split(',').map(|s| s.trim().to_string()).collect();

        let mut tags_db = crate::db::tags::Tags::new()?;
        let tag_ids = tags_db.get_or_create_tags(&tag_names)?;

        if let Some(task_id) = new_task[0].id {
            tags_db.set_task_tags(task_id, &tag_ids)?;
            msg_info!(Message::TagsAddedToTask(tag_names.join(", ")));
        }
    }

    Ok(())
}

/// Handles deletion of multiple tasks by their IDs.
///
/// This function provides a safe deletion interface with preview and confirmation
/// for removing multiple tasks simultaneously. It includes validation to ensure
/// all specified task IDs exist before performing any deletions.
///
/// ## Safety Features
///
/// - Validates all task IDs exist before deletion
/// - Shows preview of tasks to be deleted
/// - Requires explicit user confirmation
/// - Provides clear feedback about deletion results
/// - Handles non-existent IDs gracefully
///
/// # Arguments
///
/// * `ids` - Vector of task IDs to delete
async fn handle_delete_by_ids(ids: Vec<i32>, assume_yes: bool) -> Result<()> {
    if ids.is_empty() {
        msg_error!(Message::NoTaskIdsProvided);
        return Ok(());
    }

    let mut tasks_db = Tasks::new()?;

    // Fetch tasks to show preview of what will be deleted
    let tasks = tasks_db.fetch(TaskFilter::ByIds(ids.clone()))?;

    if tasks.is_empty() {
        msg_error!(Message::TasksNotFoundForIds(ids));
        return Ok(());
    }

    // Show preview of tasks to be deleted
    msg_print!(Message::TasksToBeDeleted, true);
    View::tasks(&tasks)?;

    if !assume_yes {
        // Never block on a prompt when there is no one to answer it.
        ensure_interactive("refusing to remove tasks without --yes outside an interactive terminal")?;

        // Request confirmation based on number of tasks
        let prompt = if ids.len() == 1 {
            Message::ConfirmDeleteTask
        } else {
            Message::ConfirmDeleteTasks(ids.len())
        };

        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt(prompt.to_string())
            .default(false)
            .interact()?;

        if !confirmed {
            msg_info!(Message::OperationCancelled);
            return Ok(());
        }
    }

    let deleted_count = tasks_db.delete_many(&ids)?;
    msg_success!(Message::TasksDeletedCount(deleted_count));

    Ok(())
}

/// Handles deletion of all tasks for today.
///
/// This is a dangerous operation that removes all tasks created today.
/// It includes multiple confirmation steps and detailed previews to
/// prevent accidental data loss.
///
/// ## Safety Measures
///
/// - Shows complete list of tasks to be deleted
/// - Requires two separate confirmations
/// - Uses clear warning language
/// - Defaults to "No" for all confirmations
/// - Provides escape points throughout the process
async fn handle_delete_today(assume_yes: bool) -> Result<()> {
    let mut tasks_db = Tasks::new()?;
    let today = Local::now().date_naive();

    // Fetch today's tasks
    let tasks = tasks_db.fetch(TaskFilter::Date(today))?;

    if tasks.is_empty() {
        msg_info!(Message::NoTasksForToday);
        return Ok(());
    }

    // Show complete preview of tasks to be deleted
    msg_print!(Message::TasksToBeDeleted, true);
    View::tasks(&tasks)?;

    if !assume_yes {
        // Never block on a prompt when there is no one to answer it.
        ensure_interactive("refusing to remove today's tasks without --yes outside an interactive terminal")?;

        // First confirmation with task count
        let first_confirm = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt(Message::ConfirmDeleteAllTodayTasks(tasks.len()).to_string())
            .default(false)
            .interact()?;

        if !first_confirm {
            msg_info!(Message::OperationCancelled);
            return Ok(());
        }

        // Second confirmation with stronger warning
        let second_confirm = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt(Message::ConfirmDeleteAllTodayTasksFinal.to_string())
            .default(false)
            .interact()?;

        if !second_confirm {
            msg_info!(Message::OperationCancelled);
            return Ok(());
        }
    }

    let ids: Vec<i32> = tasks.iter().filter_map(|t| t.id).collect();
    let deleted_count = tasks_db.delete_many(&ids)?;
    msg_success!(Message::TasksDeletedCount(deleted_count));

    Ok(())
}

/// Handles editing a single task by its ID.
///
/// Provides an interactive editing interface for modifying task properties
/// including name, comment, and completion status. Includes preview of
/// changes before applying them to the database.
///
/// # Arguments
///
/// * `id` - Database ID of the task to edit
async fn handle_edit_by_id(id: i32) -> Result<()> {
    // Editing prompts for each field with the current value as default.
    ensure_interactive("`kasl task edit` is interactive and needs a terminal")?;

    let mut tasks_db = Tasks::new()?;

    // Fetch the task to edit
    let task = match tasks_db.get_by_id(id)? {
        Some(task) => task,
        None => {
            msg_error!(Message::TaskNotFoundWithId(id));
            return Ok(());
        }
    };

    // Show current task state
    msg_print!(Message::CurrentTaskState, true);
    View::tasks(std::slice::from_ref(&task))?;

    // Interactive editing
    let edited_task = edit_task_interactive(&task)?;

    // Check if anything actually changed
    if edited_task.name == task.name && edited_task.comment == task.comment && edited_task.completeness == task.completeness {
        msg_info!(Message::NoChangesDetected);
        return Ok(());
    }

    // Show preview of changes
    msg_print!(Message::TaskEditPreview, true);
    View::tasks(std::slice::from_ref(&edited_task))?;

    // Confirm changes
    let confirmed = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::ConfirmTaskUpdate.to_string())
        .default(true)
        .interact()?;

    if confirmed {
        let mut task_to_update = task;
        task_to_update.update_from(&edited_task);
        tasks_db.update(&task_to_update)?;
        msg_success!(Message::TaskUpdated);
    } else {
        msg_info!(Message::OperationCancelled);
    }

    Ok(())
}

/// Handles interactive batch editing of multiple tasks.
///
/// Presents a selection interface for choosing multiple tasks from today's
/// list, then provides individual editing interfaces for each selected task.
/// This is efficient for updating multiple related tasks in sequence.
async fn handle_edit_interactive() -> Result<()> {
    // Picks tasks from a MultiSelect, then prompts per task.
    ensure_interactive("`kasl task edit` without an id is interactive and needs a terminal")?;

    let mut tasks_db = Tasks::new()?;

    // Get today's tasks for selection
    let today = Local::now().date_naive();
    let tasks = tasks_db.fetch(TaskFilter::Date(today))?;

    if tasks.is_empty() {
        msg_info!(Message::NoTasksForToday);
        return Ok(());
    }

    // Create selection list with task descriptions
    let task_descriptions: Vec<String> = tasks
        .iter()
        .map(|t| format!("[{}] {} ({}%)", t.id.unwrap_or(0), t.name, t.completeness.unwrap_or(0)))
        .collect();

    let selections = MultiSelect::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::SelectTasksToEdit.to_string())
        .items(&task_descriptions)
        .interact()?;

    if selections.is_empty() {
        msg_info!(Message::NoTasksSelected);
        return Ok(());
    }

    // Edit each selected task in sequence
    for &index in &selections {
        let task = &tasks[index];

        msg_print!(Message::EditingTask(task.name.clone()), true);
        View::tasks(std::slice::from_ref(task))?;

        let edited_task = edit_task_interactive(task)?;

        // Apply changes if anything was modified
        if edited_task.name != task.name || edited_task.comment != task.comment || edited_task.completeness != task.completeness {
            let mut task_to_update = task.clone();
            task_to_update.update_from(&edited_task);
            tasks_db.update(&task_to_update)?;
            msg_success!(Message::TaskUpdatedWithName(task.name.clone()));
        } else {
            msg_info!(Message::TaskSkippedNoChanges(task.name.clone()));
        }
    }

    msg_success!(Message::TaskEditingCompleted);
    Ok(())
}

/// Interactive task editing helper function.
///
/// Provides a consistent interactive interface for editing task properties.
/// Used by both single and batch editing operations to ensure uniform
/// user experience and validation.
///
/// # Arguments
///
/// * `task` - Original task to edit (used for default values)
///
/// # Returns
///
/// Returns a new Task instance with updated values from user input.
fn edit_task_interactive(task: &Task) -> Result<Task> {
    let name = collapse_whitespace(
        &Input::with_theme(&ColorfulTheme::default())
            .with_prompt(Message::PromptTaskNameEdit.to_string())
            .default(task.name.clone())
            .interact_text()?,
    );

    let comment = collapse_whitespace(
        &Input::with_theme(&ColorfulTheme::default())
            .with_prompt(Message::PromptTaskCommentEdit.to_string())
            .default(task.comment.clone())
            .allow_empty(true)
            .interact_text()?,
    );

    let completeness_range_msg = Message::TaskCompletenessRange.to_string();
    let completeness = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::PromptTaskCompletenessEdit.to_string())
        .default(task.completeness.unwrap_or(100))
        .validate_with(|input: &i32| -> Result<(), &str> {
            if *input >= 0 && *input <= 100 { Ok(()) } else { Err(&completeness_range_msg) }
        })
        .interact_text()?;

    Ok(Task {
        id: task.id,
        task_id: task.task_id,
        timestamp: task.timestamp.clone(),
        name,
        comment,
        completeness: Some(completeness),
        excluded_from_search: task.excluded_from_search,
        tags: vec![], // Tags are preserved separately
    })
}

/// Creates a task from a named template.
///
/// Loads the specified template and allows the user to modify the template
/// values before creating the final task. This streamlines creation of
/// frequently used task types while maintaining flexibility.
///
/// # Arguments
///
/// * `template_name` - Name of the template to use for task creation
async fn handle_create_from_template(template_name: String) -> Result<()> {
    let mut templates_db = Templates::new()?;
    let template = match templates_db.get(&template_name)? {
        Some(t) => t,
        None => {
            msg_error!(Message::TemplateNotFound(template_name));
            return Ok(());
        }
    };

    msg_info!(Message::CreatingTaskFromTemplate(template.name.clone()));

    // Allow modification of template values
    let name = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::PromptTaskName.to_string())
        .default(template.task_name)
        .interact_text()?;

    let comment = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::PromptTaskComment.to_string())
        .default(template.comment)
        .allow_empty(true)
        .interact_text()?;

    let completeness = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::PromptTaskCompleteness.to_string())
        .default(template.completeness)
        .interact_text()?;

    // Create and display the new task
    let task = Task::new(&name, &comment, Some(completeness));
    let new_task = Tasks::new()?.insert(&task)?.update_id()?.get()?;
    View::tasks(&new_task)?;

    Ok(())
}

/// Interactive template selection for task creation.
///
/// Displays available templates in a selection interface, allowing users
/// to choose from existing templates without needing to remember template names.
async fn handle_create_from_template_interactive() -> Result<()> {
    // Template is chosen from a Select.
    ensure_interactive("`--from-template` is interactive; pass --template NAME outside a terminal")?;

    let mut templates_db = Templates::new()?;
    let templates = templates_db.get_all()?;

    if templates.is_empty() {
        msg_info!(Message::NoTemplatesFound);
        msg_info!(Message::CreateTemplateFirst);
        return Ok(());
    }

    let template_options: Vec<String> = templates.iter().map(|t| format!("{} - {}", t.name, t.task_name)).collect();

    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::SelectTemplate.to_string())
        .items(&template_options)
        .interact()?;

    let template = &templates[selection];
    handle_create_from_template(template.name.clone()).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::libs::config::default_ignore_names;

    #[test]
    fn normalize_collapses_whitespace_and_punctuation() {
        assert_eq!(normalize_task_name("New commit"), "new commit");
        assert_eq!(normalize_task_name("New commit "), "new commit");
        assert_eq!(normalize_task_name("New commit."), "new commit");
        assert_eq!(normalize_task_name(" New commit"), "new commit");
        assert_eq!(normalize_task_name("New  commit..."), "new commit");
    }

    #[test]
    fn collapse_whitespace_turns_newlines_into_spaces() {
        let pasted = "PROJ-42\nFix login redirect for OAuth callback\r\n";
        assert_eq!(collapse_whitespace(pasted), "PROJ-42 Fix login redirect for OAuth callback");
        assert_eq!(collapse_whitespace("  spaced   out  "), "spaced out");
    }

    #[test]
    fn looks_like_issue_key_detects_jira_keys() {
        assert!(looks_like_issue_key("PROJ-42"));
        assert!(looks_like_issue_key("ABC-1001"));
        assert!(!looks_like_issue_key("PROJ-42 summary"));
        assert!(!looks_like_issue_key("update alert"));
        assert!(!looks_like_issue_key(""));
    }

    #[test]
    fn default_ignore_filters_merge_and_update_webui_but_not_update_alert() {
        let ignore = default_ignore_names();
        assert!(!ignore.iter().any(|n| normalize_task_name(n) == "update alert"));

        assert!(is_ignored_name("Merge remote-tracking branch 'origin/release/4.39.0' into feature/x", &ignore));
        assert!(is_ignored_name("Merge branch 'main' into feature/x", &ignore));
        assert!(is_ignored_name("update webui", &ignore));
        assert!(is_ignored_name("  Update WebUI  ", &ignore));
        assert!(!is_ignored_name("update alert", &ignore));
        assert!(!is_ignored_name("Fix login validation", &ignore));
    }

    #[test]
    fn custom_ignore_list_filters_update_alert() {
        let mut ignore = default_ignore_names();
        ignore.push("update alert".to_string());
        assert!(is_ignored_name("update alert", &ignore));
        assert!(is_ignored_name("Update alert.", &ignore));
    }

    #[test]
    fn dedup_prefers_incomplete_over_jira_over_gitlab() {
        let items = vec![
            DiscoveryItem {
                source: TaskSource::Gitlab,
                task: Task::new("New commit.", "", Some(100)),
                short_sha: Some("abc1234".into()),
            },
            DiscoveryItem {
                source: TaskSource::Jira,
                task: Task::new("New commit", "", Some(100)),
                short_sha: None,
            },
            DiscoveryItem {
                source: TaskSource::Incomplete,
                task: Task::new(" New commit", "", Some(40)),
                short_sha: None,
            },
        ];

        let deduped = dedup_discovery_items(items);
        assert_eq!(deduped.len(), 1);
        assert_eq!(deduped[0].source, TaskSource::Incomplete);
        assert_eq!(deduped[0].task.name, "New commit");
    }
}