void-focus 0.3.0-alpha.5

A feature-rich terminal focus timer with task tracking
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
mod export;
mod import;
mod schema;

use std::path::PathBuf;

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use rusqlite::{params, Connection};

use crate::model::{
    AppData, EmptyQueueBehavior, EstimateCompleteBehavior, FocusSessionRecord, Priority,
    StoredSession, Subtask, Task, TaskRecurrence, TaskStatus, TimerMode,
};
use crate::theme;

pub struct Database {
    conn: Connection,
}

impl Database {
    pub fn open() -> Result<Self> {
        let path = db_path()?;
        let existed = path.exists();
        let conn = Connection::open(&path).context("opening SQLite database")?;
        conn.pragma_update(None, "journal_mode", "WAL")?;
        conn.pragma_update(None, "foreign_keys", "ON")?;
        schema::migrate(&conn)?;

        let db = Self { conn };
        if !existed {
            let json = legacy_json_path()?;
            if json.exists() {
                import::import_json(&db, &json)?;
                let backup = json.with_extension("json.migrated");
                let _ = std::fs::rename(&json, &backup);
            }
        }
        Ok(db)
    }

    pub fn load_app_data(&self) -> Result<AppData> {
        let mut data = AppData::default();
        load_settings(&self.conn, &mut data)?;
        data.tasks = load_tasks(&self.conn)?;
        data.session_history = Vec::new();
        Ok(data)
    }

    pub fn save_app_data(&self, data: &AppData) -> Result<()> {
        let tx = self.conn.unchecked_transaction()?;
        save_settings(&tx, data)?;
        sync_tasks(&tx, &data.tasks)?;
        tx.commit()?;
        Ok(())
    }

    pub fn insert_focus_session(&self, record: &FocusSessionRecord) -> Result<i64> {
        self.conn.execute(
            "INSERT INTO focus_sessions (date, minutes, task_id, mode, completed_at, note, pause_count, pause_seconds)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
            params![
                record.date,
                record.minutes,
                record.task_id.map(|id| id as i64),
                encode_timer_mode(record.mode),
                record.completed_at.to_rfc3339(),
                record.note,
                record.pause_count,
                record.pause_seconds,
            ],
        )?;
        let id = self.conn.last_insert_rowid();
        for tag in &record.tags {
            self.conn.execute(
                "INSERT INTO session_tags (session_id, tag) VALUES (?1, ?2)",
                params![id, tag],
            )?;
        }
        Ok(id)
    }

    pub fn get_session(&self, id: i64) -> Result<StoredSession> {
        let record = self.conn.query_row(
            "SELECT date, minutes, task_id, mode, completed_at, note, pause_count, pause_seconds
             FROM focus_sessions WHERE id = ?1",
            params![id],
            |row| {
                let mode_str: String = row.get(3)?;
                Ok(FocusSessionRecord {
                    date: row.get(0)?,
                    minutes: row.get(1)?,
                    task_id: read_opt_u64(row, 2)?,
                    mode: decode_timer_mode(&mode_str),
                    completed_at: parse_datetime(&row.get::<_, String>(4)?),
                    note: row.get(5)?,
                    pause_count: row.get(6)?,
                    pause_seconds: row.get(7)?,
                    tags: Vec::new(),
                })
            },
        )?;
        Ok(StoredSession {
            id,
            record: FocusSessionRecord {
                tags: load_session_tags(&self.conn, id)?,
                ..record
            },
        })
    }

    pub fn delete_focus_session(&self, id: i64) -> Result<()> {
        self.conn
            .execute("DELETE FROM focus_sessions WHERE id = ?1", params![id])?;
        Ok(())
    }

    pub fn update_session_minutes(&self, id: i64, minutes: u32) -> Result<()> {
        self.conn.execute(
            "UPDATE focus_sessions SET minutes = ?1 WHERE id = ?2",
            params![minutes, id],
        )?;
        Ok(())
    }

    pub fn recent_sessions(&self, limit: usize) -> Result<Vec<StoredSession>> {
        self.recent_sessions_paged(0, limit)
    }

    pub fn recent_sessions_paged(&self, offset: usize, limit: usize) -> Result<Vec<StoredSession>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, date, minutes, task_id, mode, completed_at, note, pause_count, pause_seconds
             FROM focus_sessions
             ORDER BY completed_at DESC
             LIMIT ?1 OFFSET ?2",
        )?;
        let rows = stmt.query_map(params![limit as i64, offset as i64], |row| {
            let id: i64 = row.get(0)?;
            let mode_str: String = row.get(4)?;
            Ok((
                id,
                FocusSessionRecord {
                    date: row.get(1)?,
                    minutes: row.get(2)?,
                    task_id: read_opt_u64(row, 3)?,
                    mode: decode_timer_mode(&mode_str),
                    completed_at: parse_datetime(&row.get::<_, String>(5)?),
                    note: row.get(6)?,
                    pause_count: row.get(7)?,
                    pause_seconds: row.get(8)?,
                    tags: Vec::new(),
                },
            ))
        })?;
        let mut out = Vec::new();
        for row in rows {
            let (id, mut record) = row?;
            record.tags = load_session_tags(&self.conn, id)?;
            out.push(StoredSession { id, record });
        }
        Ok(out)
    }

    pub fn session_count(&self) -> Result<usize> {
        let count: i64 = self
            .conn
            .query_row("SELECT COUNT(*) FROM focus_sessions", [], |row| row.get(0))?;
        Ok(count as usize)
    }

    pub fn sessions_on_date(&self, date: &str) -> Result<Vec<StoredSession>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, date, minutes, task_id, mode, completed_at, note, pause_count, pause_seconds
             FROM focus_sessions
             WHERE date = ?1
             ORDER BY completed_at ASC",
        )?;
        let rows = stmt.query_map(params![date], |row| {
            let id: i64 = row.get(0)?;
            let mode_str: String = row.get(4)?;
            Ok((
                id,
                FocusSessionRecord {
                    date: row.get(1)?,
                    minutes: row.get(2)?,
                    task_id: read_opt_u64(row, 3)?,
                    mode: decode_timer_mode(&mode_str),
                    completed_at: parse_datetime(&row.get::<_, String>(5)?),
                    note: row.get(6)?,
                    pause_count: row.get(7)?,
                    pause_seconds: row.get(8)?,
                    tags: Vec::new(),
                },
            ))
        })?;
        let mut out = Vec::new();
        for row in rows {
            let (id, mut record) = row?;
            record.tags = load_session_tags(&self.conn, id)?;
            out.push(StoredSession { id, record });
        }
        Ok(out)
    }

    pub fn session_counts_by_mode(&self) -> Result<(u32, u32, u32)> {
        let focus: u32 = self.conn.query_row(
            "SELECT COUNT(*) FROM focus_sessions WHERE mode = ?1",
            params![encode_timer_mode(TimerMode::Focus)],
            |row| row.get(0),
        )?;
        let custom: u32 = self.conn.query_row(
            "SELECT COUNT(*) FROM focus_sessions WHERE mode = ?1",
            params![encode_timer_mode(TimerMode::Custom)],
            |row| row.get(0),
        )?;
        let breaks: u32 = self.conn.query_row(
            "SELECT COUNT(*) FROM focus_sessions WHERE mode IN (?1, ?2)",
            params![
                encode_timer_mode(TimerMode::ShortBreak),
                encode_timer_mode(TimerMode::LongBreak),
            ],
            |row| row.get(0),
        )?;
        Ok((focus, custom, breaks))
    }

    pub fn load_timer_state(&self) -> (u32, TimerMode) {
        let count: u32 = self
            .conn
            .query_row(
                "SELECT value FROM settings WHERE key = 'timer_completed_focus_sessions'",
                [],
                |row| row.get::<_, String>(0),
            )
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);
        let mode = self
            .conn
            .query_row(
                "SELECT value FROM settings WHERE key = 'timer_mode'",
                [],
                |row| row.get::<_, String>(0),
            )
            .ok()
            .map(|s| decode_timer_mode(&s))
            .unwrap_or(TimerMode::Focus);
        (count, mode)
    }

    pub fn persist_timer_state(&self, completed: u32, mode: TimerMode) -> Result<()> {
        self.set_setting("timer_completed_focus_sessions", completed.to_string())?;
        self.set_setting("timer_mode", encode_timer_mode(mode))?;
        Ok(())
    }

    pub fn set_setting(&self, key: &str, value: impl AsRef<str>) -> Result<()> {
        self.conn.execute(
            "INSERT INTO settings (key, value) VALUES (?1, ?2)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            params![key, value.as_ref()],
        )?;
        Ok(())
    }

    pub fn upsert_task(&self, task: &Task) -> Result<()> {
        let tx = self.conn.unchecked_transaction()?;
        upsert_task_row(&tx, task)?;
        tx.commit()?;
        Ok(())
    }

    pub fn delete_task(&self, id: u64) -> Result<()> {
        self.conn
            .execute("DELETE FROM tasks WHERE id = ?1", params![id as i64])?;
        Ok(())
    }

    pub fn sync_sort_orders(&self, tasks: &[Task]) -> Result<()> {
        let tx = self.conn.unchecked_transaction()?;
        for task in tasks {
            tx.execute(
                "UPDATE tasks SET sort_order = ?1 WHERE id = ?2",
                params![task.sort_order, task.id as i64],
            )?;
        }
        tx.commit()?;
        Ok(())
    }

    pub fn persist_session_stats(&self, data: &AppData) -> Result<()> {
        self.set_setting("total_focus_minutes", data.total_focus_minutes.to_string())?;
        self.set_setting("total_sessions", data.total_sessions.to_string())?;
        self.set_setting("streak_days", data.streak_days.to_string())?;
        self.set_setting(
            "last_session_date",
            data.last_session_date.clone().unwrap_or_default(),
        )?;
        self.set_setting("today_focus_minutes", data.today_focus_minutes.to_string())?;
        self.set_setting("today_date", data.today_date.clone().unwrap_or_default())?;
        self.set_setting("goal_streak_days", data.goal_streak_days.to_string())?;
        self.set_setting(
            "last_goal_date",
            data.last_goal_date.clone().unwrap_or_default(),
        )?;
        Ok(())
    }

    pub fn persist_timer_settings(&self, data: &AppData) -> Result<()> {
        self.set_setting("focus_minutes", data.focus_minutes.to_string())?;
        self.set_setting("short_break_minutes", data.short_break_minutes.to_string())?;
        self.set_setting("long_break_minutes", data.long_break_minutes.to_string())?;
        self.set_setting("long_break_every", data.long_break_every.to_string())?;
        Ok(())
    }

    pub fn persist_active_task(&self, id: Option<u64>) -> Result<()> {
        let value = id.map(|i| i.to_string()).unwrap_or_default();
        self.set_setting("active_task_id", value)
    }

    pub fn export_json(&self) -> Result<PathBuf> {
        export::export_json(&self.conn)
    }

    pub fn minutes_by_date(&self, days: usize) -> Result<Vec<(String, u32)>> {
        let today = chrono::Local::now().date_naive();
        let mut out = Vec::with_capacity(days);
        for offset in (0..days).rev() {
            let date = today - chrono::Duration::days(offset as i64);
            let key = date.format("%Y-%m-%d").to_string();
            let mins = self.focus_minutes_on_date(&key)?;
            let label = date.format("%a").to_string();
            out.push((label, mins));
        }
        Ok(out)
    }

    /// Daily focus minutes keyed by `YYYY-MM-DD` (oldest first).
    pub fn focus_minutes_series(&self, days: usize) -> Result<Vec<(String, u32)>> {
        let today = chrono::Local::now().date_naive();
        let mut out = Vec::with_capacity(days);
        for offset in (0..days).rev() {
            let date = today - chrono::Duration::days(offset as i64);
            let key = date.format("%Y-%m-%d").to_string();
            let mins = self.focus_minutes_on_date(&key)?;
            out.push((key, mins));
        }
        Ok(out)
    }

    /// All days with logged focus/custom minutes from the database.
    pub fn focus_minutes_grouped(&self) -> Result<Vec<(String, u32)>> {
        let mut stmt = self.conn.prepare(
            "SELECT date, COALESCE(SUM(minutes), 0) AS mins
             FROM focus_sessions
             WHERE mode IN (?1, ?2)
             GROUP BY date
             ORDER BY date ASC",
        )?;
        let rows = stmt.query_map(
            params![
                encode_timer_mode(TimerMode::Focus),
                encode_timer_mode(TimerMode::Custom),
            ],
            |row| Ok((row.get::<_, String>(0)?, row.get::<_, u32>(1)?)),
        )?;
        rows.collect::<Result<Vec<_>, _>>()
            .context("loading focus minutes")
    }

    fn focus_minutes_on_date(&self, key: &str) -> Result<u32> {
        self.conn
            .query_row(
                "SELECT COALESCE(SUM(minutes), 0) FROM focus_sessions
                 WHERE date = ?1 AND mode IN (?2, ?3)",
                params![
                    key,
                    encode_timer_mode(TimerMode::Focus),
                    encode_timer_mode(TimerMode::Custom),
                ],
                |row| row.get(0),
            )
            .map_err(Into::into)
    }
}

pub fn db_path() -> Result<PathBuf> {
    let dir = data_dir()?;
    Ok(dir.join("void.db"))
}

pub fn legacy_json_path() -> Result<PathBuf> {
    Ok(data_dir()?.join("data.json"))
}

fn data_dir() -> Result<PathBuf> {
    let dir = dirs::data_local_dir()
        .or_else(dirs::config_dir)
        .context("could not resolve local data directory")?;
    let focus_dir = dir.join("void");
    std::fs::create_dir_all(&focus_dir).context("creating data directory")?;
    Ok(focus_dir)
}

// ── settings ─────────────────────────────────────────────────────────────────

pub(crate) fn load_settings(conn: &Connection, data: &mut AppData) -> Result<()> {
    let mut stmt = conn.prepare("SELECT key, value FROM settings")?;
    let rows = stmt.query_map([], |row| {
        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
    })?;
    for row in rows {
        let (key, value) = row?;
        apply_setting(data, &key, &value);
    }
    Ok(())
}

fn save_settings(conn: &Connection, data: &AppData) -> Result<()> {
    let pairs: Vec<(&str, String)> = vec![
        ("next_id", data.next_id.to_string()),
        ("total_focus_minutes", data.total_focus_minutes.to_string()),
        ("total_sessions", data.total_sessions.to_string()),
        ("streak_days", data.streak_days.to_string()),
        (
            "last_session_date",
            data.last_session_date.clone().unwrap_or_default(),
        ),
        ("daily_goal_minutes", data.daily_goal_minutes.to_string()),
        ("sound_enabled", bool_str(data.sound_enabled)),
        ("auto_start_breaks", bool_str(data.auto_start_breaks)),
        ("auto_start_focus", bool_str(data.auto_start_focus)),
        ("today_focus_minutes", data.today_focus_minutes.to_string()),
        ("today_date", data.today_date.clone().unwrap_or_default()),
        ("focus_minutes", data.focus_minutes.to_string()),
        ("short_break_minutes", data.short_break_minutes.to_string()),
        ("long_break_minutes", data.long_break_minutes.to_string()),
        ("long_break_every", data.long_break_every.to_string()),
        ("auto_pick_task", bool_str(data.auto_pick_task)),
        ("auto_advance_task", bool_str(data.auto_advance_task)),
        ("theme", data.theme.clone()),
        (
            "active_task_id",
            data.active_task_id
                .map(|id| id.to_string())
                .unwrap_or_default(),
        ),
        ("notify_on_finish", bool_str(data.notify_on_finish)),
        ("goal_streak_days", data.goal_streak_days.to_string()),
        (
            "last_goal_date",
            data.last_goal_date.clone().unwrap_or_default(),
        ),
        (
            "empty_queue_behavior",
            encode_empty_queue(data.empty_queue_behavior).to_string(),
        ),
        ("log_breaks", bool_str(data.log_breaks)),
        (
            "estimate_complete",
            encode_estimate_complete(data.estimate_complete).to_string(),
        ),
        ("show_terminal_title", bool_str(data.show_terminal_title)),
        ("warn_one_minute", bool_str(data.warn_one_minute)),
        (
            "auto_pause_idle_minutes",
            data.auto_pause_idle_minutes.to_string(),
        ),
        ("archive_after_days", data.archive_after_days.to_string()),
        ("weekly_streak_weeks", data.weekly_streak_weeks.to_string()),
        (
            "monthly_streak_months",
            data.monthly_streak_months.to_string(),
        ),
        (
            "last_weekly_streak_key",
            data.last_weekly_streak_key.clone().unwrap_or_default(),
        ),
        (
            "last_monthly_streak_key",
            data.last_monthly_streak_key.clone().unwrap_or_default(),
        ),
        (
            "timer_presets",
            serde_json::to_string(&data.timer_presets).unwrap_or_default(),
        ),
        (
            "active_preset",
            data.active_preset.clone().unwrap_or_default(),
        ),
    ];

    for (key, value) in pairs {
        conn.execute(
            "INSERT INTO settings (key, value) VALUES (?1, ?2)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            params![key, value],
        )?;
    }
    Ok(())
}

fn apply_setting(data: &mut AppData, key: &str, value: &str) {
    match key {
        "next_id" => data.next_id = parse_u64(value, data.next_id),
        "total_focus_minutes" => {
            data.total_focus_minutes = parse_u32(value, data.total_focus_minutes)
        }
        "total_sessions" => data.total_sessions = parse_u32(value, data.total_sessions),
        "streak_days" => data.streak_days = parse_u32(value, data.streak_days),
        "last_session_date" => data.last_session_date = opt_string(value),
        "daily_goal_minutes" => data.daily_goal_minutes = parse_u32(value, data.daily_goal_minutes),
        "sound_enabled" => data.sound_enabled = parse_bool(value, data.sound_enabled),
        "auto_start_breaks" => data.auto_start_breaks = parse_bool(value, data.auto_start_breaks),
        "auto_start_focus" => data.auto_start_focus = parse_bool(value, data.auto_start_focus),
        "today_focus_minutes" => {
            data.today_focus_minutes = parse_u32(value, data.today_focus_minutes)
        }
        "today_date" => data.today_date = opt_string(value),
        "focus_minutes" => data.focus_minutes = parse_u32(value, data.focus_minutes),
        "short_break_minutes" => {
            data.short_break_minutes = parse_u32(value, data.short_break_minutes)
        }
        "long_break_minutes" => data.long_break_minutes = parse_u32(value, data.long_break_minutes),
        "long_break_every" => data.long_break_every = parse_u32(value, data.long_break_every),
        "auto_pick_task" => data.auto_pick_task = parse_bool(value, data.auto_pick_task),
        "auto_advance_task" => data.auto_advance_task = parse_bool(value, data.auto_advance_task),
        "theme" if !value.is_empty() => {
            data.theme = theme::normalize_theme_id(value);
        }
        "active_task_id" => data.active_task_id = value.parse().ok(),
        "notify_on_finish" => data.notify_on_finish = parse_bool(value, data.notify_on_finish),
        "goal_streak_days" => data.goal_streak_days = parse_u32(value, data.goal_streak_days),
        "last_goal_date" => data.last_goal_date = opt_string(value),
        "empty_queue_behavior" => {
            data.empty_queue_behavior =
                decode_empty_queue(value).unwrap_or(data.empty_queue_behavior)
        }
        "log_breaks" => data.log_breaks = parse_bool(value, data.log_breaks),
        "estimate_complete" => {
            data.estimate_complete =
                decode_estimate_complete(value).unwrap_or(data.estimate_complete)
        }
        "show_terminal_title" => {
            data.show_terminal_title = parse_bool(value, data.show_terminal_title)
        }
        "warn_one_minute" => data.warn_one_minute = parse_bool(value, data.warn_one_minute),
        "auto_pause_idle_minutes" => {
            data.auto_pause_idle_minutes = parse_u32(value, data.auto_pause_idle_minutes)
        }
        "archive_after_days" => data.archive_after_days = parse_u32(value, data.archive_after_days),
        "weekly_streak_weeks" => {
            data.weekly_streak_weeks = parse_u32(value, data.weekly_streak_weeks)
        }
        "monthly_streak_months" => {
            data.monthly_streak_months = parse_u32(value, data.monthly_streak_months)
        }
        "last_weekly_streak_key" => data.last_weekly_streak_key = opt_string(value),
        "last_monthly_streak_key" => data.last_monthly_streak_key = opt_string(value),
        "timer_presets" if !value.is_empty() => {
            if let Ok(presets) = serde_json::from_str(value) {
                data.timer_presets = presets;
            }
        }
        "active_preset" => data.active_preset = opt_string(value),
        _ => {}
    }
}

// ── tasks ────────────────────────────────────────────────────────────────────

pub(crate) fn load_tasks(conn: &Connection) -> Result<Vec<Task>> {
    let mut stmt = conn.prepare(
        "SELECT id, title, notes, priority, status, estimated_minutes, actual_minutes,
                sessions, created_at, completed_at, due_date, today, sort_order,
                archived, recurrence
         FROM tasks
         ORDER BY sort_order ASC, id ASC",
    )?;
    let rows = stmt.query_map([], |row| {
        Ok(Task {
            id: read_u64(row, 0)?,
            title: row.get(1)?,
            notes: row.get(2)?,
            priority: decode_priority(&row.get::<_, String>(3)?),
            status: decode_task_status(&row.get::<_, String>(4)?),
            estimated_minutes: row.get(5)?,
            actual_minutes: row.get(6)?,
            sessions: row.get(7)?,
            created_at: parse_datetime(&row.get::<_, String>(8)?),
            completed_at: row.get::<_, Option<String>>(9)?.map(|s| parse_datetime(&s)),
            due_date: row.get::<_, Option<String>>(10)?,
            today: row.get::<_, i32>(11)? != 0,
            sort_order: row.get(12)?,
            archived: row.get::<_, i32>(13)? != 0,
            recurrence: decode_recurrence(&row.get::<_, String>(14)?),
            subtasks: Vec::new(),
            blocked_by: Vec::new(),
            tags: Vec::new(),
        })
    })?;

    let mut tasks = Vec::new();
    for row in rows {
        let mut task = row?;
        task.tags = load_task_tags(conn, task.id)?;
        task.subtasks = load_subtasks(conn, task.id)?;
        task.blocked_by = load_blocked_by(conn, task.id)?;
        tasks.push(task);
    }
    Ok(tasks)
}

fn load_task_tags(conn: &Connection, task_id: u64) -> Result<Vec<String>> {
    let mut stmt = conn.prepare("SELECT tag FROM task_tags WHERE task_id = ?1 ORDER BY tag ASC")?;
    let tags = stmt
        .query_map(params![task_id as i64], |row| row.get(0))?
        .collect::<Result<Vec<String>, _>>()?;
    Ok(tags)
}

fn sync_tasks(conn: &Connection, tasks: &[Task]) -> Result<()> {
    conn.execute("DELETE FROM task_tags", [])?;
    conn.execute("DELETE FROM task_blocked_by", [])?;
    conn.execute("DELETE FROM subtasks", [])?;
    conn.execute("DELETE FROM tasks", [])?;
    for task in tasks {
        upsert_task_row(conn, task)?;
    }
    Ok(())
}

fn upsert_task_row(conn: &Connection, task: &Task) -> Result<()> {
    conn.execute(
        "INSERT INTO tasks (
            id, title, notes, priority, status, estimated_minutes, actual_minutes,
            sessions, created_at, completed_at, due_date, today, sort_order,
            archived, recurrence
         ) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15)
         ON CONFLICT(id) DO UPDATE SET
            title = excluded.title,
            notes = excluded.notes,
            priority = excluded.priority,
            status = excluded.status,
            estimated_minutes = excluded.estimated_minutes,
            actual_minutes = excluded.actual_minutes,
            sessions = excluded.sessions,
            created_at = excluded.created_at,
            completed_at = excluded.completed_at,
            due_date = excluded.due_date,
            today = excluded.today,
            sort_order = excluded.sort_order,
            archived = excluded.archived,
            recurrence = excluded.recurrence",
        params![
            task.id as i64,
            task.title,
            task.notes,
            encode_priority(task.priority),
            encode_task_status(task.status),
            task.estimated_minutes,
            task.actual_minutes,
            task.sessions,
            task.created_at.to_rfc3339(),
            task.completed_at.map(|dt| dt.to_rfc3339()),
            task.due_date,
            if task.today { 1 } else { 0 },
            task.sort_order,
            if task.archived { 1 } else { 0 },
            encode_recurrence(task.recurrence),
        ],
    )?;
    conn.execute(
        "DELETE FROM task_tags WHERE task_id = ?1",
        params![task.id as i64],
    )?;
    for tag in &task.tags {
        conn.execute(
            "INSERT INTO task_tags (task_id, tag) VALUES (?1, ?2)",
            params![task.id as i64, tag],
        )?;
    }
    conn.execute(
        "DELETE FROM subtasks WHERE task_id = ?1",
        params![task.id as i64],
    )?;
    for (i, sub) in task.subtasks.iter().enumerate() {
        conn.execute(
            "INSERT INTO subtasks (id, task_id, title, done, sort_order) VALUES (?1, ?2, ?3, ?4, ?5)",
            params![
                sub.id as i64,
                task.id as i64,
                sub.title,
                if sub.done { 1 } else { 0 },
                i as i64,
            ],
        )?;
    }
    conn.execute(
        "DELETE FROM task_blocked_by WHERE task_id = ?1",
        params![task.id as i64],
    )?;
    for blocker_id in &task.blocked_by {
        conn.execute(
            "INSERT INTO task_blocked_by (task_id, blocker_id) VALUES (?1, ?2)",
            params![task.id as i64, *blocker_id as i64],
        )?;
    }
    Ok(())
}

fn load_subtasks(conn: &Connection, task_id: u64) -> Result<Vec<Subtask>> {
    let mut stmt = conn.prepare(
        "SELECT id, title, done FROM subtasks WHERE task_id = ?1 ORDER BY sort_order ASC",
    )?;
    let rows = stmt.query_map(params![task_id as i64], |row| {
        Ok(Subtask {
            id: read_u64(row, 0)?,
            title: row.get(1)?,
            done: row.get::<_, i32>(2)? != 0,
        })
    })?;
    rows.collect::<Result<Vec<_>, _>>()
        .context("loading subtasks")
}

fn load_blocked_by(conn: &Connection, task_id: u64) -> Result<Vec<u64>> {
    let mut stmt = conn
        .prepare("SELECT blocker_id FROM task_blocked_by WHERE task_id = ?1 ORDER BY blocker_id")?;
    let rows = stmt.query_map(params![task_id as i64], |row| read_u64(row, 0))?;
    rows.collect::<Result<Vec<_>, _>>()
        .context("loading task blockers")
}

fn load_session_tags(conn: &Connection, session_id: i64) -> Result<Vec<String>> {
    let mut stmt =
        conn.prepare("SELECT tag FROM session_tags WHERE session_id = ?1 ORDER BY tag ASC")?;
    let tags = stmt
        .query_map(params![session_id], |row| row.get(0))?
        .collect::<Result<Vec<String>, _>>()?;
    Ok(tags)
}

fn encode_recurrence(r: TaskRecurrence) -> &'static str {
    match r {
        TaskRecurrence::None => "none",
        TaskRecurrence::Daily => "daily",
        TaskRecurrence::Weekly => "weekly",
        TaskRecurrence::Weekdays => "weekdays",
    }
}

fn decode_recurrence(s: &str) -> TaskRecurrence {
    match s {
        "daily" => TaskRecurrence::Daily,
        "weekly" => TaskRecurrence::Weekly,
        "weekdays" => TaskRecurrence::Weekdays,
        _ => TaskRecurrence::None,
    }
}

// ── encoding ─────────────────────────────────────────────────────────────────

fn encode_priority(p: Priority) -> &'static str {
    match p {
        Priority::Low => "low",
        Priority::Medium => "medium",
        Priority::High => "high",
    }
}

fn decode_priority(s: &str) -> Priority {
    match s {
        "high" => Priority::High,
        "low" => Priority::Low,
        _ => Priority::Medium,
    }
}

fn encode_task_status(s: TaskStatus) -> &'static str {
    match s {
        TaskStatus::Pending => "pending",
        TaskStatus::InProgress => "inprogress",
        TaskStatus::Done => "done",
    }
}

fn decode_task_status(s: &str) -> TaskStatus {
    match s {
        "done" => TaskStatus::Done,
        "inprogress" | "in_progress" => TaskStatus::InProgress,
        _ => TaskStatus::Pending,
    }
}

fn encode_timer_mode(m: TimerMode) -> &'static str {
    match m {
        TimerMode::Focus => "focus",
        TimerMode::ShortBreak => "shortbreak",
        TimerMode::LongBreak => "longbreak",
        TimerMode::Custom => "custom",
    }
}

fn decode_timer_mode(s: &str) -> TimerMode {
    match s {
        "shortbreak" | "short_break" => TimerMode::ShortBreak,
        "longbreak" | "long_break" => TimerMode::LongBreak,
        "custom" => TimerMode::Custom,
        _ => TimerMode::Focus,
    }
}

fn encode_empty_queue(b: EmptyQueueBehavior) -> &'static str {
    match b {
        EmptyQueueBehavior::FreeFocus => "free-focus",
        EmptyQueueBehavior::PauseTimer => "pause-timer",
        EmptyQueueBehavior::AskEachTime => "ask",
    }
}

fn decode_empty_queue(s: &str) -> Option<EmptyQueueBehavior> {
    Some(match s {
        "pause-timer" => EmptyQueueBehavior::PauseTimer,
        "ask" => EmptyQueueBehavior::AskEachTime,
        _ => EmptyQueueBehavior::FreeFocus,
    })
}

fn encode_estimate_complete(b: EstimateCompleteBehavior) -> &'static str {
    match b {
        EstimateCompleteBehavior::Nudge => "nudge",
        EstimateCompleteBehavior::None => "none",
        EstimateCompleteBehavior::AutoDone => "auto-done",
    }
}

fn decode_estimate_complete(s: &str) -> Option<EstimateCompleteBehavior> {
    Some(match s {
        "none" => EstimateCompleteBehavior::None,
        "auto-done" => EstimateCompleteBehavior::AutoDone,
        _ => EstimateCompleteBehavior::Nudge,
    })
}

pub(crate) fn parse_datetime(s: &str) -> DateTime<Utc> {
    DateTime::parse_from_rfc3339(s)
        .map(|dt| dt.with_timezone(&Utc))
        .unwrap_or_else(|_| Utc::now())
}

fn bool_str(v: bool) -> String {
    if v { "1" } else { "0" }.to_string()
}

fn parse_bool(s: &str, default: bool) -> bool {
    match s {
        "1" | "true" | "yes" => true,
        "0" | "false" | "no" => false,
        _ => default,
    }
}

pub(crate) fn read_u64(row: &rusqlite::Row<'_>, idx: usize) -> rusqlite::Result<u64> {
    Ok(row.get::<_, i64>(idx)? as u64)
}

pub(crate) fn read_opt_u64(row: &rusqlite::Row<'_>, idx: usize) -> rusqlite::Result<Option<u64>> {
    let value: Option<i64> = row.get(idx)?;
    Ok(value.map(|id| id as u64))
}

fn parse_u32(s: &str, default: u32) -> u32 {
    s.parse().unwrap_or(default)
}

fn parse_u64(s: &str, default: u64) -> u64 {
    s.parse().unwrap_or(default)
}

fn opt_string(s: &str) -> Option<String> {
    if s.is_empty() {
        None
    } else {
        Some(s.to_string())
    }
}