Skip to main content

smriti/services/
search.rs

1//! Search service - executes parsed queries against the database.
2
3use std::collections::{BTreeMap, HashMap, HashSet};
4
5use rusqlite::{
6    params, params_from_iter, types::Value, Connection, OptionalExtension, Result as SqliteResult,
7};
8
9use crate::search::date_parser::{DateParser, DateRange};
10use crate::search::SearchQuery;
11
12/// A single search result row.
13#[derive(Debug, Clone)]
14pub struct SearchResult {
15    pub photo_id: i64,
16    pub date_taken: Option<String>,
17    pub location_city: Option<String>,
18    pub location_country: Option<String>,
19    pub thumbnail_path: Option<String>,
20}
21
22/// Search results grouped by date.
23#[allow(dead_code)]
24#[derive(Debug, Clone)]
25pub struct SearchResultGroup {
26    pub date: String,
27    pub location: Option<String>,
28    pub results: Vec<SearchResult>,
29}
30
31/// A person matching the search query.
32#[derive(Debug, Clone)]
33pub struct PersonHit {
34    pub cluster_id: i64,
35    pub name: String,
36    pub photo_count: i64,
37    /// Resolved at load time (absolute path to face crop jpg).
38    pub face_thumbnail_path: Option<String>,
39}
40
41/// An album matching the search query.
42#[derive(Debug, Clone)]
43pub struct AlbumHit {
44    pub album_id: i64,
45    pub name: String,
46    pub photo_count: i64,
47    pub cover_photo_id: Option<i64>,
48    /// Resolved at load time (absolute path to cover thumbnail).
49    pub cover_thumbnail_path: Option<String>,
50}
51
52/// A place (city) matching the search query.
53#[derive(Debug, Clone)]
54pub struct PlaceHit {
55    pub city: String,
56    pub country: Option<String>,
57    pub photo_count: i64,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct InterpretedFilter {
62    pub kind: String,
63    pub label: String,
64}
65
66/// Unified search results across all entity types.
67#[derive(Debug, Clone, Default)]
68pub struct UnifiedSearchResults {
69    pub interpreted: Vec<InterpretedFilter>,
70    pub people: Vec<PersonHit>,
71    pub albums: Vec<AlbumHit>,
72    pub places: Vec<PlaceHit>,
73    pub photos: Vec<SearchResult>,
74    pub photos_grouped: Vec<SearchResultGroup>,
75    /// Flat list for cull mode.
76    pub photo_ids: Vec<i64>,
77    /// True when more photo pages exist beyond this one (keyset/offset
78    /// pagination — see `search_unified_page`).
79    pub has_more: bool,
80}
81
82/// One page of unified search results plus a has-more flag.
83#[derive(Debug, Clone, Default)]
84pub struct UnifiedSearchPage {
85    pub results: UnifiedSearchResults,
86    pub has_more: bool,
87}
88
89/// Search service.
90pub struct SearchService;
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93enum SmartMediaType {
94    Photo,
95    Video,
96}
97
98impl SmartMediaType {
99    fn as_db(self) -> &'static str {
100        match self {
101            Self::Photo => "photo",
102            Self::Video => "video",
103        }
104    }
105
106    fn label(self) -> &'static str {
107        match self {
108            Self::Photo => "Photos",
109            Self::Video => "Videos",
110        }
111    }
112}
113
114#[derive(Debug, Clone)]
115struct ResolvedPerson {
116    id: i64,
117    name: String,
118}
119
120#[derive(Debug, Clone)]
121struct ResolvedAlbum {
122    id: i64,
123    name: String,
124}
125
126/// A city filter. `country` is kept when the city row carried one so
127/// identical city names in different countries stay distinguishable.
128#[derive(Debug, Clone)]
129struct ResolvedCity {
130    city: String,
131    country: Option<String>,
132    label: String,
133}
134
135/// A country filter — resolved from an exact country phrase and never
136/// narrowed to the cities inside it.
137#[derive(Debug, Clone)]
138struct ResolvedCountry {
139    country: String,
140    label: String,
141}
142
143#[derive(Debug, Clone, Default)]
144struct SmartIntent {
145    date_range: Option<DateRange>,
146    text: Option<String>,
147    people_all: Vec<ResolvedPerson>,
148    people_only: bool,
149    cities: Vec<ResolvedCity>,
150    countries: Vec<ResolvedCountry>,
151    albums: Vec<ResolvedAlbum>,
152    favorite: Option<bool>,
153    media_type: Option<SmartMediaType>,
154    semantic_photo_ids: Vec<i64>,
155    /// A `#thing` phrase: photos must look like it.
156    concept: Option<String>,
157    /// `@names` that match no one; the search then finds nothing, and says so.
158    missing_people: Vec<String>,
159}
160
161impl SmartIntent {
162    fn has_structured_filters(&self) -> bool {
163        self.date_range.is_some()
164            || !self.people_all.is_empty()
165            || !self.cities.is_empty()
166            || !self.countries.is_empty()
167            || !self.albums.is_empty()
168            || self.favorite.is_some()
169            || self.media_type.is_some()
170    }
171}
172
173/// Visual search for [`SearchService::search_unified_page_with`]: photo ids
174/// that look like the text, best first, only among the given set if any.
175pub type SemanticLookup<'a> = dyn FnMut(&str, Option<&HashSet<i64>>) -> Vec<i64> + 'a;
176
177impl SearchService {
178    pub fn search(conn: &Connection, query: &SearchQuery) -> SqliteResult<Vec<SearchResult>> {
179        if query.is_empty() {
180            return Ok(Vec::new());
181        }
182
183        let mut sql = String::from(
184            "SELECT id, file_path, date_taken, location_city, location_country, thumbnail_path FROM photos WHERE is_trashed = FALSE",
185        );
186        let mut params_dyn: Vec<String> = Vec::new();
187
188        if let Some(range) = query.date_range() {
189            sql.push_str(" AND date_taken >= ? AND date_taken <= ?");
190            params_dyn.push(range.start.to_rfc3339());
191            params_dyn.push(range.end.to_rfc3339());
192        }
193
194        if let Some(location) = query.location() {
195            sql.push_str(" AND (LOWER(location_city) LIKE LOWER(?) OR LOWER(location_country) LIKE LOWER(?))");
196            let like = format!("%{}%", location);
197            params_dyn.push(like.clone());
198            params_dyn.push(like);
199        }
200
201        sql.push_str(" ORDER BY date_taken DESC LIMIT 1000");
202
203        let mut stmt = conn.prepare(&sql)?;
204
205        let mut rows_vec: Vec<SearchResult> = Vec::new();
206        match params_dyn.len() {
207            0 => {
208                let rows = stmt.query_map([], |row| {
209                    Ok(SearchResult {
210                        photo_id: row.get(0)?,
211                        date_taken: row.get(2)?,
212                        location_city: row.get(3)?,
213                        location_country: row.get(4)?,
214                        thumbnail_path: row.get(5)?,
215                    })
216                })?;
217                for r in rows {
218                    rows_vec.push(r?);
219                }
220            }
221            2 => {
222                let rows = stmt.query_map(params![params_dyn[0], params_dyn[1]], |row| {
223                    Ok(SearchResult {
224                        photo_id: row.get(0)?,
225                        date_taken: row.get(2)?,
226                        location_city: row.get(3)?,
227                        location_country: row.get(4)?,
228                        thumbnail_path: row.get(5)?,
229                    })
230                })?;
231                for r in rows {
232                    rows_vec.push(r?);
233                }
234            }
235            4 => {
236                let rows = stmt.query_map(
237                    params![params_dyn[0], params_dyn[1], params_dyn[2], params_dyn[3]],
238                    |row| {
239                        Ok(SearchResult {
240                            photo_id: row.get(0)?,
241                            date_taken: row.get(2)?,
242                            location_city: row.get(3)?,
243                            location_country: row.get(4)?,
244                            thumbnail_path: row.get(5)?,
245                        })
246                    },
247                )?;
248                for r in rows {
249                    rows_vec.push(r?);
250                }
251            }
252            _ => {
253                let rows = stmt.query_map(
254                    params![
255                        params_dyn[0],
256                        params_dyn[1],
257                        params_dyn[2],
258                        params_dyn[3],
259                        params_dyn[4],
260                        params_dyn[5]
261                    ],
262                    |row| {
263                        Ok(SearchResult {
264                            photo_id: row.get(0)?,
265                            date_taken: row.get(2)?,
266                            location_city: row.get(3)?,
267                            location_country: row.get(4)?,
268                            thumbnail_path: row.get(5)?,
269                        })
270                    },
271                )?;
272                for r in rows {
273                    rows_vec.push(r?);
274                }
275            }
276        }
277
278        if let Some(person_name) = query.person() {
279            rows_vec = Self::filter_by_person(conn, rows_vec, person_name)?;
280        }
281
282        Ok(rows_vec)
283    }
284
285    fn filter_by_person(
286        conn: &Connection,
287        results: Vec<SearchResult>,
288        person_name: &str,
289    ) -> SqliteResult<Vec<SearchResult>> {
290        let mut stmt = conn.prepare(
291            r#"
292            SELECT DISTINCT photo_id FROM (
293                SELECT f.photo_id AS photo_id
294                FROM faces f
295                JOIN face_clusters fc ON f.cluster_id = fc.id
296                WHERE fc.name IS NOT NULL AND LOWER(fc.name) LIKE LOWER(?1)
297
298                UNION
299
300                SELECT pii.photo_id AS photo_id
301                FROM photo_inferred_identities pii
302                JOIN face_clusters fc ON pii.cluster_id = fc.id
303                WHERE fc.name IS NOT NULL AND LOWER(fc.name) LIKE LOWER(?1)
304            )
305            "#,
306        )?;
307
308        let ids: HashSet<i64> = stmt
309            .query_map(params![format!("%{}%", person_name)], |row| row.get(0))?
310            .collect::<SqliteResult<HashSet<_>>>()?;
311
312        Ok(results
313            .into_iter()
314            .filter(|r| ids.contains(&r.photo_id))
315            .collect())
316    }
317
318    pub fn group_by_date(results: Vec<SearchResult>) -> Vec<SearchResultGroup> {
319        let mut groups: BTreeMap<String, Vec<SearchResult>> = BTreeMap::new();
320
321        for result in results {
322            let date = result
323                .date_taken
324                .as_ref()
325                .and_then(|d| d.get(..10))
326                .unwrap_or("Unknown")
327                .to_string();
328
329            groups.entry(date).or_default().push(result);
330        }
331
332        groups
333            .into_iter()
334            .rev()
335            .map(|(date, results)| {
336                let location = results.iter().find_map(|r| {
337                    r.location_city
338                        .clone()
339                        .or_else(|| r.location_country.clone())
340                });
341
342                SearchResultGroup {
343                    date,
344                    location,
345                    results,
346                }
347            })
348            .collect()
349    }
350
351    /// Remember a search the user settled on (pressed Enter, opened a
352    /// result), for the recent list. Typing alone never adds one.
353    pub fn remember_query(conn: &Connection, query: &str) -> SqliteResult<()> {
354        let query = query.split_whitespace().collect::<Vec<_>>().join(" ");
355        if query.is_empty() {
356            return Ok(());
357        }
358        // Re-added as the newest row, so the list's order is the row order
359        // and never depends on how finely the clock ticks.
360        let uses: i64 = conn
361            .query_row(
362                "SELECT use_count FROM recent_searches WHERE query = ?1",
363                params![query],
364                |row| row.get(0),
365            )
366            .optional()?
367            .unwrap_or(0);
368        conn.execute(
369            "DELETE FROM recent_searches WHERE query = ?1",
370            params![query],
371        )?;
372        conn.execute(
373            "INSERT INTO recent_searches (query, use_count) VALUES (?1, ?2)",
374            params![query, uses + 1],
375        )?;
376        conn.execute(
377            "DELETE FROM recent_searches WHERE id NOT IN
378               (SELECT id FROM recent_searches ORDER BY id DESC LIMIT ?1)",
379            params![Self::RECENT_KEPT as i64],
380        )?;
381        Ok(())
382    }
383
384    /// The latest remembered searches, newest first.
385    pub fn recent_queries(conn: &Connection, limit: usize) -> SqliteResult<Vec<String>> {
386        let mut stmt =
387            conn.prepare("SELECT query FROM recent_searches ORDER BY id DESC LIMIT ?1")?;
388        let rows = stmt.query_map(params![limit as i64], |row| row.get(0))?;
389        rows.collect()
390    }
391
392    pub fn clear_recent(conn: &Connection) -> SqliteResult<()> {
393        conn.execute("DELETE FROM recent_searches", [])?;
394        Ok(())
395    }
396
397    /// Searches the user pinned, in the order they pinned them. Kept in the
398    /// library, so they travel with it; clearing recent searches keeps them.
399    pub fn pinned_queries(conn: &Connection) -> SqliteResult<Vec<String>> {
400        let raw: Option<String> = conn
401            .query_row(
402                "SELECT value FROM library_meta WHERE key = 'search.pinned'",
403                [],
404                |row| row.get(0),
405            )
406            .optional()?;
407        Ok(raw
408            .and_then(|s| serde_json::from_str(&s).ok())
409            .unwrap_or_default())
410    }
411
412    /// Pin or unpin a search. Pinning one already pinned changes nothing.
413    pub fn set_pinned(conn: &Connection, query: &str, pinned: bool) -> SqliteResult<()> {
414        let query = query.split_whitespace().collect::<Vec<_>>().join(" ");
415        if query.is_empty() {
416            return Ok(());
417        }
418        let mut list = Self::pinned_queries(conn)?;
419        list.retain(|q| q != &query);
420        if pinned {
421            list.push(query);
422            let excess = list.len().saturating_sub(Self::PINNED_KEPT);
423            list.drain(..excess);
424        }
425        conn.execute(
426            "INSERT INTO library_meta (key, value) VALUES ('search.pinned', ?1)
427             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
428            params![serde_json::to_string(&list).unwrap_or_else(|_| "[]".into())],
429        )?;
430        Ok(())
431    }
432
433    const RECENT_KEPT: usize = 50;
434    const PINNED_KEPT: usize = 12;
435
436    /// Run a unified multi-entity search.
437    ///
438    /// The query string is parsed once via `QueryParser`; people/album/place
439    /// matches use simple substring LIKE. Photos use the existing
440    /// QueryParser-based filter.
441    pub fn search_unified(
442        conn: &Connection,
443        raw_query: &str,
444    ) -> SqliteResult<UnifiedSearchResults> {
445        Self::search_unified_with_semantic(conn, raw_query, Vec::new())
446    }
447
448    /// First page (legacy shape: up to 1000 photos) — kept for callers
449    /// that have not moved to `search_unified_page` yet.
450    pub fn search_unified_with_semantic(
451        conn: &Connection,
452        raw_query: &str,
453        semantic_photo_ids: Vec<i64>,
454    ) -> SqliteResult<UnifiedSearchResults> {
455        Ok(Self::search_unified_page(
456            conn,
457            raw_query,
458            semantic_photo_ids,
459            0,
460            Self::UNIFIED_SEARCH_MAX_PHOTOS,
461        )?
462        .results)
463    }
464
465    /// One page of unified results. `offset`/`limit` page the photo
466    /// list; people/albums/places hits are query-wide and identical on
467    /// every page. Ordering is stable (`date_taken DESC, id DESC`, or
468    /// semantic rank first when semantic candidates are supplied), so
469    /// concatenated pages never duplicate or skip a photo.
470    pub fn search_unified_page(
471        conn: &Connection,
472        raw_query: &str,
473        semantic_photo_ids: Vec<i64>,
474        offset: usize,
475        limit: usize,
476    ) -> SqliteResult<UnifiedSearchPage> {
477        let query = raw_query.trim();
478        if query.is_empty() {
479            return Ok(UnifiedSearchPage::default());
480        }
481        let mut intent = Self::parse_smart_intent(conn, query)?;
482        intent.semantic_photo_ids = semantic_photo_ids;
483        Self::finish_page(conn, query, intent, offset, limit)
484    }
485
486    /// One page of results, with visual search supplied by the caller:
487    /// `semantic(text, within)` returns the photos that look like `text`,
488    /// best first, only among `within` when given. It's asked only about
489    /// what the query leaves once people, places, dates and the like are
490    /// taken out (never about names), and not at all when nothing is left.
491    /// With filters, similarity is scored among the photos that pass them,
492    /// so "Dad and Mom food" isn't limited to the library's top food photos.
493    pub fn search_unified_page_with(
494        conn: &Connection,
495        raw_query: &str,
496        semantic: &mut SemanticLookup<'_>,
497        offset: usize,
498        limit: usize,
499    ) -> SqliteResult<UnifiedSearchPage> {
500        let query = raw_query.trim();
501        if query.is_empty() {
502            return Ok(UnifiedSearchPage::default());
503        }
504        let mut intent = Self::parse_smart_intent(conn, query)?;
505        let wanted = intent.concept.clone().or_else(|| intent.text.clone());
506        if let (Some(text), true) = (wanted, intent.missing_people.is_empty()) {
507            let within = if intent.has_structured_filters() {
508                let mut base = intent.clone();
509                base.text = None;
510                base.concept = None;
511                let (rows, _) =
512                    Self::search_smart_photos(conn, &base, 0, Self::UNIFIED_SEARCH_MAX_PHOTOS)?;
513                Some(rows.into_iter().map(|r| r.photo_id).collect::<HashSet<_>>())
514            } else {
515                None
516            };
517            if within.as_ref().is_none_or(|w| !w.is_empty()) {
518                intent.semantic_photo_ids = semantic(&text, within.as_ref());
519            }
520        }
521        Self::finish_page(conn, query, intent, offset, limit)
522    }
523
524    fn finish_page(
525        conn: &Connection,
526        query: &str,
527        intent: SmartIntent,
528        offset: usize,
529        limit: usize,
530    ) -> SqliteResult<UnifiedSearchPage> {
531        let mut results = UnifiedSearchResults {
532            interpreted: Self::interpreted_filters(&intent),
533            // Entity hit lists are query-wide and identical on every
534            // page — only `photos` is paged.
535            people: Self::search_people(conn, query)?,
536            albums: Self::search_albums(conn, query)?,
537            places: Self::search_places(conn, query)?,
538            ..Default::default()
539        };
540
541        let (photos, has_more) = Self::search_smart_photos(conn, &intent, offset, limit)?;
542
543        results.photo_ids = photos.iter().map(|r| r.photo_id).collect();
544        results.photos_grouped = Self::group_by_date(photos.clone());
545        results.photos = photos;
546        results.has_more = has_more;
547
548        Ok(UnifiedSearchPage { results, has_more })
549    }
550
551    fn parse_smart_intent(conn: &Connection, raw: &str) -> SqliteResult<SmartIntent> {
552        let (text_part, date_range) = Self::split_query(raw);
553        let mut text = text_part.unwrap_or_default();
554        let mut intent = SmartIntent {
555            date_range,
556            ..Default::default()
557        };
558        let mut lower = text.to_lowercase();
559
560        if let Some(rest) = lower
561            .strip_prefix("only ")
562            .or_else(|| lower.strip_prefix("just "))
563        {
564            intent.people_only = true;
565            text = text[text.len() - rest.len()..].trim().to_string();
566            lower = text.to_lowercase();
567        }
568
569        // `@Name` people first, so their names never reach the word rules.
570        if text.contains('@') {
571            text = Self::take_explicit_people(conn, &text, &mut intent)?;
572            lower = text.to_lowercase();
573        }
574
575        for (needle, media) in [
576            ("videos", SmartMediaType::Video),
577            ("video", SmartMediaType::Video),
578            ("photos", SmartMediaType::Photo),
579            ("photo", SmartMediaType::Photo),
580        ] {
581            if Self::contains_word(&lower, needle) {
582                intent.media_type = Some(media);
583                text = Self::remove_word(&text, needle);
584                lower = text.to_lowercase();
585                break;
586            }
587        }
588
589        for needle in [
590            "favourites",
591            "favorites",
592            "favourite",
593            "favorite",
594            "starred",
595        ] {
596            if Self::contains_word(&lower, needle) {
597                intent.favorite = Some(true);
598                text = Self::remove_word(&text, needle);
599                lower = text.to_lowercase();
600                break;
601            }
602        }
603
604        // A `#thing` phrase runs to the next `#`; the words the rules above
605        // understood ("videos", "favourites") are already out of it.
606        if let Some(at) = text.find('#') {
607            let (before, phrase) = text.split_at(at);
608            let words: Vec<String> = phrase
609                .split('#')
610                .map(|part| part.split_whitespace().collect::<Vec<_>>().join(" "))
611                .filter(|part| !part.is_empty())
612                .collect();
613            if !words.is_empty() {
614                intent.concept = Some(words.join(" "));
615            }
616            text = before.trim().to_string();
617            lower = text.to_lowercase();
618        }
619
620        let album_phrase = if let Some(rest) = lower.strip_prefix("album ") {
621            Some(text[text.len() - rest.len()..].trim().to_string())
622        } else {
623            lower
624                .strip_prefix("in album ")
625                .map(|rest| text[text.len() - rest.len()..].trim().to_string())
626        };
627        if let Some(album_query) = album_phrase.as_deref() {
628            intent.albums = Self::resolve_albums(conn, album_query)?;
629            if !intent.albums.is_empty() {
630                text.clear();
631            }
632        }
633
634        let mut remaining = text.trim().to_string();
635        if !remaining.is_empty() {
636            let people = Self::resolve_people(conn, &remaining)?;
637            if !people.is_empty() {
638                remaining =
639                    Self::remove_entity_names(&remaining, people.iter().map(|p| p.name.as_str()));
640                for person in people {
641                    if !intent.people_all.iter().any(|p| p.id == person.id) {
642                        intent.people_all.push(person);
643                    }
644                }
645            }
646        }
647
648        if !remaining.trim().is_empty() {
649            let cities = Self::resolve_cities(conn, remaining.trim())?;
650            if !cities.is_empty() {
651                remaining =
652                    Self::remove_entity_names(&remaining, cities.iter().map(|c| c.city.as_str()));
653                intent.cities = cities;
654            }
655        }
656
657        if !remaining.trim().is_empty() {
658            let countries = Self::resolve_countries(conn, remaining.trim())?;
659            if !countries.is_empty() {
660                remaining = Self::remove_entity_names(
661                    &remaining,
662                    countries.iter().map(|c| c.country.as_str()),
663                );
664                intent.countries = countries;
665            }
666        }
667
668        let cleanup = remaining
669            .split_whitespace()
670            .filter(|w| {
671                // Punctuation-only leftovers (e.g. the comma from
672                // "Delhi, India") are not meaningful text filters.
673                w.chars().any(char::is_alphanumeric)
674                    && !matches!(
675                        w.to_lowercase().as_str(),
676                        "and"
677                            | "&"
678                            | "with"
679                            | "in"
680                            | "at"
681                            | "from"
682                            | "person"
683                            | "people"
684                            | "containing"
685                    )
686            })
687            .collect::<Vec<_>>()
688            .join(" ");
689        if !cleanup.trim().is_empty() {
690            intent.text = Some(cleanup.trim().to_string());
691        }
692        Ok(intent)
693    }
694
695    fn interpreted_filters(intent: &SmartIntent) -> Vec<InterpretedFilter> {
696        let mut out = Vec::new();
697        if intent.people_only {
698            out.push(InterpretedFilter {
699                kind: "only".into(),
700                label: "Only".into(),
701            });
702        }
703        for p in &intent.people_all {
704            out.push(InterpretedFilter {
705                kind: "person".into(),
706                label: p.name.clone(),
707            });
708        }
709        for c in &intent.cities {
710            out.push(InterpretedFilter {
711                kind: "place".into(),
712                label: c.label.clone(),
713            });
714        }
715        for c in &intent.countries {
716            out.push(InterpretedFilter {
717                kind: "place".into(),
718                label: c.label.clone(),
719            });
720        }
721        for a in &intent.albums {
722            out.push(InterpretedFilter {
723                kind: "album".into(),
724                label: a.name.clone(),
725            });
726        }
727        if let Some(media) = intent.media_type {
728            out.push(InterpretedFilter {
729                kind: "media".into(),
730                label: media.label().into(),
731            });
732        }
733        if intent.favorite == Some(true) {
734            out.push(InterpretedFilter {
735                kind: "favorite".into(),
736                label: "Favourites".into(),
737            });
738        }
739        if let Some(range) = &intent.date_range {
740            out.push(InterpretedFilter {
741                kind: "date".into(),
742                label: Self::date_label(range),
743            });
744        }
745        for name in &intent.missing_people {
746            out.push(InterpretedFilter {
747                kind: "missing".into(),
748                label: format!("No one called {name}"),
749            });
750        }
751        if let Some(concept) = &intent.concept {
752            out.push(InterpretedFilter {
753                kind: "semantic".into(),
754                label: concept.clone(),
755            });
756        }
757        if let Some(text) = &intent.text {
758            if intent.semantic_photo_ids.is_empty() || intent.concept.is_some() {
759                out.push(InterpretedFilter {
760                    kind: "text".into(),
761                    label: text.clone(),
762                });
763            } else {
764                out.push(InterpretedFilter {
765                    kind: "semantic".into(),
766                    label: text.clone(),
767                });
768            }
769        } else if intent.concept.is_none() && !intent.semantic_photo_ids.is_empty() {
770            out.push(InterpretedFilter {
771                kind: "semantic".into(),
772                label: "Visual meaning".into(),
773            });
774        }
775        out
776    }
777
778    /// Peel a date range off the end (or whole) of `q` and return
779    /// (remaining_text, date_range). Either component may be None.
780    fn split_query(q: &str) -> (Option<String>, Option<DateRange>) {
781        let trimmed = q.trim();
782        if trimmed.is_empty() {
783            return (None, None);
784        }
785        // Whole-string match first — "March 2019" → date only.
786        if let Some(range) = DateParser::parse(trimmed) {
787            return (None, Some(range));
788        }
789        let words: Vec<&str> = trimmed.split_whitespace().collect();
790        // Try any two-word date span first — "Goa March 2019 videos",
791        // "March 2019 Goa", "last year Paris".
792        if words.len() >= 2 {
793            for i in 0..(words.len() - 1) {
794                let candidate = format!("{} {}", words[i], words[i + 1]);
795                if let Some(range) = DateParser::parse(&candidate) {
796                    let rest = words
797                        .iter()
798                        .enumerate()
799                        .filter_map(|(idx, word)| {
800                            if idx == i || idx == i + 1 {
801                                None
802                            } else {
803                                Some(*word)
804                            }
805                        })
806                        .collect::<Vec<_>>()
807                        .join(" ");
808                    let rest = rest.trim().to_string();
809                    return (if rest.is_empty() { None } else { Some(rest) }, Some(range));
810                }
811            }
812        }
813        // Try any one-word date span — "2023 Goa", "Goa 2023",
814        // "videos 2023 Goa".
815        for i in 0..words.len() {
816            if let Some(range) = DateParser::parse(words[i]) {
817                let rest = words
818                    .iter()
819                    .enumerate()
820                    .filter_map(|(idx, word)| if idx == i { None } else { Some(*word) })
821                    .collect::<Vec<_>>()
822                    .join(" ");
823                let rest = rest.trim().to_string();
824                return (if rest.is_empty() { None } else { Some(rest) }, Some(range));
825            }
826        }
827        (Some(trimmed.to_string()), None)
828    }
829
830    /// Upper bound on photos a single legacy (non-paged) unified search
831    /// returns, and the safety cap the semantic path ranks within.
832    /// Hard product ceiling for one query. Callers may page below this
833    /// boundary, but no page can expose or request a result beyond it.
834    pub const UNIFIED_SEARCH_MAX_PHOTOS: usize = 20_000;
835
836    /// Safety cap on rows fetched for semantic ranking. Ranking happens
837    /// in Rust (candidate order first), so pages must come out of one
838    /// globally-ordered list; the cap bounds that work.
839    const SEMANTIC_FETCH_CAP: usize = 20_000;
840
841    /// Returns (page_rows, has_more).
842    fn search_smart_photos(
843        conn: &Connection,
844        intent: &SmartIntent,
845        offset: usize,
846        limit: usize,
847    ) -> SqliteResult<(Vec<SearchResult>, bool)> {
848        if !intent.missing_people.is_empty() {
849            return Ok((Vec::new(), false));
850        }
851        let mut sql = String::from(
852            "SELECT p.id, p.date_taken, p.location_city, p.location_country, p.thumbnail_path \
853             FROM photos p WHERE p.is_trashed = FALSE",
854        );
855        let mut bind: Vec<Value> = Vec::new();
856        if intent.concept.is_some() {
857            // Asked for by name: the photo has to look like it.
858            if intent.semantic_photo_ids.is_empty() {
859                sql.push_str(" AND 0");
860            } else {
861                sql.push_str(" AND p.id IN (SELECT value FROM json_each(?))");
862                bind.push(Value::Text(
863                    serde_json::to_string(&intent.semantic_photo_ids).unwrap_or_default(),
864                ));
865            }
866        }
867
868        if let Some(d) = &intent.date_range {
869            sql.push_str(" AND p.date_taken >= ? AND p.date_taken <= ?");
870            bind.push(Value::Text(d.start.to_rfc3339()));
871            bind.push(Value::Text(d.end.to_rfc3339()));
872        }
873        if let Some(media) = intent.media_type {
874            sql.push_str(" AND p.media_type = ?");
875            bind.push(Value::Text(media.as_db().to_string()));
876        }
877        if intent.favorite == Some(true) {
878            sql.push_str(" AND p.is_favorite = TRUE");
879        }
880        for album in &intent.albums {
881            sql.push_str(
882                " AND EXISTS (SELECT 1 FROM album_photos ap WHERE ap.photo_id = p.id AND ap.album_id = ?)",
883            );
884            bind.push(Value::Integer(album.id));
885        }
886        // Cities are alternatives (a photo is in one place at a time):
887        // any one of the resolved cities may match. A city keeps its
888        // country when known, so identical city names in different
889        // countries stay distinguishable.
890        if !intent.cities.is_empty() {
891            let arms = intent
892                .cities
893                .iter()
894                .map(|c| match &c.country {
895                    Some(_) => {
896                        "(LOWER(p.location_city) LIKE LOWER(?) \
897                                AND LOWER(p.location_country) LIKE LOWER(?))"
898                    }
899                    None => "LOWER(p.location_city) LIKE LOWER(?)",
900                })
901                .collect::<Vec<_>>()
902                .join(" OR ");
903            sql.push_str(&format!(" AND ({arms})"));
904            for city in &intent.cities {
905                bind.push(Value::Text(format!("%{}%", city.city)));
906                if let Some(country) = &city.country {
907                    bind.push(Value::Text(format!("%{}%", country)));
908                }
909            }
910        }
911        // Countries likewise OR together; a country predicate matches
912        // every city inside the country (never narrowed to one city).
913        if !intent.countries.is_empty() {
914            let arms = std::iter::repeat_n(
915                "LOWER(p.location_country) LIKE LOWER(?)",
916                intent.countries.len(),
917            )
918            .collect::<Vec<_>>()
919            .join(" OR ");
920            sql.push_str(&format!(" AND ({arms})"));
921            for country in &intent.countries {
922                bind.push(Value::Text(format!("%{}%", country.country)));
923            }
924        }
925        for person in &intent.people_all {
926            sql.push_str(
927                " AND (EXISTS (
928                    SELECT 1 FROM faces f
929                    WHERE f.photo_id = p.id AND f.cluster_id = ?
930                ) OR EXISTS (
931                    SELECT 1 FROM photo_inferred_identities pii
932                    WHERE pii.photo_id = p.id AND pii.cluster_id = ?
933                ))",
934            );
935            bind.push(Value::Integer(person.id));
936            bind.push(Value::Integer(person.id));
937        }
938        if intent.people_only && !intent.people_all.is_empty() {
939            sql.push_str(" AND p.faces_processed = TRUE");
940            let placeholders = std::iter::repeat_n("?", intent.people_all.len())
941                .collect::<Vec<_>>()
942                .join(",");
943            sql.push_str(&format!(
944                " AND NOT EXISTS (
945                    SELECT 1 FROM faces f
946                    WHERE f.photo_id = p.id
947                      AND (f.cluster_id IS NULL OR f.cluster_id NOT IN ({placeholders}))
948                )"
949            ));
950            for person in &intent.people_all {
951                bind.push(Value::Integer(person.id));
952            }
953            sql.push_str(&format!(
954                " AND NOT EXISTS (
955                    SELECT 1 FROM photo_inferred_identities pii
956                    WHERE pii.photo_id = p.id AND pii.cluster_id NOT IN ({placeholders})
957                )"
958            ));
959            for person in &intent.people_all {
960                bind.push(Value::Integer(person.id));
961            }
962        }
963        if let Some(t) = &intent.text {
964            // Without a `#thing`, leftover words may also be a file name, a
965            // camera or a place the parser didn't know, so a visual match
966            // is one way in among those, not a requirement.
967            let semantic_ids: &[i64] = if intent.concept.is_some() {
968                &[]
969            } else {
970                &intent.semantic_photo_ids
971            };
972            let semantic_clause = if semantic_ids.is_empty() {
973                String::new()
974            } else {
975                " OR p.id IN (SELECT value FROM json_each(?))".to_string()
976            };
977            sql.push_str(&format!(
978                " AND (
979                    LOWER(p.file_name) LIKE LOWER(?) OR
980                    LOWER(p.location_city) LIKE LOWER(?) OR
981                    LOWER(p.location_country) LIKE LOWER(?) OR
982                    LOWER(p.camera_make) LIKE LOWER(?) OR
983                    LOWER(p.camera_model) LIKE LOWER(?) OR
984                    LOWER(COALESCE(p.camera_make, '') || ' ' || COALESCE(p.camera_model, '')) LIKE LOWER(?) OR
985                    EXISTS (
986                        SELECT 1
987                        FROM faces f
988                        JOIN face_clusters fc ON fc.id = f.cluster_id
989                        WHERE f.photo_id = p.id AND LOWER(fc.name) LIKE LOWER(?)
990                    ) OR
991                    EXISTS (
992                        SELECT 1
993                        FROM photo_inferred_identities pii
994                        JOIN face_clusters fc ON fc.id = pii.cluster_id
995                        WHERE pii.photo_id = p.id AND LOWER(fc.name) LIKE LOWER(?)
996                    )
997                    {semantic_clause}
998                )",
999            ));
1000            let like = Value::Text(format!("%{}%", t));
1001            for _ in 0..8 {
1002                bind.push(like.clone());
1003            }
1004            if !semantic_ids.is_empty() {
1005                // One JSON parameter, however many ids: a filtered set can be
1006                // thousands, past SQLite's limit on parameters.
1007                bind.push(Value::Text(
1008                    serde_json::to_string(semantic_ids).unwrap_or_default(),
1009                ));
1010            }
1011        } else if intent.concept.is_none()
1012            && !intent.semantic_photo_ids.is_empty()
1013            && !intent.has_structured_filters()
1014        {
1015            sql.push_str(" AND p.id IN (SELECT value FROM json_each(?))");
1016            bind.push(Value::Text(
1017                serde_json::to_string(&intent.semantic_photo_ids).unwrap_or_default(),
1018            ));
1019        }
1020
1021        if intent.semantic_photo_ids.is_empty() {
1022            // Pure SQL ordering is stable, so offset paging can be done
1023            // entirely in SQLite. One extra row detects has_more.
1024            let remaining = Self::UNIFIED_SEARCH_MAX_PHOTOS.saturating_sub(offset);
1025            let page_limit = limit.min(remaining);
1026            sql.push_str(&format!(
1027                " ORDER BY p.date_taken DESC, p.id DESC LIMIT {} OFFSET {}",
1028                page_limit.saturating_add(1),
1029                offset
1030            ));
1031            let mut stmt = conn.prepare(&sql)?;
1032            let rows = stmt.query_map(params_from_iter(bind.iter()), |row| {
1033                Ok(SearchResult {
1034                    photo_id: row.get(0)?,
1035                    date_taken: row.get(1)?,
1036                    location_city: row.get(2)?,
1037                    location_country: row.get(3)?,
1038                    thumbnail_path: row.get(4)?,
1039                })
1040            })?;
1041            let mut results = rows.collect::<SqliteResult<Vec<_>>>()?;
1042            let has_more =
1043                results.len() > page_limit && offset + page_limit < Self::UNIFIED_SEARCH_MAX_PHOTOS;
1044            results.truncate(page_limit);
1045            Ok((results, has_more))
1046        } else {
1047            // Semantic ranking is computed in Rust over the candidate
1048            // order, so all matching rows are fetched up to a safety
1049            // cap and paged from the globally-ranked list. This keeps
1050            // ranking stable across pages.
1051            sql.push_str(&format!(
1052                " ORDER BY p.date_taken DESC, p.id DESC LIMIT {}",
1053                Self::SEMANTIC_FETCH_CAP
1054            ));
1055            let mut stmt = conn.prepare(&sql)?;
1056            let rows = stmt.query_map(params_from_iter(bind.iter()), |row| {
1057                Ok(SearchResult {
1058                    photo_id: row.get(0)?,
1059                    date_taken: row.get(1)?,
1060                    location_city: row.get(2)?,
1061                    location_country: row.get(3)?,
1062                    thumbnail_path: row.get(4)?,
1063                })
1064            })?;
1065            let mut results = rows.collect::<SqliteResult<Vec<_>>>()?;
1066            let rank: HashMap<i64, usize> = intent
1067                .semantic_photo_ids
1068                .iter()
1069                .enumerate()
1070                .map(|(idx, id)| (*id, idx))
1071                .collect();
1072            results.sort_by(
1073                |a, b| match (rank.get(&a.photo_id), rank.get(&b.photo_id)) {
1074                    (Some(ra), Some(rb)) => ra.cmp(rb),
1075                    (Some(_), None) => std::cmp::Ordering::Less,
1076                    (None, Some(_)) => std::cmp::Ordering::Greater,
1077                    (None, None) => b
1078                        .date_taken
1079                        .cmp(&a.date_taken)
1080                        .then(b.photo_id.cmp(&a.photo_id)),
1081                },
1082            );
1083            let page_limit = limit.min(Self::UNIFIED_SEARCH_MAX_PHOTOS.saturating_sub(offset));
1084            let has_more = offset + page_limit < results.len()
1085                && offset + page_limit < Self::UNIFIED_SEARCH_MAX_PHOTOS;
1086            let page: Vec<SearchResult> =
1087                results.into_iter().skip(offset).take(page_limit).collect();
1088            Ok((page, has_more))
1089        }
1090    }
1091
1092    /// Take `@Name` people out of `text`. A name matches whole and
1093    /// case-insensitively, the longest one that fits, so `@Uncle Raju`
1094    /// needs no quotes; `@"..."` is accepted too. A name nobody has is
1095    /// recorded as missing. Returns the text without them.
1096    fn take_explicit_people(
1097        conn: &Connection,
1098        text: &str,
1099        intent: &mut SmartIntent,
1100    ) -> SqliteResult<String> {
1101        let mut stmt = conn.prepare(
1102            "SELECT id, name FROM face_clusters
1103             WHERE name IS NOT NULL AND trim(name) != ''
1104             ORDER BY length(name) DESC, photo_count DESC",
1105        )?;
1106        let named: Vec<ResolvedPerson> = stmt
1107            .query_map([], |row| {
1108                Ok(ResolvedPerson {
1109                    id: row.get(0)?,
1110                    name: row.get(1)?,
1111                })
1112            })?
1113            .collect::<SqliteResult<_>>()?;
1114
1115        let mut rest = String::with_capacity(text.len());
1116        let mut tail = text;
1117        while let Some(at) = tail.find('@') {
1118            rest.push_str(&tail[..at]);
1119            let after = &tail[at + 1..];
1120            let (wanted, used) = match after.strip_prefix('"') {
1121                Some(quoted) => {
1122                    let end = quoted.find('"').unwrap_or(quoted.len());
1123                    (Some(quoted[..end].trim()), 1 + (end + 1).min(quoted.len()))
1124                }
1125                None => (None, 0),
1126            };
1127            let found = match wanted {
1128                Some(name) => named
1129                    .iter()
1130                    .find(|p| p.name.trim().eq_ignore_ascii_case(name) || p.name.trim() == name)
1131                    .map(|p| (p, used)),
1132                None => named.iter().find_map(|p| {
1133                    let len = Self::name_prefix_len(after, p.name.trim())?;
1134                    Some((p, len))
1135                }),
1136            };
1137            match found {
1138                Some((person, len)) => {
1139                    if !intent.people_all.iter().any(|p| p.id == person.id) {
1140                        intent.people_all.push(person.clone());
1141                    }
1142                    tail = &after[len..];
1143                }
1144                None => {
1145                    let len = if used > 0 {
1146                        used
1147                    } else {
1148                        after.find(char::is_whitespace).unwrap_or(after.len())
1149                    };
1150                    let word = wanted.map(str::to_string).unwrap_or_else(|| {
1151                        after[..len]
1152                            .trim_matches(|c: char| !c.is_alphanumeric())
1153                            .to_string()
1154                    });
1155                    if !word.is_empty() {
1156                        intent.missing_people.push(word);
1157                    }
1158                    tail = &after[len..];
1159                }
1160            }
1161            rest.push(' ');
1162        }
1163        rest.push_str(tail);
1164        Ok(rest.split_whitespace().collect::<Vec<_>>().join(" "))
1165    }
1166
1167    /// Bytes of `text` taken by `name` at its start, ignoring case, when the
1168    /// name ends on a word boundary there.
1169    fn name_prefix_len(text: &str, name: &str) -> Option<usize> {
1170        if name.is_empty() {
1171            return None;
1172        }
1173        let mut t = text.char_indices();
1174        let mut end = 0;
1175        for n in name.chars() {
1176            let (i, c) = t.next()?;
1177            if !c.to_lowercase().eq(n.to_lowercase()) {
1178                return None;
1179            }
1180            end = i + c.len_utf8();
1181        }
1182        match text[end..].chars().next() {
1183            Some(c) if c.is_alphanumeric() => None,
1184            _ => Some(end),
1185        }
1186    }
1187
1188    fn resolve_people(conn: &Connection, text: &str) -> SqliteResult<Vec<ResolvedPerson>> {
1189        let mut stmt = conn.prepare(
1190            "SELECT id, name FROM face_clusters
1191             WHERE name IS NOT NULL AND trim(name) != ''
1192             ORDER BY length(name) DESC, photo_count DESC",
1193        )?;
1194        let rows = stmt.query_map([], |row| {
1195            Ok(ResolvedPerson {
1196                id: row.get(0)?,
1197                name: row.get(1)?,
1198            })
1199        })?;
1200        let lower = text.to_lowercase();
1201        let mut out = Vec::new();
1202        for row in rows {
1203            let person = row?;
1204            if Self::contains_phrase(&lower, &person.name.to_lowercase()) {
1205                out.push(person);
1206            }
1207        }
1208        Ok(out)
1209    }
1210
1211    fn resolve_albums(conn: &Connection, text: &str) -> SqliteResult<Vec<ResolvedAlbum>> {
1212        let like = format!("%{}%", text.trim());
1213        let mut stmt = conn.prepare(
1214            "SELECT id, name FROM albums
1215             WHERE LOWER(name) LIKE LOWER(?1)
1216             ORDER BY updated_at DESC
1217             LIMIT 5",
1218        )?;
1219        let rows = stmt.query_map(params![like], |row| {
1220            Ok(ResolvedAlbum {
1221                id: row.get(0)?,
1222                name: row.get(1)?,
1223            })
1224        })?;
1225        rows.collect()
1226    }
1227
1228    /// Resolve city filters. Cities come from the grouped (city,
1229    /// country) photo rows — capped generously, not only from the top
1230    /// 100 most frequent places. Multiple matching cities are
1231    /// alternatives, not simultaneous requirements.
1232    fn resolve_cities(conn: &Connection, text: &str) -> SqliteResult<Vec<ResolvedCity>> {
1233        let mut stmt = conn.prepare(
1234            "SELECT location_city, location_country, COUNT(*) AS cnt
1235             FROM photos
1236             WHERE is_trashed = FALSE
1237               AND location_city IS NOT NULL
1238             GROUP BY location_city, location_country
1239             ORDER BY cnt DESC
1240             LIMIT 1000",
1241        )?;
1242        let rows = stmt.query_map([], |row| {
1243            let city: String = row.get(0)?;
1244            let country: Option<String> = row.get(1)?;
1245            let label = match &country {
1246                Some(country) => format!("{}, {}", city, country),
1247                None => city.clone(),
1248            };
1249            Ok(ResolvedCity {
1250                city,
1251                country,
1252                label,
1253            })
1254        })?;
1255        let lower = text.to_lowercase();
1256        let mut out = Vec::new();
1257        for row in rows {
1258            let place = row?;
1259            if Self::contains_phrase(&lower, &place.city.to_lowercase()) {
1260                out.push(place);
1261                if out.len() >= 3 {
1262                    break;
1263                }
1264            }
1265        }
1266        Ok(out)
1267    }
1268
1269    /// Resolve country filters from the full set of countries present
1270    /// in the library (not derived from the top-N city rows). An exact
1271    /// country phrase becomes a country predicate and never narrows to
1272    /// individual cities.
1273    fn resolve_countries(conn: &Connection, text: &str) -> SqliteResult<Vec<ResolvedCountry>> {
1274        let mut stmt = conn.prepare(
1275            "SELECT DISTINCT location_country
1276             FROM photos
1277             WHERE is_trashed = FALSE
1278               AND location_country IS NOT NULL",
1279        )?;
1280        let rows = stmt.query_map([], |row| {
1281            let country: String = row.get(0)?;
1282            Ok(ResolvedCountry {
1283                label: country.clone(),
1284                country,
1285            })
1286        })?;
1287        let lower = text.to_lowercase();
1288        let mut out = Vec::new();
1289        for row in rows {
1290            let resolved = row?;
1291            if Self::contains_phrase(&lower, &resolved.country.to_lowercase()) {
1292                out.push(resolved);
1293                if out.len() >= 3 {
1294                    break;
1295                }
1296            }
1297        }
1298        Ok(out)
1299    }
1300
1301    fn contains_word(lower: &str, needle: &str) -> bool {
1302        lower
1303            .split(|c: char| !c.is_alphanumeric())
1304            .any(|w| w == needle)
1305    }
1306
1307    fn contains_phrase(lower: &str, phrase: &str) -> bool {
1308        if phrase.trim().is_empty() {
1309            return false;
1310        }
1311        // Normalize punctuation to word boundaries so queries such as
1312        // "Paris, France" match the same entity spans as "Paris France".
1313        // Token normalization also avoids substring matches inside longer
1314        // names and works for Unicode city/country names.
1315        let normalize = |value: &str| {
1316            value
1317                .split(|c: char| !c.is_alphanumeric())
1318                .filter(|part| !part.is_empty())
1319                .collect::<Vec<_>>()
1320                .join(" ")
1321        };
1322        let haystack = normalize(lower);
1323        let needle = normalize(phrase);
1324        haystack == needle
1325            || haystack.contains(&format!(" {needle} "))
1326            || haystack.starts_with(&format!("{needle} "))
1327            || haystack.ends_with(&format!(" {needle}"))
1328    }
1329
1330    fn remove_word(text: &str, needle: &str) -> String {
1331        text.split_whitespace()
1332            .filter(|w| {
1333                // `#photo booth` is a thing to look for, not the word "photo".
1334                w.starts_with('#')
1335                    || w.trim_matches(|c: char| !c.is_alphanumeric())
1336                        .to_lowercase()
1337                        != needle
1338            })
1339            .collect::<Vec<_>>()
1340            .join(" ")
1341    }
1342
1343    /// Remove every recognized `name` from `text` by blanking the
1344    /// matched spans (replaced with spaces, so later whitespace-based
1345    /// passes still work). Matching is case-insensitive with Unicode
1346    /// case folding, and requires the span to start and end on phrase
1347    /// boundaries — a name embedded inside a longer word ("Tata" in
1348    /// "Tataganj") is left alone.
1349    fn remove_entity_names<'a>(text: &str, names: impl Iterator<Item = &'a str>) -> String {
1350        let mut out = text.to_string();
1351        for name in names {
1352            out = Self::remove_phrase(&out, name);
1353        }
1354        out
1355    }
1356
1357    fn remove_phrase(text: &str, phrase: &str) -> String {
1358        let phrase = phrase.trim();
1359        if phrase.is_empty() || text.is_empty() {
1360            return text.to_string();
1361        }
1362        let t: Vec<char> = text.chars().collect();
1363        let p: Vec<char> = phrase.chars().collect();
1364        let is_word_char = |c: char| c.is_alphanumeric();
1365        let caseless_eq = |a: char, b: char| a.to_lowercase().eq(b.to_lowercase());
1366
1367        let mut masked = vec![false; t.len()];
1368        let mut i = 0;
1369        while i + p.len() <= t.len() {
1370            if t[i..i + p.len()]
1371                .iter()
1372                .zip(p.iter())
1373                .all(|(&a, &b)| caseless_eq(a, b))
1374            {
1375                let end = i + p.len();
1376                let before_ok = i == 0 || !is_word_char(t[i - 1]);
1377                let after_ok = end == t.len() || !is_word_char(t[end]);
1378                if before_ok && after_ok {
1379                    for m in masked[i..end].iter_mut() {
1380                        *m = true;
1381                    }
1382                    i = end;
1383                    continue;
1384                }
1385            }
1386            i += 1;
1387        }
1388        if masked.iter().all(|m| !*m) {
1389            return text.to_string();
1390        }
1391        let mut out = String::with_capacity(text.len());
1392        for (c, m) in t.iter().zip(masked.iter()) {
1393            if *m {
1394                out.push(' ');
1395            } else {
1396                out.push(*c);
1397            }
1398        }
1399        out
1400    }
1401
1402    fn date_label(range: &DateRange) -> String {
1403        let start = range.start.format("%Y-%m-%d").to_string();
1404        let end = range.end.format("%Y-%m-%d").to_string();
1405        if start == end {
1406            start
1407        } else {
1408            format!("{} to {}", start, end)
1409        }
1410    }
1411
1412    fn search_people(conn: &Connection, q: &str) -> SqliteResult<Vec<PersonHit>> {
1413        let like = format!("%{}%", q);
1414        // representative_face_id → relative `.photovault/faces/<id>.jpg`
1415        // path. Mirrors face_repo::populate_face_thumbnails so the
1416        // frontend's thumbUrl helper resolves the file uniformly.
1417        let mut stmt = conn.prepare(
1418            r#"
1419            SELECT fc.id, fc.name, fc.photo_count, fc.representative_face_id
1420            FROM face_clusters fc
1421            WHERE fc.name IS NOT NULL
1422              AND LOWER(fc.name) LIKE LOWER(?1)
1423            ORDER BY fc.photo_count DESC
1424            LIMIT 10
1425            "#,
1426        )?;
1427        let rows = stmt.query_map(params![like], |row| {
1428            let face_id: Option<i64> = row.get(3)?;
1429            Ok(PersonHit {
1430                cluster_id: row.get(0)?,
1431                name: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
1432                photo_count: row.get(2)?,
1433                face_thumbnail_path: face_id.map(|id| format!(".photovault/faces/{}.jpg", id)),
1434            })
1435        })?;
1436        rows.collect()
1437    }
1438
1439    fn search_albums(conn: &Connection, q: &str) -> SqliteResult<Vec<AlbumHit>> {
1440        let like = format!("%{}%", q);
1441        // LEFT JOIN to pull the cover photo's thumbnail_path so the
1442        // frontend can render the album hit with its cover image.
1443        let mut stmt = conn.prepare(
1444            r#"
1445            SELECT a.id, a.name, a.photo_count, a.cover_photo_id, pcov.thumbnail_path
1446            FROM albums a
1447            LEFT JOIN photos pcov ON pcov.id = a.cover_photo_id
1448            WHERE LOWER(a.name) LIKE LOWER(?1)
1449            ORDER BY a.updated_at DESC
1450            LIMIT 10
1451            "#,
1452        )?;
1453        let rows = stmt.query_map(params![like], |row| {
1454            Ok(AlbumHit {
1455                album_id: row.get(0)?,
1456                name: row.get(1)?,
1457                photo_count: row.get(2)?,
1458                cover_photo_id: row.get(3)?,
1459                cover_thumbnail_path: row.get(4)?,
1460            })
1461        })?;
1462        rows.collect()
1463    }
1464
1465    fn search_places(conn: &Connection, q: &str) -> SqliteResult<Vec<PlaceHit>> {
1466        let like = format!("%{}%", q);
1467        let mut stmt = conn.prepare(
1468            r#"
1469            SELECT location_city, location_country, COUNT(*) AS cnt
1470            FROM photos
1471            WHERE is_trashed = FALSE
1472              AND location_city IS NOT NULL
1473              AND (LOWER(location_city) LIKE LOWER(?1)
1474                   OR LOWER(location_country) LIKE LOWER(?1))
1475            GROUP BY location_city, location_country
1476            ORDER BY cnt DESC
1477            LIMIT 10
1478            "#,
1479        )?;
1480        let rows = stmt.query_map(params![like], |row| {
1481            Ok(PlaceHit {
1482                city: row.get(0)?,
1483                country: row.get(1)?,
1484                photo_count: row.get(2)?,
1485            })
1486        })?;
1487        rows.collect()
1488    }
1489}
1490
1491#[cfg(test)]
1492mod tests {
1493    use super::*;
1494
1495    fn search_test_conn() -> Connection {
1496        let conn = Connection::open_in_memory().unwrap();
1497        conn.execute_batch(
1498            r#"
1499            CREATE TABLE photos (
1500                id INTEGER PRIMARY KEY,
1501                file_path TEXT NOT NULL,
1502                file_name TEXT NOT NULL,
1503                file_hash TEXT NOT NULL,
1504                file_size INTEGER NOT NULL,
1505                date_taken TEXT,
1506                location_city TEXT,
1507                location_country TEXT,
1508                camera_make TEXT,
1509                camera_model TEXT,
1510                thumbnail_path TEXT,
1511                faces_processed BOOLEAN DEFAULT FALSE,
1512                media_type TEXT NOT NULL DEFAULT 'photo',
1513                is_favorite BOOLEAN DEFAULT FALSE,
1514                is_trashed BOOLEAN DEFAULT FALSE
1515            );
1516            CREATE TABLE face_clusters (
1517                id INTEGER PRIMARY KEY,
1518                name TEXT,
1519                photo_count INTEGER NOT NULL DEFAULT 0,
1520                representative_face_id INTEGER
1521            );
1522            CREATE TABLE faces (
1523                id INTEGER PRIMARY KEY,
1524                photo_id INTEGER NOT NULL,
1525                cluster_id INTEGER
1526            );
1527            CREATE TABLE photo_inferred_identities (
1528                photo_id INTEGER NOT NULL,
1529                cluster_id INTEGER NOT NULL
1530            );
1531            CREATE TABLE albums (
1532                id INTEGER PRIMARY KEY,
1533                name TEXT NOT NULL,
1534                photo_count INTEGER NOT NULL DEFAULT 0,
1535                cover_photo_id INTEGER,
1536                updated_at TEXT
1537            );
1538            CREATE TABLE album_photos (
1539                album_id INTEGER NOT NULL,
1540                photo_id INTEGER NOT NULL
1541            );
1542            "#,
1543        )
1544        .unwrap();
1545        conn
1546    }
1547
1548    fn insert_photo(conn: &Connection, id: i64, file_name: &str, date_taken: &str) {
1549        conn.execute(
1550            "INSERT INTO photos
1551                (id, file_path, file_name, file_hash, file_size, date_taken, media_type, thumbnail_path)
1552             VALUES (?1, ?2, ?3, ?4, 100, ?5, 'photo', ?6)",
1553            params![
1554                id,
1555                format!("{file_name}.jpg"),
1556                file_name,
1557                format!("hash-{id}"),
1558                date_taken,
1559                format!(".photovault/thumbs/{file_name}.jpg")
1560            ],
1561        )
1562        .unwrap();
1563    }
1564
1565    fn set_location(conn: &Connection, id: i64, city: &str, country: &str) {
1566        conn.execute(
1567            "UPDATE photos SET location_city = ?2, location_country = ?3 WHERE id = ?1",
1568            params![id, city, country],
1569        )
1570        .unwrap();
1571    }
1572
1573    fn insert_person(conn: &Connection, id: i64, name: &str, photo_ids: &[i64]) {
1574        conn.execute(
1575            "INSERT INTO face_clusters (id, name, photo_count) VALUES (?1, ?2, ?3)",
1576            params![id, name, photo_ids.len() as i64],
1577        )
1578        .unwrap();
1579        for (idx, photo_id) in photo_ids.iter().enumerate() {
1580            conn.execute(
1581                "INSERT INTO faces (id, photo_id, cluster_id) VALUES (?1, ?2, ?3)",
1582                params![10_000 + idx as i64 + id * 100, photo_id, id],
1583            )
1584            .unwrap();
1585        }
1586    }
1587
1588    /// What visual search was asked: the text, and the set it searched in.
1589    type Asked = Vec<(String, Option<Vec<i64>>)>;
1590
1591    /// A visual search stub: records what it was asked, answers `ids`.
1592    fn page_with(conn: &Connection, q: &str, ids: Vec<i64>) -> (UnifiedSearchResults, Asked) {
1593        let mut asked = Vec::new();
1594        let mut semantic = |text: &str, within: Option<&HashSet<i64>>| {
1595            let mut within: Option<Vec<i64>> = within.map(|w| w.iter().copied().collect());
1596            if let Some(w) = within.as_mut() {
1597                w.sort_unstable();
1598            }
1599            asked.push((text.to_string(), within.clone()));
1600            ids.iter()
1601                .copied()
1602                .filter(|id| within.as_ref().is_none_or(|w| w.contains(id)))
1603                .collect()
1604        };
1605        let page = SearchService::search_unified_page_with(conn, q, &mut semantic, 0, 100).unwrap();
1606        (page.results, asked)
1607    }
1608
1609    fn chips(results: &UnifiedSearchResults) -> Vec<(String, String)> {
1610        results
1611            .interpreted
1612            .iter()
1613            .map(|f| (f.kind.clone(), f.label.clone()))
1614            .collect()
1615    }
1616
1617    #[test]
1618    fn visual_search_sees_only_the_thing_not_the_names() {
1619        let conn = search_test_conn();
1620        for id in 1..=4 {
1621            insert_photo(&conn, id, &format!("img{id}"), "2024-01-01T10:00:00Z");
1622        }
1623        insert_person(&conn, 1, "Dad", &[1, 2, 3]);
1624        insert_person(&conn, 2, "Mom", &[2, 3]);
1625
1626        let (results, asked) = page_with(&conn, "Dad and Mom food", vec![3, 4]);
1627        // Scored among Dad-and-Mom photos only, and asked about "food" alone.
1628        assert_eq!(asked, vec![("food".to_string(), Some(vec![2, 3]))]);
1629        assert_eq!(results.photo_ids, vec![3]);
1630
1631        // Names only: no visual search at all.
1632        let (_, asked) = page_with(&conn, "Dad and Mom", vec![1]);
1633        assert!(asked.is_empty());
1634    }
1635
1636    #[test]
1637    fn at_names_match_whole_names_and_say_when_no_one_matches() {
1638        let conn = search_test_conn();
1639        for id in 1..=3 {
1640            insert_photo(&conn, id, &format!("img{id}"), "2024-01-01T10:00:00Z");
1641        }
1642        insert_person(&conn, 1, "Uncle Raju", &[1, 2]);
1643        insert_person(&conn, 2, "Raju", &[3]);
1644
1645        let (results, _) = page_with(&conn, "@uncle raju", vec![]);
1646        assert_eq!(results.photo_ids.len(), 2);
1647        assert_eq!(
1648            chips(&results),
1649            vec![("person".to_string(), "Uncle Raju".to_string())]
1650        );
1651
1652        let (results, _) = page_with(&conn, "@\"Raju\"", vec![]);
1653        assert_eq!(results.photo_ids, vec![3]);
1654
1655        let (results, asked) = page_with(&conn, "@Kiran beach", vec![1]);
1656        assert!(results.photo_ids.is_empty());
1657        assert!(asked.is_empty());
1658        assert!(
1659            chips(&results).contains(&("missing".to_string(), "No one called Kiran".to_string()))
1660        );
1661    }
1662
1663    #[test]
1664    fn a_hash_thing_must_be_seen_in_the_photo() {
1665        let conn = search_test_conn();
1666        insert_photo(&conn, 1, "food_court_2019", "2024-01-01T10:00:00Z");
1667        insert_photo(&conn, 2, "img2", "2024-01-02T10:00:00Z");
1668        insert_photo(&conn, 3, "img3", "2024-01-03T10:00:00Z");
1669        insert_person(&conn, 1, "Dad", &[1, 2, 3]);
1670
1671        // Plain words: a file name still counts.
1672        let (results, _) = page_with(&conn, "Dad food", vec![2]);
1673        let mut ids = results.photo_ids.clone();
1674        ids.sort_unstable();
1675        assert_eq!(ids, vec![1, 2]);
1676
1677        // `#food`: only photos that look like food; "videos" still filters.
1678        let (results, _) = page_with(&conn, "@Dad #food", vec![2]);
1679        assert_eq!(results.photo_ids, vec![2]);
1680        conn.execute("UPDATE photos SET media_type = 'video' WHERE id = 3", [])
1681            .unwrap();
1682        let (results, asked) = page_with(&conn, "@Dad #food videos", vec![2, 3]);
1683        assert_eq!(asked, vec![("food".to_string(), Some(vec![3]))]);
1684        assert_eq!(results.photo_ids, vec![3]);
1685        assert!(chips(&results).contains(&("semantic".to_string(), "food".to_string())));
1686    }
1687
1688    #[test]
1689    fn recent_searches_keep_the_latest_once_each() {
1690        let conn = search_test_conn();
1691        conn.execute_batch(
1692            "CREATE TABLE recent_searches (id INTEGER PRIMARY KEY, query TEXT NOT NULL,
1693               last_used DATETIME DEFAULT CURRENT_TIMESTAMP, use_count INTEGER DEFAULT 1,
1694               UNIQUE(query))",
1695        )
1696        .unwrap();
1697        for q in ["goa", "  dad   2019 ", "goa", ""] {
1698            SearchService::remember_query(&conn, q).unwrap();
1699        }
1700        assert_eq!(
1701            SearchService::recent_queries(&conn, 5).unwrap(),
1702            vec!["goa", "dad 2019"]
1703        );
1704        SearchService::clear_recent(&conn).unwrap();
1705        assert!(SearchService::recent_queries(&conn, 5).unwrap().is_empty());
1706    }
1707
1708    #[test]
1709    fn pinned_searches_keep_their_order_and_survive_clearing_recent() {
1710        let conn = search_test_conn();
1711        conn.execute_batch(
1712            "CREATE TABLE IF NOT EXISTS library_meta (key TEXT PRIMARY KEY, value TEXT);
1713             CREATE TABLE IF NOT EXISTS recent_searches (id INTEGER PRIMARY KEY,
1714                query TEXT NOT NULL, use_count INTEGER NOT NULL DEFAULT 1);",
1715        )
1716        .unwrap();
1717        assert!(SearchService::pinned_queries(&conn).unwrap().is_empty());
1718        SearchService::set_pinned(&conn, "@Mom  #cake", true).unwrap();
1719        SearchService::set_pinned(&conn, "goa 2019", true).unwrap();
1720        SearchService::set_pinned(&conn, "@Mom #cake", true).unwrap();
1721        assert_eq!(
1722            SearchService::pinned_queries(&conn).unwrap(),
1723            vec!["goa 2019", "@Mom #cake"]
1724        );
1725        SearchService::clear_recent(&conn).unwrap();
1726        SearchService::set_pinned(&conn, "goa 2019", false).unwrap();
1727        assert_eq!(
1728            SearchService::pinned_queries(&conn).unwrap(),
1729            vec!["@Mom #cake"]
1730        );
1731    }
1732
1733    #[test]
1734    fn hashtags_survive_the_word_rules() {
1735        assert_eq!(
1736            SearchService::remove_word("#photo booth photos", "photos"),
1737            "#photo booth"
1738        );
1739        assert_eq!(
1740            SearchService::remove_word("#photo booth", "photo"),
1741            "#photo booth"
1742        );
1743    }
1744
1745    #[test]
1746    fn unified_search_returns_semantic_matches_when_text_does_not_match_metadata() {
1747        let conn = search_test_conn();
1748        insert_photo(&conn, 1, "img001", "2024-01-01T10:00:00Z");
1749        insert_photo(&conn, 2, "img002", "2024-01-02T10:00:00Z");
1750        insert_photo(&conn, 3, "img003", "2024-01-03T10:00:00Z");
1751
1752        let results =
1753            SearchService::search_unified_with_semantic(&conn, "group photo", vec![3, 1]).unwrap();
1754
1755        assert_eq!(results.photo_ids, vec![3, 1]);
1756        assert_eq!(
1757            results
1758                .interpreted
1759                .iter()
1760                .map(|f| (f.kind.as_str(), f.label.as_str()))
1761                .collect::<Vec<_>>(),
1762            vec![("media", "Photos"), ("semantic", "group")]
1763        );
1764    }
1765
1766    #[test]
1767    fn unified_search_ands_date_filter_with_semantic_matches() {
1768        let conn = search_test_conn();
1769        insert_photo(&conn, 1, "img001", "2023-06-01T10:00:00Z");
1770        insert_photo(&conn, 2, "img002", "2024-06-01T10:00:00Z");
1771        insert_photo(&conn, 3, "img003", "2024-07-01T10:00:00Z");
1772
1773        let results =
1774            SearchService::search_unified_with_semantic(&conn, "family 2024", vec![1, 3, 2])
1775                .unwrap();
1776
1777        assert_eq!(results.photo_ids, vec![3, 2]);
1778        assert!(results
1779            .interpreted
1780            .iter()
1781            .any(|f| f.kind == "semantic" && f.label == "family"));
1782        assert!(results.interpreted.iter().any(|f| f.kind == "date"));
1783    }
1784
1785    #[test]
1786    fn unified_search_excludes_trashed_semantic_matches() {
1787        let conn = search_test_conn();
1788        insert_photo(&conn, 1, "img001", "2024-01-01T10:00:00Z");
1789        insert_photo(&conn, 2, "img002", "2024-01-02T10:00:00Z");
1790        conn.execute("UPDATE photos SET is_trashed = TRUE WHERE id = 1", [])
1791            .unwrap();
1792
1793        let results =
1794            SearchService::search_unified_with_semantic(&conn, "beach", vec![1, 2]).unwrap();
1795
1796        assert_eq!(results.photo_ids, vec![2]);
1797    }
1798
1799    #[test]
1800    fn unified_search_resolves_person_and_place_independent_of_order() {
1801        let conn = search_test_conn();
1802        insert_photo(&conn, 1, "vizag-tata", "2024-01-01T10:00:00Z");
1803        insert_photo(&conn, 2, "vizag-other", "2024-01-02T10:00:00Z");
1804        insert_photo(&conn, 3, "goa-tata", "2024-01-03T10:00:00Z");
1805        set_location(&conn, 1, "Vizianagaram", "India");
1806        set_location(&conn, 2, "Vizianagaram", "India");
1807        set_location(&conn, 3, "Goa", "India");
1808        insert_person(&conn, 7, "Tata", &[1, 3]);
1809
1810        let a = SearchService::search_unified_with_semantic(&conn, "tata vizianagaram", vec![])
1811            .unwrap();
1812        let b = SearchService::search_unified_with_semantic(&conn, "vizianagaram tata", vec![])
1813            .unwrap();
1814
1815        assert_eq!(a.photo_ids, vec![1]);
1816        assert_eq!(b.photo_ids, vec![1]);
1817        assert_eq!(
1818            a.interpreted
1819                .iter()
1820                .map(|f| (f.kind.as_str(), f.label.as_str()))
1821                .collect::<Vec<_>>(),
1822            vec![("person", "Tata"), ("place", "Vizianagaram, India")]
1823        );
1824        assert_eq!(
1825            b.interpreted
1826                .iter()
1827                .map(|f| (f.kind.as_str(), f.label.as_str()))
1828                .collect::<Vec<_>>(),
1829            vec![("person", "Tata"), ("place", "Vizianagaram, India")]
1830        );
1831    }
1832
1833    #[test]
1834    fn semantic_does_not_delete_fully_structured_matches() {
1835        let conn = search_test_conn();
1836        insert_photo(&conn, 1, "vizag-tata", "2024-01-01T10:00:00Z");
1837        insert_photo(&conn, 2, "vizag-tata-older", "2023-01-01T10:00:00Z");
1838        set_location(&conn, 1, "Vizianagaram", "India");
1839        set_location(&conn, 2, "Vizianagaram", "India");
1840        insert_person(&conn, 7, "Tata", &[1, 2]);
1841
1842        let results =
1843            SearchService::search_unified_with_semantic(&conn, "tata vizianagaram", vec![1])
1844                .unwrap();
1845
1846        assert_eq!(results.photo_ids, vec![1, 2]);
1847    }
1848
1849    #[test]
1850    fn place_search_handles_case_punctuation_and_unicode_without_span_loss() {
1851        let conn = search_test_conn();
1852        insert_photo(&conn, 1, "paris", "2024-01-01T10:00:00Z");
1853        insert_photo(&conn, 2, "munich", "2024-01-02T10:00:00Z");
1854        set_location(&conn, 1, "Paris", "France");
1855        set_location(&conn, 2, "München", "Germany");
1856
1857        let paris =
1858            SearchService::search_unified_with_semantic(&conn, "PARIS, France", vec![]).unwrap();
1859        assert_eq!(paris.photo_ids, vec![1]);
1860
1861        let munich = SearchService::search_unified_with_semantic(&conn, "mÜnchen", vec![]).unwrap();
1862        assert_eq!(munich.photo_ids, vec![2]);
1863    }
1864
1865    #[test]
1866    fn semantic_visual_text_still_filters_inside_structured_matches() {
1867        let conn = search_test_conn();
1868        insert_photo(&conn, 1, "vizag-tata-car", "2024-01-01T10:00:00Z");
1869        insert_photo(&conn, 2, "vizag-tata-home", "2024-01-02T10:00:00Z");
1870        set_location(&conn, 1, "Vizianagaram", "India");
1871        set_location(&conn, 2, "Vizianagaram", "India");
1872        insert_person(&conn, 7, "Tata", &[1, 2]);
1873
1874        let results =
1875            SearchService::search_unified_with_semantic(&conn, "car tata vizianagaram", vec![1])
1876                .unwrap();
1877
1878        assert_eq!(results.photo_ids, vec![1]);
1879        assert!(results
1880            .interpreted
1881            .iter()
1882            .any(|f| f.kind == "semantic" && f.label == "car"));
1883    }
1884}