things3-core 1.1.0

Core library for Things 3 database access and data models
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
//! Query builder for filtering and searching tasks

use crate::models::{TaskFilters, TaskStatus, TaskType};
use chrono::{Datelike, Duration, NaiveDate, Utc};
use uuid::Uuid;

/// Builder for constructing task queries with filters
#[derive(Debug, Clone)]
pub struct TaskQueryBuilder {
    filters: TaskFilters,
    /// OR-semantics / exclusion / count tag filters applied by `execute()` in Rust.
    /// Kept off `TaskFilters` to preserve the stable public struct surface.
    /// Only present in `advanced-queries` builds (same gate as `execute()`).
    #[cfg(feature = "advanced-queries")]
    any_tags: Option<Vec<String>>,
    #[cfg(feature = "advanced-queries")]
    exclude_tags: Option<Vec<String>>,
    #[cfg(feature = "advanced-queries")]
    tag_count_min: Option<usize>,
    #[cfg(feature = "advanced-queries")]
    fuzzy_query: Option<String>,
    #[cfg(feature = "advanced-queries")]
    fuzzy_threshold: Option<f32>,
    #[cfg(feature = "advanced-queries")]
    where_expr: Option<crate::filter_expr::FilterExpr>,
}

impl TaskQueryBuilder {
    /// Create a new query builder
    #[must_use]
    pub fn new() -> Self {
        Self {
            filters: TaskFilters::default(),
            #[cfg(feature = "advanced-queries")]
            any_tags: None,
            #[cfg(feature = "advanced-queries")]
            exclude_tags: None,
            #[cfg(feature = "advanced-queries")]
            tag_count_min: None,
            #[cfg(feature = "advanced-queries")]
            fuzzy_query: None,
            #[cfg(feature = "advanced-queries")]
            fuzzy_threshold: None,
            #[cfg(feature = "advanced-queries")]
            where_expr: None,
        }
    }

    /// Filter by status
    #[must_use]
    pub const fn status(mut self, status: TaskStatus) -> Self {
        self.filters.status = Some(status);
        self
    }

    /// Filter by task type
    #[must_use]
    pub const fn task_type(mut self, task_type: TaskType) -> Self {
        self.filters.task_type = Some(task_type);
        self
    }

    /// Filter by project UUID
    #[must_use]
    pub const fn project_uuid(mut self, project_uuid: Uuid) -> Self {
        self.filters.project_uuid = Some(project_uuid);
        self
    }

    /// Filter by area UUID
    #[must_use]
    pub const fn area_uuid(mut self, area_uuid: Uuid) -> Self {
        self.filters.area_uuid = Some(area_uuid);
        self
    }

    /// Filter by tags (AND semantics — task must contain every listed tag).
    #[must_use]
    pub fn tags(mut self, tags: Vec<String>) -> Self {
        self.filters.tags = Some(tags);
        self
    }

    /// Filter to tasks containing **any** of these tags (OR semantics).
    ///
    /// Composes with `.tags()` (AND) and `.exclude_tags()` (NOT) — all
    /// active tag filters must be satisfied. Applied in Rust by `execute()`;
    /// not reflected in `build()`.
    ///
    /// Requires the `advanced-queries` feature flag.
    #[cfg(feature = "advanced-queries")]
    #[must_use]
    pub fn any_tags(mut self, tags: Vec<String>) -> Self {
        self.any_tags = Some(tags);
        self
    }

    /// Filter out tasks containing any of these tags. Applied in Rust by `execute()`;
    /// not reflected in `build()`.
    ///
    /// Requires the `advanced-queries` feature flag.
    #[cfg(feature = "advanced-queries")]
    #[must_use]
    pub fn exclude_tags(mut self, tags: Vec<String>) -> Self {
        self.exclude_tags = Some(tags);
        self
    }

    /// Filter to tasks with at least `min` tags total. Applied in Rust by `execute()`;
    /// not reflected in `build()`.
    ///
    /// Requires the `advanced-queries` feature flag.
    #[cfg(feature = "advanced-queries")]
    #[must_use]
    pub fn tag_count(mut self, min: usize) -> Self {
        self.tag_count_min = Some(min);
        self
    }

    /// Filter and rank tasks by fuzzy similarity to `query` (title and notes).
    ///
    /// Scores are computed with windowed Levenshtein; only tasks meeting the
    /// threshold (default `0.6`, tunable via `fuzzy_threshold`) are returned.
    /// If `.search()` is also set, fuzzy wins and a warning is logged.
    ///
    /// Applied in Rust by `execute()` / `execute_ranked()`; not reflected in `build()`.
    ///
    /// Requires the `advanced-queries` feature flag.
    #[cfg(feature = "advanced-queries")]
    #[must_use]
    pub fn fuzzy_search(mut self, query: &str) -> Self {
        self.fuzzy_query = Some(query.to_string());
        self
    }

    /// Override the minimum fuzzy-match score threshold (clamped to `[0.0, 1.0]`).
    /// Defaults to `0.6` when not called.
    ///
    /// Requires the `advanced-queries` feature flag.
    #[cfg(feature = "advanced-queries")]
    #[must_use]
    pub fn fuzzy_threshold(mut self, threshold: f32) -> Self {
        self.fuzzy_threshold = Some(threshold.clamp(0.0, 1.0));
        self
    }

    /// Apply a boolean expression tree as an additional filter.
    ///
    /// The expression composes via AND with the SQL pre-fetch (`TaskFilters`)
    /// and with the other post-filters (`any_tags`, `exclude_tags`,
    /// `tag_count`, fuzzy search). To express disjunction or negation across
    /// statuses or types, leave `filters.status` / `filters.task_type` unset
    /// and put the OR/NOT branches inside `expr` instead.
    ///
    /// Evaluated in Rust by `execute()` after the database returns rows; not
    /// reflected in `build()`.
    ///
    /// Requires the `advanced-queries` feature flag.
    #[cfg(feature = "advanced-queries")]
    #[must_use]
    pub fn where_expr(mut self, expr: crate::filter_expr::FilterExpr) -> Self {
        self.where_expr = Some(expr);
        self
    }

    /// Filter by start date range
    #[must_use]
    pub const fn start_date_range(
        mut self,
        from: Option<NaiveDate>,
        to: Option<NaiveDate>,
    ) -> Self {
        self.filters.start_date_from = from;
        self.filters.start_date_to = to;
        self
    }

    /// Filter by deadline range
    #[must_use]
    pub const fn deadline_range(mut self, from: Option<NaiveDate>, to: Option<NaiveDate>) -> Self {
        self.filters.deadline_from = from;
        self.filters.deadline_to = to;
        self
    }

    /// Add search query
    #[must_use]
    pub fn search(mut self, query: &str) -> Self {
        self.filters.search_query = Some(query.to_string());
        self
    }

    /// Set limit
    #[must_use]
    pub const fn limit(mut self, limit: usize) -> Self {
        self.filters.limit = Some(limit);
        self
    }

    /// Set offset for pagination
    #[must_use]
    pub const fn offset(mut self, offset: usize) -> Self {
        self.filters.offset = Some(offset);
        self
    }

    /// Filter to tasks whose deadline is today.
    #[must_use]
    pub fn due_today(self) -> Self {
        let today = today();
        self.deadline_range(Some(today), Some(today))
    }

    /// Filter to tasks whose deadline falls between today and the upcoming Sunday
    /// (Monday-Sunday week).
    #[must_use]
    pub fn due_this_week(self) -> Self {
        let today = today();
        self.deadline_range(Some(today), Some(end_of_week(today)))
    }

    /// Filter to tasks whose deadline falls in next calendar week (next Monday
    /// through Sunday, Monday-Sunday week).
    #[must_use]
    pub fn due_next_week(self) -> Self {
        let today = today();
        let next_monday = end_of_week(today) + Duration::days(1);
        self.deadline_range(Some(next_monday), Some(end_of_week(next_monday)))
    }

    /// Filter to tasks whose deadline is between today and `days` days from now (inclusive).
    #[must_use]
    pub fn due_in(self, days: i64) -> Self {
        let today = today();
        self.deadline_range(Some(today), Some(today + Duration::days(days)))
    }

    /// Filter to overdue tasks: deadline strictly before today.
    ///
    /// If no `status` filter has already been set, this also restricts results
    /// to incomplete tasks (a completed task isn't meaningfully overdue). An
    /// explicit `.status(...)` call before this helper is preserved.
    #[must_use]
    pub fn overdue(mut self) -> Self {
        let yesterday = today() - Duration::days(1);
        self.filters.deadline_from = None;
        self.filters.deadline_to = Some(yesterday);
        if self.filters.status.is_none() {
            self.filters.status = Some(TaskStatus::Incomplete);
        }
        self
    }

    /// Filter to tasks with a start date of today.
    #[must_use]
    pub fn starting_today(self) -> Self {
        let today = today();
        self.start_date_range(Some(today), Some(today))
    }

    /// Filter to tasks with a start date between today and the upcoming Sunday
    /// (Monday-Sunday week).
    #[must_use]
    pub fn starting_this_week(self) -> Self {
        let today = today();
        self.start_date_range(Some(today), Some(end_of_week(today)))
    }

    /// Build the final filters
    #[must_use]
    pub fn build(self) -> TaskFilters {
        self.filters
    }

    /// Execute the query against a live database connection.
    ///
    /// SQL-level filters and the `tags` AND-filter are handled by `query_tasks`.
    /// Builder-only predicates (`any_tags`, `exclude_tags`, `tag_count`,
    /// `fuzzy_search`) are applied in Rust afterward; when any are active,
    /// `limit`/`offset` pagination is deferred to Rust so pages count only
    /// matching rows. When `fuzzy_search` is set, this delegates to
    /// `execute_ranked` and strips scores.
    ///
    /// Requires the `advanced-queries` feature flag.
    ///
    /// # Errors
    ///
    /// Returns an error if the database query fails or task data cannot be mapped.
    #[cfg(feature = "advanced-queries")]
    pub async fn execute(
        &self,
        db: &crate::database::ThingsDatabase,
    ) -> crate::error::Result<Vec<crate::models::Task>> {
        if self.fuzzy_query.is_some() {
            return self
                .execute_ranked(db)
                .await
                .map(|ranked| ranked.into_iter().map(|r| r.task).collect());
        }

        let has_tag_post_filters = self.any_tags.as_ref().is_some_and(|t| !t.is_empty())
            || self.exclude_tags.as_ref().is_some_and(|t| !t.is_empty())
            || self.tag_count_min.is_some();
        let has_where_expr = self.where_expr.is_some();

        if !has_tag_post_filters && !has_where_expr {
            return db.query_tasks(&self.filters).await;
        }

        let mut filters_no_page = self.filters.clone();
        let limit = filters_no_page.limit.take();
        let offset = filters_no_page.offset.take();

        let tasks = db.query_tasks(&filters_no_page).await?;
        let mut tasks = Self::apply_tag_filters(
            tasks,
            self.any_tags.as_deref(),
            self.exclude_tags.as_deref(),
            self.tag_count_min,
        );

        if let Some(expr) = &self.where_expr {
            tasks.retain(|task| expr.matches(task));
        }

        let offset = offset.unwrap_or(0);
        tasks = tasks.into_iter().skip(offset).collect();
        if let Some(limit) = limit {
            tasks.truncate(limit);
        }

        Ok(tasks)
    }

    #[cfg(feature = "advanced-queries")]
    fn apply_tag_filters(
        mut tasks: Vec<crate::models::Task>,
        any_tags: Option<&[String]>,
        exclude_tags: Option<&[String]>,
        tag_count_min: Option<usize>,
    ) -> Vec<crate::models::Task> {
        if let Some(any) = any_tags {
            if !any.is_empty() {
                tasks.retain(|task| any.iter().any(|f| task.tags.contains(f)));
            }
        }
        if let Some(excl) = exclude_tags {
            if !excl.is_empty() {
                tasks.retain(|task| !excl.iter().any(|f| task.tags.contains(f)));
            }
        }
        if let Some(min) = tag_count_min {
            tasks.retain(|task| task.tags.len() >= min);
        }
        tasks
    }

    /// Execute the query and return tasks paired with their fuzzy-match scores,
    /// sorted by score descending (ties broken by UUID for determinism).
    ///
    /// Requires `.fuzzy_search(query)` to be set — returns a validation error
    /// otherwise (it is a programming error to ask for ranked results with no
    /// fuzzy predicate).
    ///
    /// Requires the `advanced-queries` feature flag.
    ///
    /// # Errors
    ///
    /// Returns an error if `fuzzy_search` is not set, or if the database query fails.
    #[cfg(feature = "advanced-queries")]
    pub async fn execute_ranked(
        &self,
        db: &crate::database::ThingsDatabase,
    ) -> crate::error::Result<Vec<crate::models::RankedTask>> {
        let query = self.fuzzy_query.as_deref().ok_or_else(|| {
            crate::error::ThingsError::validation(
                "execute_ranked requires fuzzy_search() to be set",
            )
        })?;

        let query_lc = query.to_lowercase();
        let threshold = self.fuzzy_threshold.unwrap_or(DEFAULT_FUZZY_THRESHOLD);

        let mut filters_no_page = self.filters.clone();
        let limit = filters_no_page.limit.take();
        let offset = filters_no_page.offset.take();

        if filters_no_page.search_query.is_some() {
            tracing::warn!(
                "fuzzy_search and search both set; fuzzy takes precedence, ignoring substring search"
            );
            filters_no_page.search_query = None;
        }

        let tasks = db.query_tasks(&filters_no_page).await?;
        let mut tasks = Self::apply_tag_filters(
            tasks,
            self.any_tags.as_deref(),
            self.exclude_tags.as_deref(),
            self.tag_count_min,
        );

        if let Some(expr) = &self.where_expr {
            tasks.retain(|task| expr.matches(task));
        }

        let mut scored: Vec<crate::models::RankedTask> = tasks
            .into_iter()
            .filter_map(|task| {
                let score = task_fuzzy_score(&query_lc, &task);
                if score >= threshold {
                    Some(crate::models::RankedTask { task, score })
                } else {
                    None
                }
            })
            .collect();

        scored.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.task.uuid.cmp(&b.task.uuid))
        });

        let offset = offset.unwrap_or(0);
        scored = scored.into_iter().skip(offset).collect();
        if let Some(limit) = limit {
            scored.truncate(limit);
        }

        Ok(scored)
    }

    /// Snapshot the full builder state — both [`TaskFilters`] and the
    /// builder-only post-1.0.0 predicates — into a [`crate::saved_queries::SavedQuery`].
    ///
    /// Combine with [`crate::saved_queries::SavedQueryStore`] to persist queries
    /// to disk and replay them later via [`Self::from_saved_query`].
    ///
    /// Requires the `advanced-queries` feature flag.
    #[cfg(feature = "advanced-queries")]
    #[must_use]
    pub fn to_saved_query(&self, name: impl Into<String>) -> crate::saved_queries::SavedQuery {
        crate::saved_queries::SavedQuery {
            name: name.into(),
            description: None,
            filters: self.filters.clone(),
            any_tags: self.any_tags.clone(),
            exclude_tags: self.exclude_tags.clone(),
            tag_count_min: self.tag_count_min,
            fuzzy_query: self.fuzzy_query.clone(),
            fuzzy_threshold: self.fuzzy_threshold,
            where_expr: self.where_expr.clone(),
            saved_at: chrono::Utc::now(),
        }
    }

    /// Reconstruct a builder from a previously-saved [`crate::saved_queries::SavedQuery`].
    /// The returned builder can be executed directly via [`Self::execute`] or
    /// [`Self::execute_ranked`].
    ///
    /// Requires the `advanced-queries` feature flag.
    #[cfg(feature = "advanced-queries")]
    #[must_use]
    pub fn from_saved_query(query: &crate::saved_queries::SavedQuery) -> Self {
        Self {
            filters: query.filters.clone(),
            any_tags: query.any_tags.clone(),
            exclude_tags: query.exclude_tags.clone(),
            tag_count_min: query.tag_count_min,
            fuzzy_query: query.fuzzy_query.clone(),
            fuzzy_threshold: query.fuzzy_threshold.map(|t| t.clamp(0.0, 1.0)),
            where_expr: query.where_expr.clone(),
        }
    }
}

impl Default for TaskQueryBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "advanced-queries")]
const DEFAULT_FUZZY_THRESHOLD: f32 = 0.6;

#[cfg(feature = "advanced-queries")]
fn task_fuzzy_score(query_lc: &str, task: &crate::models::Task) -> f32 {
    let title_score = fuzzy_field_score(query_lc, &task.title);
    let notes_score = task
        .notes
        .as_deref()
        .map(|n| fuzzy_field_score(query_lc, n))
        .unwrap_or(0.0);
    title_score.max(notes_score)
}

#[cfg(feature = "advanced-queries")]
fn fuzzy_field_score(query_lc: &str, field: &str) -> f32 {
    let field_lc = field.to_lowercase();
    if !query_lc.is_empty() && field_lc.contains(query_lc) {
        return 1.0;
    }
    best_window_score(query_lc, &field_lc)
}

#[cfg(feature = "advanced-queries")]
fn best_window_score(query: &str, field: &str) -> f32 {
    if query.is_empty() || field.is_empty() {
        return 0.0;
    }
    let window_len = (2 * query.len()).min(field.len());
    let step = 1;
    let chars: Vec<char> = field.chars().collect();
    let n = chars.len();
    let mut best = 0.0f32;
    let mut i = 0;
    loop {
        let end = (i + window_len).min(n);
        let slice: String = chars[i..end].iter().collect();
        let score = strsim::normalized_levenshtein(query, &slice) as f32;
        if score > best {
            best = score;
        }
        if end >= n {
            break;
        }
        i += step;
    }
    best
}

fn today() -> NaiveDate {
    Utc::now().date_naive()
}

fn end_of_week(d: NaiveDate) -> NaiveDate {
    let days_from_monday = i64::from(d.weekday().num_days_from_monday());
    d + Duration::days(6 - days_from_monday)
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::NaiveDate;
    use uuid::Uuid;

    #[test]
    fn test_task_query_builder_new() {
        let builder = TaskQueryBuilder::new();
        let filters = builder.build();

        assert!(filters.status.is_none());
        assert!(filters.task_type.is_none());
        assert!(filters.project_uuid.is_none());
        assert!(filters.area_uuid.is_none());
        assert!(filters.tags.is_none());
        assert!(filters.start_date_from.is_none());
        assert!(filters.start_date_to.is_none());
        assert!(filters.deadline_from.is_none());
        assert!(filters.deadline_to.is_none());
        assert!(filters.search_query.is_none());
        assert!(filters.limit.is_none());
        assert!(filters.offset.is_none());
    }

    #[test]
    fn test_task_query_builder_default() {
        let builder = TaskQueryBuilder::default();
        let filters = builder.build();

        assert!(filters.status.is_none());
        assert!(filters.task_type.is_none());
    }

    #[test]
    fn test_task_query_builder_status() {
        let builder = TaskQueryBuilder::new().status(TaskStatus::Completed);
        let filters = builder.build();

        assert_eq!(filters.status, Some(TaskStatus::Completed));
    }

    #[test]
    fn test_task_query_builder_task_type() {
        let builder = TaskQueryBuilder::new().task_type(TaskType::Project);
        let filters = builder.build();

        assert_eq!(filters.task_type, Some(TaskType::Project));
    }

    #[test]
    fn test_task_query_builder_project_uuid() {
        let uuid = Uuid::new_v4();
        let builder = TaskQueryBuilder::new().project_uuid(uuid);
        let filters = builder.build();

        assert_eq!(filters.project_uuid, Some(uuid));
    }

    #[test]
    fn test_task_query_builder_area_uuid() {
        let uuid = Uuid::new_v4();
        let builder = TaskQueryBuilder::new().area_uuid(uuid);
        let filters = builder.build();

        assert_eq!(filters.area_uuid, Some(uuid));
    }

    #[test]
    fn test_task_query_builder_tags() {
        let tags = vec!["urgent".to_string(), "important".to_string()];
        let builder = TaskQueryBuilder::new().tags(tags.clone());
        let filters = builder.build();

        assert_eq!(filters.tags, Some(tags));
    }

    #[cfg(feature = "advanced-queries")]
    #[test]
    fn test_task_query_builder_any_tags() {
        let tags = vec!["a".to_string(), "b".to_string()];
        let builder = TaskQueryBuilder::new().any_tags(tags.clone());
        assert_eq!(builder.any_tags, Some(tags));
    }

    #[cfg(feature = "advanced-queries")]
    #[test]
    fn test_task_query_builder_exclude_tags() {
        let tags = vec!["archived".to_string()];
        let builder = TaskQueryBuilder::new().exclude_tags(tags.clone());
        assert_eq!(builder.exclude_tags, Some(tags));
    }

    #[cfg(feature = "advanced-queries")]
    #[test]
    fn test_task_query_builder_tag_count() {
        let builder = TaskQueryBuilder::new().tag_count(2);
        assert_eq!(builder.tag_count_min, Some(2));
    }

    #[cfg(feature = "advanced-queries")]
    #[test]
    fn test_task_query_builder_where_expr_setter() {
        use crate::filter_expr::FilterExpr;
        let expr = FilterExpr::status(TaskStatus::Incomplete);
        let builder = TaskQueryBuilder::new().where_expr(expr.clone());
        assert_eq!(builder.where_expr, Some(expr));
    }

    #[cfg(feature = "advanced-queries")]
    #[test]
    fn test_task_query_builder_chaining_tag_methods() {
        let builder = TaskQueryBuilder::new()
            .tags(vec!["a".to_string()])
            .any_tags(vec!["b".to_string(), "c".to_string()])
            .exclude_tags(vec!["d".to_string()])
            .tag_count(1);
        assert_eq!(builder.filters.tags, Some(vec!["a".to_string()]));
        assert_eq!(
            builder.any_tags,
            Some(vec!["b".to_string(), "c".to_string()])
        );
        assert_eq!(builder.exclude_tags, Some(vec!["d".to_string()]));
        assert_eq!(builder.tag_count_min, Some(1));
    }

    #[cfg(feature = "advanced-queries")]
    #[test]
    fn test_fuzzy_search_sets_field() {
        let builder = TaskQueryBuilder::new().fuzzy_search("meeting");
        assert_eq!(builder.fuzzy_query, Some("meeting".to_string()));
    }

    #[cfg(feature = "advanced-queries")]
    #[test]
    fn test_fuzzy_threshold_clamps_low() {
        let builder = TaskQueryBuilder::new().fuzzy_threshold(-0.5);
        assert_eq!(builder.fuzzy_threshold, Some(0.0));
    }

    #[cfg(feature = "advanced-queries")]
    #[test]
    fn test_fuzzy_threshold_clamps_high() {
        let builder = TaskQueryBuilder::new().fuzzy_threshold(1.5);
        assert_eq!(builder.fuzzy_threshold, Some(1.0));
    }

    #[cfg(feature = "advanced-queries")]
    #[test]
    fn test_fuzzy_search_chains_with_other_filters() {
        let builder = TaskQueryBuilder::new()
            .status(TaskStatus::Incomplete)
            .fuzzy_search("agenda")
            .fuzzy_threshold(0.7);
        assert_eq!(builder.fuzzy_query, Some("agenda".to_string()));
        assert_eq!(builder.fuzzy_threshold, Some(0.7));
        assert_eq!(builder.filters.status, Some(TaskStatus::Incomplete));
    }

    #[cfg(feature = "advanced-queries")]
    mod fuzzy_score_tests {
        use super::*;

        #[test]
        fn test_fuzzy_score_substring_short_circuit() {
            assert_eq!(fuzzy_field_score("foo", "blah foo bar"), 1.0);
        }

        #[test]
        fn test_fuzzy_score_typo_above_threshold() {
            let score = fuzzy_field_score("urgent", "urgnt");
            assert!(score >= 0.6, "expected score >= 0.6, got {score}");
        }

        #[test]
        fn test_best_window_score_long_field() {
            let long_field = "alexander needs to buy eggs and milk from the store today";
            let whole = strsim::normalized_levenshtein("alex", long_field) as f32;
            let windowed = best_window_score("alex", long_field);
            assert!(
                windowed > whole,
                "windowed ({windowed}) should beat whole-field ({whole})"
            );
        }

        #[test]
        fn test_task_fuzzy_score_uses_max_of_title_notes() {
            use chrono::Utc;
            use uuid::Uuid;
            let task = crate::models::Task {
                uuid: Uuid::new_v4(),
                title: "unrelated title xyz".to_string(),
                notes: Some("meeting agenda important".to_string()),
                task_type: crate::models::TaskType::Todo,
                status: crate::models::TaskStatus::Incomplete,
                start_date: None,
                deadline: None,
                created: Utc::now(),
                modified: Utc::now(),
                stop_date: None,
                project_uuid: None,
                area_uuid: None,
                parent_uuid: None,
                tags: vec![],
                children: vec![],
            };
            let score = task_fuzzy_score("agenda", &task);
            assert_eq!(score, 1.0, "notes contains 'agenda', score should be 1.0");
        }
    }

    #[cfg(feature = "advanced-queries")]
    mod saved_query_conversion_tests {
        use super::*;

        #[test]
        fn test_to_saved_query_captures_all_state() {
            let from = NaiveDate::from_ymd_opt(2026, 1, 1).unwrap();
            let to = NaiveDate::from_ymd_opt(2026, 12, 31).unwrap();
            let project = Uuid::new_v4();

            let builder = TaskQueryBuilder::new()
                .status(TaskStatus::Incomplete)
                .task_type(TaskType::Todo)
                .project_uuid(project)
                .tags(vec!["work".to_string()])
                .any_tags(vec!["urgent".to_string(), "p0".to_string()])
                .exclude_tags(vec!["archived".to_string()])
                .tag_count(2)
                .fuzzy_search("budget")
                .fuzzy_threshold(0.75)
                .start_date_range(Some(from), Some(to))
                .limit(10)
                .offset(5);

            let saved = builder.to_saved_query("everything");
            assert_eq!(saved.name, "everything");
            assert_eq!(saved.filters.status, Some(TaskStatus::Incomplete));
            assert_eq!(saved.filters.task_type, Some(TaskType::Todo));
            assert_eq!(saved.filters.project_uuid, Some(project));
            assert_eq!(saved.filters.tags, Some(vec!["work".to_string()]));
            assert_eq!(saved.filters.start_date_from, Some(from));
            assert_eq!(saved.filters.limit, Some(10));
            assert_eq!(saved.filters.offset, Some(5));
            assert_eq!(
                saved.any_tags,
                Some(vec!["urgent".to_string(), "p0".to_string()])
            );
            assert_eq!(saved.exclude_tags, Some(vec!["archived".to_string()]));
            assert_eq!(saved.tag_count_min, Some(2));
            assert_eq!(saved.fuzzy_query, Some("budget".to_string()));
            assert_eq!(saved.fuzzy_threshold, Some(0.75));
            assert!(saved.where_expr.is_none());
        }

        #[test]
        fn test_to_saved_query_captures_where_expr() {
            use crate::filter_expr::FilterExpr;
            let expr = FilterExpr::status(TaskStatus::Incomplete)
                .or(FilterExpr::status(TaskStatus::Completed));
            let saved = TaskQueryBuilder::new()
                .where_expr(expr.clone())
                .to_saved_query("with-expr");
            assert_eq!(saved.where_expr, Some(expr));
        }

        #[test]
        fn test_from_saved_query_restores_all_state() {
            let original = TaskQueryBuilder::new()
                .status(TaskStatus::Completed)
                .any_tags(vec!["a".to_string()])
                .fuzzy_search("hello")
                .fuzzy_threshold(0.9)
                .limit(7);
            let saved = original.to_saved_query("test");
            let rebuilt = TaskQueryBuilder::from_saved_query(&saved);

            assert_eq!(rebuilt.filters.status, Some(TaskStatus::Completed));
            assert_eq!(rebuilt.filters.limit, Some(7));
            assert_eq!(rebuilt.any_tags, Some(vec!["a".to_string()]));
            assert_eq!(rebuilt.fuzzy_query, Some("hello".to_string()));
            assert_eq!(rebuilt.fuzzy_threshold, Some(0.9));
        }

        #[test]
        fn test_saved_query_roundtrip_through_json() {
            let original = TaskQueryBuilder::new()
                .status(TaskStatus::Incomplete)
                .any_tags(vec!["x".to_string()])
                .fuzzy_search("foo")
                .fuzzy_threshold(0.5);

            let saved = original.to_saved_query("rt");
            let json = serde_json::to_string(&saved).unwrap();
            let restored: crate::saved_queries::SavedQuery = serde_json::from_str(&json).unwrap();
            let rebuilt = TaskQueryBuilder::from_saved_query(&restored);

            assert_eq!(rebuilt.filters.status, Some(TaskStatus::Incomplete));
            assert_eq!(rebuilt.any_tags, Some(vec!["x".to_string()]));
            assert_eq!(rebuilt.fuzzy_query, Some("foo".to_string()));
            assert_eq!(rebuilt.fuzzy_threshold, Some(0.5));
        }

        #[test]
        fn test_from_saved_query_restores_where_expr_through_json() {
            use crate::filter_expr::FilterExpr;
            let expr = FilterExpr::Or(vec![
                FilterExpr::status(TaskStatus::Incomplete),
                FilterExpr::status(TaskStatus::Completed),
            ])
            .and(FilterExpr::task_type(TaskType::Project).not());

            let saved = TaskQueryBuilder::new()
                .where_expr(expr.clone())
                .to_saved_query("expr-rt");
            let json = serde_json::to_string(&saved).unwrap();
            let restored: crate::saved_queries::SavedQuery = serde_json::from_str(&json).unwrap();
            let rebuilt = TaskQueryBuilder::from_saved_query(&restored);
            assert_eq!(rebuilt.where_expr, Some(expr));
        }
    }

    #[test]
    fn test_task_query_builder_start_date_range() {
        let from = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let to = NaiveDate::from_ymd_opt(2024, 12, 31).unwrap();
        let builder = TaskQueryBuilder::new().start_date_range(Some(from), Some(to));
        let filters = builder.build();

        assert_eq!(filters.start_date_from, Some(from));
        assert_eq!(filters.start_date_to, Some(to));
    }

    #[test]
    fn test_task_query_builder_deadline_range() {
        let from = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let to = NaiveDate::from_ymd_opt(2024, 12, 31).unwrap();
        let builder = TaskQueryBuilder::new().deadline_range(Some(from), Some(to));
        let filters = builder.build();

        assert_eq!(filters.deadline_from, Some(from));
        assert_eq!(filters.deadline_to, Some(to));
    }

    #[test]
    fn test_task_query_builder_search() {
        let query = "test search";
        let builder = TaskQueryBuilder::new().search(query);
        let filters = builder.build();

        assert_eq!(filters.search_query, Some(query.to_string()));
    }

    #[test]
    fn test_task_query_builder_limit() {
        let builder = TaskQueryBuilder::new().limit(50);
        let filters = builder.build();

        assert_eq!(filters.limit, Some(50));
    }

    #[test]
    fn test_task_query_builder_offset() {
        let builder = TaskQueryBuilder::new().offset(10);
        let filters = builder.build();

        assert_eq!(filters.offset, Some(10));
    }

    #[cfg(feature = "advanced-queries")]
    mod execute_tests {
        use super::*;
        use tempfile::NamedTempFile;

        #[tokio::test]
        async fn test_execute_empty_builder() {
            let f = NamedTempFile::new().unwrap();
            crate::test_utils::create_test_database(f.path())
                .await
                .unwrap();
            let db = crate::database::ThingsDatabase::new(f.path())
                .await
                .unwrap();
            let result = TaskQueryBuilder::new().execute(&db).await;
            assert!(result.is_ok());
        }

        #[tokio::test]
        async fn test_execute_with_status_filter() {
            let f = NamedTempFile::new().unwrap();
            crate::test_utils::create_test_database(f.path())
                .await
                .unwrap();
            let db = crate::database::ThingsDatabase::new(f.path())
                .await
                .unwrap();
            let result = TaskQueryBuilder::new()
                .status(TaskStatus::Incomplete)
                .execute(&db)
                .await;
            assert!(result.is_ok());
            assert!(result
                .unwrap()
                .iter()
                .all(|t| t.status == TaskStatus::Incomplete));
        }
    }

    #[test]
    fn test_task_query_builder_chaining() {
        let uuid = Uuid::new_v4();
        let tags = vec!["urgent".to_string()];
        let from = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let to = NaiveDate::from_ymd_opt(2024, 12, 31).unwrap();

        let builder = TaskQueryBuilder::new()
            .status(TaskStatus::Incomplete)
            .task_type(TaskType::Todo)
            .project_uuid(uuid)
            .tags(tags.clone())
            .start_date_range(Some(from), Some(to))
            .search("test")
            .limit(25)
            .offset(5);

        let filters = builder.build();

        assert_eq!(filters.status, Some(TaskStatus::Incomplete));
        assert_eq!(filters.task_type, Some(TaskType::Todo));
        assert_eq!(filters.project_uuid, Some(uuid));
        assert_eq!(filters.tags, Some(tags));
        assert_eq!(filters.start_date_from, Some(from));
        assert_eq!(filters.start_date_to, Some(to));
        assert_eq!(filters.search_query, Some("test".to_string()));
        assert_eq!(filters.limit, Some(25));
        assert_eq!(filters.offset, Some(5));
    }

    mod date_helper_tests {
        use super::*;

        #[test]
        fn test_due_today_sets_deadline_range_to_today() {
            let filters = TaskQueryBuilder::new().due_today().build();
            let today = today();
            assert_eq!(filters.deadline_from, Some(today));
            assert_eq!(filters.deadline_to, Some(today));
        }

        #[test]
        fn test_due_this_week_ends_on_sunday() {
            let filters = TaskQueryBuilder::new().due_this_week().build();
            let today = today();
            assert_eq!(filters.deadline_from, Some(today));
            let to = filters.deadline_to.unwrap();
            assert_eq!(to.weekday(), chrono::Weekday::Sun);
            assert!(to >= today);
        }

        #[test]
        fn test_due_next_week_spans_monday_to_sunday() {
            let filters = TaskQueryBuilder::new().due_next_week().build();
            let from = filters.deadline_from.unwrap();
            let to = filters.deadline_to.unwrap();
            assert_eq!(from.weekday(), chrono::Weekday::Mon);
            assert_eq!(to.weekday(), chrono::Weekday::Sun);
            assert_eq!(to - from, Duration::days(6));
            assert!(from > today());
        }

        #[test]
        fn test_due_in_n_days() {
            let filters = TaskQueryBuilder::new().due_in(7).build();
            let today = today();
            assert_eq!(filters.deadline_from, Some(today));
            assert_eq!(filters.deadline_to, Some(today + Duration::days(7)));
        }

        #[test]
        fn test_due_in_zero_days_is_today() {
            let filters = TaskQueryBuilder::new().due_in(0).build();
            let today = today();
            assert_eq!(filters.deadline_from, Some(today));
            assert_eq!(filters.deadline_to, Some(today));
        }

        #[test]
        fn test_overdue_sets_deadline_to_yesterday_with_no_lower_bound() {
            let filters = TaskQueryBuilder::new().overdue().build();
            let yesterday = today() - Duration::days(1);
            assert_eq!(filters.deadline_from, None);
            assert_eq!(filters.deadline_to, Some(yesterday));
        }

        #[test]
        fn test_overdue_implicitly_sets_status_incomplete_when_unset() {
            let filters = TaskQueryBuilder::new().overdue().build();
            assert_eq!(filters.status, Some(TaskStatus::Incomplete));
        }

        #[test]
        fn test_overdue_does_not_override_explicit_status() {
            let filters = TaskQueryBuilder::new()
                .status(TaskStatus::Canceled)
                .overdue()
                .build();
            assert_eq!(filters.status, Some(TaskStatus::Canceled));
        }

        #[test]
        fn test_starting_today_sets_start_date_range() {
            let filters = TaskQueryBuilder::new().starting_today().build();
            let today = today();
            assert_eq!(filters.start_date_from, Some(today));
            assert_eq!(filters.start_date_to, Some(today));
        }

        #[test]
        fn test_starting_this_week_ends_on_sunday() {
            let filters = TaskQueryBuilder::new().starting_this_week().build();
            let today = today();
            assert_eq!(filters.start_date_from, Some(today));
            let to = filters.start_date_to.unwrap();
            assert_eq!(to.weekday(), chrono::Weekday::Sun);
            assert!(to >= today);
        }

        #[test]
        fn test_end_of_week_on_monday_returns_following_sunday() {
            let monday = NaiveDate::from_ymd_opt(2026, 4, 27).unwrap();
            assert_eq!(monday.weekday(), chrono::Weekday::Mon);
            let eow = end_of_week(monday);
            assert_eq!(eow, NaiveDate::from_ymd_opt(2026, 5, 3).unwrap());
            assert_eq!(eow.weekday(), chrono::Weekday::Sun);
        }

        #[test]
        fn test_end_of_week_on_sunday_returns_same_day() {
            let sunday = NaiveDate::from_ymd_opt(2026, 5, 3).unwrap();
            assert_eq!(sunday.weekday(), chrono::Weekday::Sun);
            assert_eq!(end_of_week(sunday), sunday);
        }
    }
}