ticktickrs 0.1.4

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

use std::env;
use std::process::ExitCode;

use clap::Parser;

use api::{
    AuthHandler, CreateProjectRequest, CreateTaskRequest, TickTickClient, UpdateProjectRequest,
    UpdateTaskRequest,
};
use cli::project::ProjectCommands;
use cli::subtask::SubtaskCommands;
use cli::task::TaskCommands;
use cli::{Cli, Commands};
use config::{Config, TokenStorage};
use constants::{ENV_CLIENT_ID, ENV_CLIENT_SECRET};
use models::{ChecklistItemRequest, Priority, Status};
use output::json::{
    JsonResponse, ProjectData, ProjectListData, SubtaskListData, TaskData, TaskListData,
    VersionData,
};
use output::text;
use output::OutputFormat;
use utils::date_parser::parse_date;

/// Application name
const APP_NAME: &str = env!("CARGO_PKG_NAME");
/// Application version
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");

#[tokio::main]
async fn main() -> ExitCode {
    // Load environment variables from .env file if present
    let _ = dotenvy::dotenv();

    let cli = Cli::parse();

    // Determine output format
    let format = if cli.json {
        OutputFormat::Json
    } else {
        OutputFormat::Text
    };

    // Run the command and handle errors
    let result = run_command(cli.command, format, cli.quiet).await;

    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            if !cli.quiet {
                eprintln!("{}", e);
            }
            ExitCode::FAILURE
        }
    }
}

async fn run_command(command: Commands, format: OutputFormat, quiet: bool) -> anyhow::Result<()> {
    match command {
        Commands::Init => cmd_init(format, quiet).await,
        Commands::Reset { force } => cmd_reset(force, format, quiet),
        Commands::Version => cmd_version(format, quiet),
        Commands::Project(cmd) => cmd_project(cmd, format, quiet).await,
        Commands::Task(cmd) => cmd_task(cmd, format, quiet).await,
        Commands::Subtask(cmd) => cmd_subtask(cmd, format, quiet).await,
    }
}

/// Initialize OAuth authentication
async fn cmd_init(format: OutputFormat, quiet: bool) -> anyhow::Result<()> {
    // Check if already initialized
    if TokenStorage::exists()? {
        let message =
            "Already authenticated. Use 'tickrs reset' to clear credentials and re-authenticate.";
        if !quiet {
            output_message(format, message, "ALREADY_INITIALIZED")?;
        }
        return Ok(());
    }

    // Load client credentials from environment
    let client_id = env::var(ENV_CLIENT_ID).map_err(|_| {
        anyhow::anyhow!(
            "Missing {} environment variable. Set it to your TickTick OAuth client ID.",
            ENV_CLIENT_ID
        )
    })?;

    let client_secret = env::var(ENV_CLIENT_SECRET).map_err(|_| {
        anyhow::anyhow!(
            "Missing {} environment variable. Set it to your TickTick OAuth client secret.",
            ENV_CLIENT_SECRET
        )
    })?;

    // Create auth handler and get URL first
    let auth = AuthHandler::new(client_id, client_secret);
    let (auth_url, _) = auth.get_auth_url()?;

    if !quiet && format == OutputFormat::Text {
        println!("Opening browser for TickTick authorization...");
        println!();
        println!("If the browser doesn't open, visit this URL:");
        println!("{}", auth_url);
        println!();
    }

    // Run OAuth flow
    let token = auth.run_oauth_flow().await?;

    // Save token
    TokenStorage::save(&token)?;

    // Initialize config
    let config = Config::default();
    config.save()?;

    let message = "Authentication successful";
    if !quiet {
        output_message(format, message, "SUCCESS")?;
    }

    Ok(())
}

/// Reset configuration and clear stored token
fn cmd_reset(force: bool, format: OutputFormat, quiet: bool) -> anyhow::Result<()> {
    // Check if anything exists to reset
    let token_exists = TokenStorage::exists()?;
    let config_path = Config::config_path()?;
    let config_exists = config_path.exists();

    if !token_exists && !config_exists {
        let message = "Nothing to reset - no configuration or token found";
        if !quiet {
            output_message(format, message, "NOTHING_TO_RESET")?;
        }
        return Ok(());
    }

    // Confirm unless --force is specified
    if !force && format == OutputFormat::Text {
        println!("This will delete your stored credentials and configuration.");
        println!("You will need to re-authenticate with 'tickrs init'.");
        print!("Continue? [y/N] ");
        std::io::Write::flush(&mut std::io::stdout())?;

        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;

        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Aborted.");
            return Ok(());
        }
    }

    // Delete token and config
    if token_exists {
        TokenStorage::delete()?;
    }
    if config_exists {
        Config::delete()?;
    }

    let message = "Configuration and credentials cleared";
    if !quiet {
        output_message(format, message, "SUCCESS")?;
    }

    Ok(())
}

/// Display version information
fn cmd_version(format: OutputFormat, quiet: bool) -> anyhow::Result<()> {
    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let data = VersionData {
                name: APP_NAME.to_string(),
                version: APP_VERSION.to_string(),
            };
            let response = JsonResponse::success(data);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_version(APP_NAME, APP_VERSION));
        }
    }

    Ok(())
}

/// Output a message in the appropriate format
fn output_message(format: OutputFormat, message: &str, code: &str) -> anyhow::Result<()> {
    match format {
        OutputFormat::Json => {
            let response = JsonResponse::success_with_message(serde_json::json!({}), message);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            if code == "SUCCESS" {
                println!("{}", text::format_success(message));
            } else {
                println!("{}", message);
            }
        }
    }
    Ok(())
}

/// Handle project commands
async fn cmd_project(
    cmd: ProjectCommands,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    match cmd {
        ProjectCommands::List => cmd_project_list(format, quiet).await,
        ProjectCommands::Show { id } => cmd_project_show(&id, format, quiet).await,
        ProjectCommands::Use { name_or_id } => cmd_project_use(&name_or_id, format, quiet).await,
        ProjectCommands::Create {
            name,
            color,
            view_mode,
            kind,
        } => cmd_project_create(&name, color, view_mode, kind, format, quiet).await,
        ProjectCommands::Update {
            id,
            name,
            color,
            closed,
        } => cmd_project_update(&id, name, color, closed, format, quiet).await,
        ProjectCommands::Delete { id, force } => {
            cmd_project_delete(&id, force, format, quiet).await
        }
    }
}

/// List all projects
async fn cmd_project_list(format: OutputFormat, quiet: bool) -> anyhow::Result<()> {
    let client = TickTickClient::new()?;
    let projects = client.list_projects().await?;

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let data = ProjectListData { projects };
            let response = JsonResponse::success(data);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_project_list(&projects));
        }
    }

    Ok(())
}

/// Show project details
async fn cmd_project_show(id: &str, format: OutputFormat, quiet: bool) -> anyhow::Result<()> {
    let client = TickTickClient::new()?;
    let project = client.get_project(id).await?;

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let data = ProjectData { project };
            let response = JsonResponse::success(data);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_project_details(&project));
        }
    }

    Ok(())
}

/// Set default project for commands
async fn cmd_project_use(
    name_or_id: &str,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let client = TickTickClient::new()?;
    let projects = client.list_projects().await?;

    // Find project by name or ID
    let project = projects
        .iter()
        .find(|p| p.id == name_or_id || p.name.eq_ignore_ascii_case(name_or_id))
        .ok_or_else(|| anyhow::anyhow!("Project not found: {}", name_or_id))?;

    // Update config with the project ID
    let mut config = Config::load()?;
    config.default_project_id = Some(project.id.clone());
    config.save()?;

    if quiet {
        return Ok(());
    }

    let message = format!("Default project set to '{}'", project.name);
    match format {
        OutputFormat::Json => {
            let data = ProjectData {
                project: project.clone(),
            };
            let response = JsonResponse::success_with_message(data, &message);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_success(&message));
        }
    }

    Ok(())
}

/// Create a new project
async fn cmd_project_create(
    name: &str,
    color: Option<String>,
    view_mode: Option<String>,
    kind: Option<String>,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let client = TickTickClient::new()?;

    let request = CreateProjectRequest {
        name: name.to_string(),
        color,
        view_mode,
        kind,
    };

    let project = client.create_project(&request).await?;

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let data = ProjectData { project };
            let response = JsonResponse::success_with_message(data, "Project created successfully");
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!(
                "{}",
                text::format_success_with_id("Project created", &project.id)
            );
        }
    }

    Ok(())
}

/// Update an existing project
async fn cmd_project_update(
    id: &str,
    name: Option<String>,
    color: Option<String>,
    closed: Option<bool>,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let client = TickTickClient::new()?;

    let request = UpdateProjectRequest {
        name,
        color,
        closed,
        view_mode: None,
    };

    let project = client.update_project(id, &request).await?;

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let data = ProjectData { project };
            let response = JsonResponse::success_with_message(data, "Project updated successfully");
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!(
                "{}",
                text::format_success_with_id("Project updated", &project.id)
            );
        }
    }

    Ok(())
}

/// Delete a project
async fn cmd_project_delete(
    id: &str,
    force: bool,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    // Confirm unless --force is specified
    if !force && format == OutputFormat::Text {
        print!("Delete project '{}'? [y/N] ", id);
        std::io::Write::flush(&mut std::io::stdout())?;

        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;

        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Aborted.");
            return Ok(());
        }
    }

    let client = TickTickClient::new()?;
    client.delete_project(id).await?;

    if quiet {
        return Ok(());
    }

    let message = "Project deleted successfully";
    match format {
        OutputFormat::Json => {
            let response = JsonResponse::success_with_message(serde_json::json!({}), message);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_success(message));
        }
    }

    Ok(())
}

/// Handle task commands
async fn cmd_task(cmd: TaskCommands, format: OutputFormat, quiet: bool) -> anyhow::Result<()> {
    match cmd {
        TaskCommands::List {
            project_id,
            project_name,
            priority,
            tag,
            status,
        } => {
            cmd_task_list(
                project_id,
                project_name,
                priority,
                tag,
                status,
                format,
                quiet,
            )
            .await
        }
        TaskCommands::Show {
            id,
            project_id,
            project_name,
        } => cmd_task_show(&id, project_id, project_name, format, quiet).await,
        TaskCommands::Create {
            title,
            project_id,
            project_name,
            content,
            priority,
            tags,
            date,
            start,
            due,
            all_day,
            timezone,
            items,
        } => {
            cmd_task_create(
                &title,
                project_id,
                project_name,
                content,
                priority,
                tags,
                date,
                start,
                due,
                all_day,
                timezone,
                items,
                format,
                quiet,
            )
            .await
        }
        TaskCommands::Update {
            id,
            project_id,
            project_name,
            title,
            content,
            priority,
            tags,
            date,
            start,
            due,
            all_day,
            timezone,
            items,
        } => {
            cmd_task_update(
                &id,
                project_id,
                project_name,
                title,
                content,
                priority,
                tags,
                date,
                start,
                due,
                all_day,
                timezone,
                items,
                format,
                quiet,
            )
            .await
        }
        TaskCommands::Delete {
            id,
            project_id,
            project_name,
            force,
        } => cmd_task_delete(&id, project_id, project_name, force, format, quiet).await,
        TaskCommands::Complete {
            id,
            project_id,
            project_name,
        } => cmd_task_complete(&id, project_id, project_name, format, quiet).await,
        TaskCommands::Uncomplete {
            id,
            project_id,
            project_name,
        } => cmd_task_uncomplete(&id, project_id, project_name, format, quiet).await,
    }
}

/// Resolve project name to ID by looking up all projects
async fn resolve_project_name(name: &str) -> anyhow::Result<String> {
    let client = TickTickClient::new()?;
    let projects = client.list_projects().await?;
    let project = projects
        .iter()
        .find(|p| p.name.eq_ignore_ascii_case(name))
        .ok_or_else(|| anyhow::anyhow!("Project not found: {}", name))?;
    Ok(project.id.clone())
}

/// Get the project ID from argument, name lookup, or config default
async fn get_project_id(
    project_id: Option<String>,
    project_name: Option<String>,
) -> anyhow::Result<String> {
    match (project_id, project_name) {
        (Some(_), Some(_)) => {
            anyhow::bail!("Cannot specify both --project-id and --project-name")
        }
        (Some(id), None) => Ok(id),
        (None, Some(name)) => resolve_project_name(&name).await,
        (None, None) => {
            let config = Config::load()?;
            config.default_project_id.ok_or_else(|| {
                anyhow::anyhow!(
                    "No project specified. Use --project-id, --project-name, or set a default with 'tickrs project use <name>'"
                )
            })
        }
    }
}

/// List tasks in a project
async fn cmd_task_list(
    project_id: Option<String>,
    project_name: Option<String>,
    priority_filter: Option<Priority>,
    tag_filter: Option<String>,
    status_filter: Option<String>,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let project_id = get_project_id(project_id, project_name).await?;
    let client = TickTickClient::new()?;
    let mut tasks = client.list_tasks(&project_id).await?;

    // Apply filters
    if let Some(priority) = priority_filter {
        tasks.retain(|t| t.priority == priority);
    }

    if let Some(ref tag) = tag_filter {
        let tag_lower = tag.to_lowercase();
        tasks.retain(|t| t.tags.iter().any(|tt| tt.to_lowercase() == tag_lower));
    }

    if let Some(ref status) = status_filter {
        let status_lower = status.to_lowercase();
        match status_lower.as_str() {
            "complete" | "completed" | "done" => {
                tasks.retain(|t| t.status == Status::Complete);
            }
            "incomplete" | "pending" | "open" => {
                tasks.retain(|t| t.status == Status::Normal);
            }
            _ => {
                anyhow::bail!(
                    "Invalid status filter: {}. Use 'complete' or 'incomplete'",
                    status
                );
            }
        }
    }

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let count = tasks.len();
            let data = TaskListData { tasks, count };
            let response = JsonResponse::success(data);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_task_list(&tasks));
        }
    }

    Ok(())
}

/// Show task details
async fn cmd_task_show(
    task_id: &str,
    project_id: Option<String>,
    project_name: Option<String>,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let project_id = get_project_id(project_id, project_name).await?;
    let client = TickTickClient::new()?;
    let task = client.get_task(&project_id, task_id).await?;

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let data = TaskData { task };
            let response = JsonResponse::success(data);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_task_details(&task));
        }
    }

    Ok(())
}

/// Create a new task
#[allow(clippy::too_many_arguments)]
async fn cmd_task_create(
    title: &str,
    project_id: Option<String>,
    project_name: Option<String>,
    content: Option<String>,
    priority: Option<Priority>,
    tags: Option<String>,
    date: Option<String>,
    start: Option<String>,
    due: Option<String>,
    all_day: bool,
    timezone: Option<String>,
    items: Option<String>,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let project_id = get_project_id(project_id, project_name).await?;

    // Parse dates
    let (start_date, due_date) = parse_task_dates(date, start, due)?;

    // Parse tags
    let tags_vec = tags.map(|t| t.split(',').map(|s| s.trim().to_string()).collect());

    // Parse subtasks/items
    let items_vec = items.map(|i| {
        i.split(',')
            .enumerate()
            .map(|(idx, s)| ChecklistItemRequest::new(s.trim()).with_sort_order(idx as i64))
            .collect()
    });

    let request = CreateTaskRequest {
        title: title.to_string(),
        project_id: project_id.clone(),
        content,
        is_all_day: if all_day { Some(true) } else { None },
        start_date,
        due_date,
        priority: priority.map(|p| p.to_api_value()),
        time_zone: timezone,
        tags: tags_vec,
        items: items_vec,
    };

    let client = TickTickClient::new()?;
    let task = client.create_task(&request).await?;

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let data = TaskData { task };
            let response = JsonResponse::success_with_message(data, "Task created successfully");
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_success_with_id("Task created", &task.id));
        }
    }

    Ok(())
}

/// Update an existing task
#[allow(clippy::too_many_arguments)]
async fn cmd_task_update(
    task_id: &str,
    project_id: Option<String>,
    project_name: Option<String>,
    title: Option<String>,
    content: Option<String>,
    priority: Option<Priority>,
    tags: Option<String>,
    date: Option<String>,
    start: Option<String>,
    due: Option<String>,
    all_day: Option<bool>,
    timezone: Option<String>,
    items: Option<String>,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let project_id = get_project_id(project_id, project_name).await?;

    // Parse dates
    let (start_date, due_date) = parse_task_dates(date, start, due)?;

    // Parse tags
    let tags_vec = tags.map(|t| t.split(',').map(|s| s.trim().to_string()).collect());

    // Parse subtasks/items
    let items_vec = items.map(|i| {
        i.split(',')
            .enumerate()
            .map(|(idx, s)| ChecklistItemRequest::new(s.trim()).with_sort_order(idx as i64))
            .collect()
    });

    let request = UpdateTaskRequest {
        id: task_id.to_string(),
        project_id: project_id.clone(),
        title,
        content,
        is_all_day: all_day,
        start_date,
        due_date,
        priority: priority.map(|p| p.to_api_value()),
        time_zone: timezone,
        tags: tags_vec,
        status: None,
        items: items_vec,
    };

    let client = TickTickClient::new()?;
    let task = client.update_task(task_id, &request).await?;

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let data = TaskData { task };
            let response = JsonResponse::success_with_message(data, "Task updated successfully");
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_success_with_id("Task updated", &task.id));
        }
    }

    Ok(())
}

/// Delete a task
async fn cmd_task_delete(
    task_id: &str,
    project_id: Option<String>,
    project_name: Option<String>,
    force: bool,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let project_id = get_project_id(project_id, project_name).await?;

    // Confirm unless --force is specified
    if !force && format == OutputFormat::Text {
        print!("Delete task '{}'? [y/N] ", task_id);
        std::io::Write::flush(&mut std::io::stdout())?;

        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;

        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Aborted.");
            return Ok(());
        }
    }

    let client = TickTickClient::new()?;
    client.delete_task(&project_id, task_id).await?;

    if quiet {
        return Ok(());
    }

    let message = "Task deleted successfully";
    match format {
        OutputFormat::Json => {
            let response = JsonResponse::success_with_message(serde_json::json!({}), message);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_success(message));
        }
    }

    Ok(())
}

/// Mark a task as complete
async fn cmd_task_complete(
    task_id: &str,
    project_id: Option<String>,
    project_name: Option<String>,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let project_id = get_project_id(project_id, project_name).await?;

    let client = TickTickClient::new()?;
    client.complete_task(&project_id, task_id).await?;

    if quiet {
        return Ok(());
    }

    let message = "Task marked as complete";
    match format {
        OutputFormat::Json => {
            let response = JsonResponse::success_with_message(serde_json::json!({}), message);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_success(message));
        }
    }

    Ok(())
}

/// Mark a task as incomplete
async fn cmd_task_uncomplete(
    task_id: &str,
    project_id: Option<String>,
    project_name: Option<String>,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let project_id = get_project_id(project_id, project_name).await?;

    let client = TickTickClient::new()?;
    let task = client.uncomplete_task(&project_id, task_id).await?;

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let data = TaskData { task };
            let response = JsonResponse::success_with_message(data, "Task marked as incomplete");
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_success("Task marked as incomplete"));
        }
    }

    Ok(())
}

fn parse_task_dates(
    date: Option<String>,
    start: Option<String>,
    due: Option<String>,
) -> anyhow::Result<(Option<String>, Option<String>)> {
    if let Some(date_str) = date {
        let dt = parse_date(&date_str)?;
        let formatted = dt.format("%Y-%m-%dT%H:%M:%S%z").to_string();
        return Ok((Some(formatted.clone()), Some(formatted)));
    }

    let start_date = start
        .map(|s| parse_date(&s).map(|dt| dt.format("%Y-%m-%dT%H:%M:%S%z").to_string()))
        .transpose()?;

    let due_date = due
        .map(|s| parse_date(&s).map(|dt| dt.format("%Y-%m-%dT%H:%M:%S%z").to_string()))
        .transpose()?;

    Ok((start_date, due_date))
}

/// Handle subtask commands
async fn cmd_subtask(
    cmd: SubtaskCommands,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    match cmd {
        SubtaskCommands::List {
            task_id,
            project_id,
            project_name,
        } => cmd_subtask_list(&task_id, project_id, project_name, format, quiet).await,
    }
}

/// List subtasks (checklist items) for a task
async fn cmd_subtask_list(
    task_id: &str,
    project_id: Option<String>,
    project_name: Option<String>,
    format: OutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    let project_id = get_project_id(project_id, project_name).await?;
    let client = TickTickClient::new()?;
    let task = client.get_task(&project_id, task_id).await?;

    let subtasks = task.items;

    if quiet {
        return Ok(());
    }

    match format {
        OutputFormat::Json => {
            let count = subtasks.len();
            let data = SubtaskListData { subtasks, count };
            let response = JsonResponse::success(data);
            println!("{}", response.to_json_string());
        }
        OutputFormat::Text => {
            println!("{}", text::format_subtask_list(&subtasks));
        }
    }

    Ok(())
}