Skip to main content

smriti/services/
memories.rs

1//! Memories — "N years ago today" style rediscovery.
2//!
3//! Generators: OnThisDay, FallbackWindow, SeasonalRecap, PersonStory,
4//! PlaceStory, YearRecap — one ranker, one hero-selector, one block filter.
5//! Memories are computed per-day from `photos` / `faces` / `memory_blocks`;
6//! nothing is persisted except the user's block preferences.
7
8use std::collections::{HashMap, HashSet};
9
10use crate::services::collage_picks::{self, NOT_SCREENSHOT};
11use crate::services::story;
12use chrono::{Datelike, Duration, NaiveDate};
13use rusqlite::{params, Connection, Result as SqliteResult};
14
15pub type MemoryId = String;
16
17/// A bounded slowshow batch: sample days rather than photos so a huge
18/// burst cannot dominate. Older days get more chances, not exclusivity.
19pub fn surprise_photos(
20    conn: &Connection,
21    album_id: Option<i64>,
22    exclude_ids: &[i64],
23) -> SqliteResult<Vec<i64>> {
24    let excluded = serde_json::to_string(&exclude_ids.iter().rev().take(256).collect::<Vec<_>>())
25        .expect("integer IDs serialize");
26    let mut stmt = conn.prepare(&format!(
27        "WITH eligible AS MATERIALIZED (
28          SELECT p.id, p.file_hash, p.phash, p.is_favorite,
29                 COALESCE(p.width * p.height, 0) AS area,
30                 COALESCE(substr(p.date_taken, 1, 10), 'undated:' || p.id) AS day
31          FROM photos p
32          WHERE p.is_trashed = FALSE AND p.media_type = 'photo'
33            AND {NOT_SCREENSHOT}
34            AND (p.date_taken IS NULL OR substr(p.date_taken, 1, 10) <= date('now'))
35            AND (?1 IS NULL OR (?1 = -1 AND p.is_favorite = TRUE)
36                 OR EXISTS (SELECT 1 FROM album_photos ap WHERE ap.album_id = ?1 AND ap.photo_id = p.id))
37            AND p.id NOT IN (SELECT value FROM json_each(?2))
38            AND NOT EXISTS (
39              SELECT 1 FROM faces f JOIN memory_blocks mb
40              ON mb.kind = 'person' AND mb.target_key = CAST(f.cluster_id AS TEXT)
41              WHERE f.photo_id = p.id AND f.user_confirmed >= 0)
42        ), days AS MATERIALIZED (
43          SELECT day, ((random() & 2147483647) + 1) /
44            CASE WHEN day < date('now', '-1 year') THEN 4 ELSE 1 END AS ticket
45          FROM eligible GROUP BY day ORDER BY ticket LIMIT 12
46        ), ranked AS (
47          SELECT e.*, d.ticket, row_number() OVER (
48            PARTITION BY e.day ORDER BY e.is_favorite DESC, e.area DESC, random()) AS rank
49          FROM eligible e JOIN days d ON e.day = d.day
50        )
51        SELECT id, file_hash, phash, day,
52          (SELECT group_id FROM duplicate_group_members WHERE photo_id = ranked.id LIMIT 1)
53        FROM ranked WHERE rank <= 8 ORDER BY ticket, day, rank"
54    ))?;
55    let mut rows = stmt.query(params![album_id, excluded])?;
56    let mut ids = Vec::new();
57    let mut hashes = HashSet::new();
58    let mut phashes: Vec<u64> = Vec::new();
59    let mut groups = HashSet::new();
60    let mut per_day = HashMap::<String, usize>::new();
61    while let Some(row) = rows.next()? {
62        let id: i64 = row.get(0)?;
63        let hash: String = row.get(1)?;
64        let phash: Option<i64> = row.get(2)?;
65        let day: String = row.get(3)?;
66        let group: Option<i64> = row.get(4)?;
67        let count = per_day.entry(day).or_default();
68        if *count >= 3
69            || hashes.contains(&hash)
70            || group.is_some_and(|g| groups.contains(&g))
71            || phash.is_some_and(|h| {
72                phashes
73                    .iter()
74                    .any(|other| (*other ^ h as u64).count_ones() <= 4)
75            })
76        {
77            continue;
78        }
79        *count += 1;
80        hashes.insert(hash);
81        if let Some(hash) = phash {
82            phashes.push(hash as u64);
83        }
84        if let Some(group) = group {
85            groups.insert(group);
86        }
87        ids.push(id);
88    }
89    Ok(ids)
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum MemoryKind {
94    OnThisDay,
95    FallbackWindow,
96    SeasonalRecap,
97    PersonStory,
98    PlaceStory,
99    /// Ultimate fallback: surfaces "X years ago" with photos from a prior
100    /// year when no other generator produced anything. Guarantees a sparse
101    /// library still sees something if it has any history at all.
102    YearRecap,
103}
104
105#[derive(Debug, Clone)]
106pub struct Memory {
107    pub id: MemoryId,
108    pub kind: MemoryKind,
109    pub title: String,
110    pub photo_ids: Vec<i64>,
111    pub hero_photo_id: i64,
112    /// Relative thumbnail path for the chosen hero (set during hero
113    /// selection). None if the hero photo hasn't had a thumbnail
114    /// generated yet.
115    pub hero_thumbnail_path: Option<String>,
116    pub score: f32,
117    pub year: i32,
118    pub has_faces: bool,
119    /// Favourites among the photos shown.
120    pub favorites: usize,
121    /// Someone the user has named appears in it.
122    pub named_person: bool,
123    /// What hiding this memory blocks: a day, month, year, person or place.
124    pub hide_key: String,
125}
126
127#[derive(Debug, Clone)]
128pub struct MemoryCard {
129    pub id: MemoryId,
130    /// What kind of memory this is; collage suggestions say why from it.
131    pub kind: MemoryKind,
132    pub title: String,
133    pub hero_photo_id: i64,
134    pub hero_thumbnail_path: Option<String>,
135    pub photo_count: usize,
136    pub photo_ids: Vec<i64>,
137    pub hide_key: String,
138}
139
140impl From<Memory> for MemoryCard {
141    fn from(m: Memory) -> Self {
142        Self {
143            hide_key: m.hide_key,
144            id: m.id,
145            kind: m.kind,
146            title: m.title,
147            hero_photo_id: m.hero_photo_id,
148            hero_thumbnail_path: m.hero_thumbnail_path,
149            photo_count: m.photo_ids.len(),
150            photo_ids: m.photo_ids,
151        }
152    }
153}
154
155/// Minimum library age before Memories surface. If the oldest non-trashed
156/// photo is newer than this many months ago, hide the feature.
157const MIN_LIBRARY_AGE_MONTHS: i64 = 3;
158
159/// Minimum age (in months) for a photo to appear in memories. Photos newer
160/// than this are too recent to be nostalgic.
161const MIN_PHOTO_AGE_MONTHS: i64 = 3;
162
163/// Maximum memory cards returned by the generator.
164const MAX_CARDS: usize = 20;
165
166/// SeasonalRecap threshold — month needs at least this many photos to
167/// surface as a recap. Lowered from 10 so sparse libraries (a few dozen
168/// photos a year) can still see monthly memories.
169const SEASONAL_MIN_PHOTOS: i64 = 5;
170
171/// Cap on photos per YearRecap card.
172const YEAR_RECAP_MAX_PHOTOS: usize = 50;
173/// Photos each generator considers per memory.
174const MAX_MEMORY_PHOTOS: usize = 500;
175/// Photos a memory shows: the best of each stretch of its time span. A
176/// memory is a look back, not the whole camera roll of that day.
177const MAX_SHOWN_PHOTOS: usize = 60;
178/// Memories of one kind the user has hidden before that kind is shown less.
179const HIDDEN_BEFORE_LESS: usize = 3;
180const HIDE_BLOCK_KIND: &str = "memory";
181
182/// Top entry point: full pipeline. Runs the generators, scores, filters
183/// blocks, picks heroes, returns cards.
184pub fn generate_for_today(conn: &Connection, today: NaiveDate) -> Result<Vec<MemoryCard>, String> {
185    let current_year = today.year();
186
187    let mut all: Vec<Memory> = Vec::new();
188
189    let on_this_day_results = on_this_day(conn, today, current_year)
190        .map_err(|e| format!("OnThisDay query failed: {}", e))?;
191    let had_exact = !on_this_day_results.is_empty();
192    all.extend(on_this_day_results);
193
194    if !had_exact {
195        let fb = fallback_window(conn, today, current_year)
196            .map_err(|e| format!("FallbackWindow query failed: {}", e))?;
197        all.extend(fb);
198    }
199
200    let seasonal = seasonal_recap(conn, today, current_year)
201        .map_err(|e| format!("SeasonalRecap query failed: {}", e))?;
202    all.extend(seasonal);
203
204    if let Some(person) =
205        person_story(conn, today).map_err(|e| format!("PersonStory query failed: {e}"))?
206    {
207        all.push(person);
208    }
209    if let Some(place) =
210        place_story(conn, today).map_err(|e| format!("PlaceStory query failed: {e}"))?
211    {
212        all.push(place);
213    }
214
215    // Ultimate fallback. Only fires when no specific anniversary or season
216    // qualifies; surfaces "X years ago" cards from prior years so a sparse
217    // library still has something to show.
218    if all.is_empty() {
219        let recaps = year_recap(conn, today, current_year)
220            .map_err(|e| format!("YearRecap query failed: {}", e))?;
221        all.extend(recaps);
222    }
223
224    if all.is_empty() {
225        return Ok(Vec::new());
226    }
227
228    let blocks = load_person_blocks(conn).map_err(|e| format!("Block load failed: {}", e))?;
229    if !blocks.is_empty() {
230        filter_blocked(conn, &mut all, &blocks)
231            .map_err(|e| format!("Block filter failed: {}", e))?;
232    }
233
234    let scores = curate_photos(conn, &mut all).map_err(|e| format!("Curation failed: {e}"))?;
235    populate_hero_and_faces(conn, &mut all, &scores)
236        .map_err(|e| format!("Hero selection failed: {}", e))?;
237    let hidden = load_hidden(conn).map_err(|e| format!("Hidden load failed: {e}"))?;
238    all.retain(|m| !hidden.contains(&m.hide_key));
239    rank(&mut all, current_year, &hidden);
240
241    if all.len() > MAX_CARDS {
242        all.truncate(MAX_CARDS);
243    }
244
245    // Titles last, so only the cards shown pay for the lookups.
246    let home =
247        crate::services::album_suggestions::home(conn).map(|(city, country, _, _)| (city, country));
248    for memory in &mut all {
249        retitle(conn, memory, today, &home);
250    }
251
252    Ok(all.into_iter().map(MemoryCard::from).collect())
253}
254
255/// Swap a generic title for one that says where or who, when the photos
256/// make that clear: "Three years ago today, in Bern", "Bern, October 2023".
257fn retitle(
258    conn: &Connection,
259    memory: &mut Memory,
260    today: NaiveDate,
261    home: &Option<(String, String)>,
262) {
263    let facts = || story::Facts::gather_with_home(conn, &memory.photo_ids, home.clone());
264    memory.title = match memory.kind {
265        MemoryKind::OnThisDay | MemoryKind::FallbackWindow => {
266            story::looking_back(&story::spelled(&memory.title), &facts())
267        }
268        MemoryKind::SeasonalRecap => {
269            story::month_back(story::month_name(today.month()), memory.year, &facts())
270        }
271        MemoryKind::YearRecap => story::year_back(memory.year, &facts()),
272        MemoryKind::PersonStory | MemoryKind::PlaceStory => return,
273    };
274}
275
276/// [`generate_for_today`], reused while the library is unchanged. Memories,
277/// a memory's detail page and the suggested collages all need today's cards,
278/// and building them scans the whole library, so they're built once and
279/// rebuilt only when the day or the library changes.
280pub fn generate_for_today_cached(
281    conn: &Connection,
282    today: NaiveDate,
283) -> Result<Vec<MemoryCard>, String> {
284    static CACHE: std::sync::Mutex<Option<(String, Vec<MemoryCard>)>> = std::sync::Mutex::new(None);
285    let key = cache_key(conn, today).map_err(|e| format!("Memories cache key failed: {e}"))?;
286    if let Some((cached_key, cards)) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
287        if *cached_key == key {
288            return Ok(cards.clone());
289        }
290    }
291    let cards = generate_for_today(conn, today)?;
292    *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = Some((key, cards.clone()));
293    Ok(cards)
294}
295
296/// Changes whenever anything memories are built from changes: photos
297/// (added, trashed, favourited, dated, placed), faces and their people,
298/// names, and hidden people.
299fn cache_key(conn: &Connection, today: NaiveDate) -> SqliteResult<String> {
300    let fingerprint: String = conn.query_row(
301        r#"SELECT
302             (SELECT count(*) || ':' || ifnull(max(id), 0) || ':' || total(is_trashed) || ':'
303                     || total(is_favorite) || ':' || count(location_city) || ':' || count(date_taken)
304              FROM photos)
305             || '|' || (SELECT count(*) || ':' || ifnull(max(id), 0) || ':' || total(cluster_id) FROM faces)
306             || '|' || (SELECT ifnull(group_concat(id || '=' || name), '') FROM face_clusters
307                        WHERE name IS NOT NULL)
308             || '|' || (SELECT count(*) || ':' || ifnull(max(id), 0) FROM memory_blocks)"#,
309        [],
310        |row| row.get(0),
311    )?;
312    Ok(format!(
313        "{}|{today}|{fingerprint}|{:?}",
314        conn.path().unwrap_or(""),
315        crate::services::album_suggestions::home_override()
316    ))
317}
318
319/// Check whether the library has enough history to justify Memories.
320pub fn library_is_old_enough(conn: &Connection, today: NaiveDate) -> bool {
321    let oldest: Option<String> = conn
322        .query_row(
323            "SELECT MIN(date_taken) FROM photos WHERE is_trashed = FALSE AND date_taken IS NOT NULL",
324            [],
325            |row| row.get(0),
326        )
327        .ok()
328        .flatten();
329
330    let Some(oldest_str) = oldest else {
331        return false;
332    };
333
334    // Parse "YYYY-MM-DD HH:MM:SS" or "YYYY-MM-DD" prefix.
335    let parsed = chrono::NaiveDateTime::parse_from_str(&oldest_str, "%Y-%m-%d %H:%M:%S")
336        .map(|dt| dt.date())
337        .or_else(|_| {
338            NaiveDate::parse_from_str(&oldest_str[..oldest_str.len().min(10)], "%Y-%m-%d")
339        });
340
341    let Ok(oldest_date) = parsed else {
342        return false;
343    };
344
345    let age_days = today.signed_duration_since(oldest_date).num_days();
346    age_days >= MIN_LIBRARY_AGE_MONTHS * 30
347}
348
349fn memory_id(kind: MemoryKind, year: i32, today: NaiveDate) -> MemoryId {
350    format!(
351        "{}-{}-{:02}-{:02}",
352        match kind {
353            MemoryKind::OnThisDay => "otd",
354            MemoryKind::FallbackWindow => "fw",
355            MemoryKind::SeasonalRecap => "sr",
356            MemoryKind::PersonStory => "person",
357            MemoryKind::PlaceStory => "place",
358            MemoryKind::YearRecap => "yr",
359        },
360        year,
361        today.month(),
362        today.day()
363    )
364}
365
366fn parse_ids(csv: &str) -> Vec<i64> {
367    csv.split(',')
368        .filter_map(|s| s.trim().parse::<i64>().ok())
369        .collect()
370}
371
372// ---------- Generators ----------
373
374fn on_this_day(
375    conn: &Connection,
376    today: NaiveDate,
377    _current_year: i32,
378) -> SqliteResult<Vec<Memory>> {
379    let today_md = format!("{:02}-{:02}", today.month(), today.day());
380    // Include same-year photos as long as they're old enough (>= MIN_PHOTO_AGE_MONTHS).
381    // The cutoff date excludes photos from the recent N months.
382    let cutoff = today - Duration::days(MIN_PHOTO_AGE_MONTHS * 30);
383    let cutoff_str = cutoff.format("%Y-%m-%d").to_string();
384    let mut stmt = conn.prepare(&format!(
385        r#"
386        WITH matched AS (
387            SELECT id,
388                   CAST(strftime('%Y', date_taken) AS INTEGER) AS yr,
389                   ROW_NUMBER() OVER (
390                       PARTITION BY CAST(strftime('%Y', date_taken) AS INTEGER)
391                       ORDER BY date_taken DESC, id DESC
392                   ) AS rn
393            FROM photos p
394            WHERE is_trashed = FALSE
395              AND {NOT_SCREENSHOT}
396              AND date_taken IS NOT NULL
397              AND strftime('%m-%d', date_taken) = ?1
398              AND date_taken < ?2
399        )
400        SELECT yr, GROUP_CONCAT(id) AS photo_ids
401        FROM matched
402        WHERE rn <= ?3
403        GROUP BY yr
404        ORDER BY yr DESC
405        LIMIT 10
406        "#,
407    ))?;
408
409    let rows = stmt.query_map(
410        params![today_md, cutoff_str, MAX_MEMORY_PHOTOS as i64],
411        |row| Ok((row.get::<_, i32>(0)?, row.get::<_, String>(1)?)),
412    )?;
413
414    let mut out = Vec::new();
415    for row in rows {
416        let (yr, csv) = row?;
417        let photo_ids = parse_ids(&csv);
418        if photo_ids.is_empty() {
419            continue;
420        }
421        let photo_date = NaiveDate::from_ymd_opt(yr, today.month(), today.day())
422            .unwrap_or(NaiveDate::from_ymd_opt(yr, 1, 1).unwrap());
423        let title = format!("{} today", age_label(photo_date, today));
424        out.push(Memory {
425            id: memory_id(MemoryKind::OnThisDay, yr, today),
426            kind: MemoryKind::OnThisDay,
427            title,
428            photo_ids,
429            hero_photo_id: 0,
430            hero_thumbnail_path: None,
431            score: 0.0,
432            year: yr,
433            has_faces: false,
434            favorites: 0,
435            named_person: false,
436            hide_key: String::new(),
437        });
438    }
439    Ok(out)
440}
441
442fn fallback_window(
443    conn: &Connection,
444    today: NaiveDate,
445    _current_year: i32,
446) -> SqliteResult<Vec<Memory>> {
447    let mds: Vec<String> = (-3..=3)
448        .map(|offset| {
449            let d = today + Duration::days(offset);
450            format!("{:02}-{:02}", d.month(), d.day())
451        })
452        .collect();
453
454    let cutoff = today - Duration::days(MIN_PHOTO_AGE_MONTHS * 30);
455    let cutoff_str = cutoff.format("%Y-%m-%d").to_string();
456
457    let mut stmt = conn.prepare(&format!(
458        r#"
459        WITH matched AS (
460            SELECT id,
461                   CAST(strftime('%Y', date_taken) AS INTEGER) AS yr,
462                   ROW_NUMBER() OVER (
463                       PARTITION BY CAST(strftime('%Y', date_taken) AS INTEGER)
464                       ORDER BY date_taken DESC, id DESC
465                   ) AS rn
466            FROM photos p
467            WHERE is_trashed = FALSE
468              AND {NOT_SCREENSHOT}
469              AND date_taken IS NOT NULL
470              AND strftime('%m-%d', date_taken) IN (?1, ?2, ?3, ?4, ?5, ?6, ?7)
471              AND date_taken < ?8
472        )
473        SELECT yr, GROUP_CONCAT(id) AS photo_ids
474        FROM matched
475        WHERE rn <= ?9
476        GROUP BY yr
477        ORDER BY yr DESC
478        LIMIT 10
479        "#,
480    ))?;
481
482    let rows = stmt.query_map(
483        params![
484            mds[0],
485            mds[1],
486            mds[2],
487            mds[3],
488            mds[4],
489            mds[5],
490            mds[6],
491            cutoff_str,
492            MAX_MEMORY_PHOTOS as i64
493        ],
494        |row| Ok((row.get::<_, i32>(0)?, row.get::<_, String>(1)?)),
495    )?;
496
497    let mut out = Vec::new();
498    for row in rows {
499        let (yr, csv) = row?;
500        let photo_ids = parse_ids(&csv);
501        if photo_ids.is_empty() {
502            continue;
503        }
504        let photo_date = NaiveDate::from_ymd_opt(yr, today.month(), today.day())
505            .unwrap_or(NaiveDate::from_ymd_opt(yr, 1, 1).unwrap());
506        let title = format!("{} this week", age_label(photo_date, today));
507        out.push(Memory {
508            id: memory_id(MemoryKind::FallbackWindow, yr, today),
509            kind: MemoryKind::FallbackWindow,
510            title,
511            photo_ids,
512            hero_photo_id: 0,
513            hero_thumbnail_path: None,
514            score: 0.0,
515            year: yr,
516            has_faces: false,
517            favorites: 0,
518            named_person: false,
519            hide_key: String::new(),
520        });
521    }
522    Ok(out)
523}
524
525fn seasonal_recap(
526    conn: &Connection,
527    today: NaiveDate,
528    _current_year: i32,
529) -> SqliteResult<Vec<Memory>> {
530    let month = format!("{:02}", today.month());
531    let cutoff = today - Duration::days(MIN_PHOTO_AGE_MONTHS * 30);
532    let cutoff_str = cutoff.format("%Y-%m-%d").to_string();
533
534    let mut stmt = conn.prepare(&format!(
535        r#"
536        WITH matched AS (
537            SELECT id,
538                   CAST(strftime('%Y', date_taken) AS INTEGER) AS yr,
539                   COUNT(*) OVER (
540                       PARTITION BY CAST(strftime('%Y', date_taken) AS INTEGER)
541                   ) AS total_count,
542                   ROW_NUMBER() OVER (
543                       PARTITION BY CAST(strftime('%Y', date_taken) AS INTEGER)
544                       ORDER BY date_taken DESC, id DESC
545                   ) AS rn
546            FROM photos p
547            WHERE is_trashed = FALSE
548              AND {NOT_SCREENSHOT}
549              AND date_taken IS NOT NULL
550              AND strftime('%m', date_taken) = ?1
551              AND date_taken < ?2
552        )
553        SELECT yr, GROUP_CONCAT(id) AS photo_ids
554        FROM matched
555        WHERE rn <= ?4
556        GROUP BY yr
557        HAVING MAX(total_count) >= ?3
558        ORDER BY yr DESC
559        LIMIT 5
560        "#,
561    ))?;
562
563    let rows = stmt.query_map(
564        params![
565            month,
566            cutoff_str,
567            SEASONAL_MIN_PHOTOS,
568            MAX_MEMORY_PHOTOS as i64
569        ],
570        |row| Ok((row.get::<_, i32>(0)?, row.get::<_, String>(1)?)),
571    )?;
572
573    let month_name = month_name(today.month());
574    let mut out = Vec::new();
575    for row in rows {
576        let (yr, csv) = row?;
577        let photo_ids = parse_ids(&csv);
578        if photo_ids.is_empty() {
579            continue;
580        }
581        out.push(Memory {
582            id: memory_id(MemoryKind::SeasonalRecap, yr, today),
583            kind: MemoryKind::SeasonalRecap,
584            title: format!("{} {}, worth another look", month_name, yr),
585            photo_ids,
586            hero_photo_id: 0,
587            hero_thumbnail_path: None,
588            score: 0.0,
589            year: yr,
590            has_faces: false,
591            favorites: 0,
592            named_person: false,
593            hide_key: String::new(),
594        });
595    }
596    Ok(out)
597}
598
599/// Rotate one named person with a real history through the library. Requiring
600/// three separate years keeps this personal without turning every face cluster
601/// into a card.
602fn person_story(conn: &Connection, today: NaiveDate) -> SqliteResult<Option<Memory>> {
603    let mut stmt = conn.prepare(
604        r#"
605        WITH appearances AS (
606            SELECT DISTINCT f.cluster_id, fc.name, p.id AS photo_id,
607                   CAST(strftime('%Y', p.date_taken) AS INTEGER) AS yr,
608                   p.date_taken, p.is_favorite
609            FROM faces f
610            JOIN face_clusters fc ON fc.id = f.cluster_id
611            JOIN photos p ON p.id = f.photo_id
612            LEFT JOIN memory_blocks mb
613              ON mb.kind = 'person' AND mb.target_key = CAST(f.cluster_id AS TEXT)
614            WHERE p.is_trashed = FALSE
615              AND f.user_confirmed >= 0
616              AND p.date_taken IS NOT NULL
617              AND fc.name IS NOT NULL AND TRIM(fc.name) != ''
618              AND mb.id IS NULL
619        ),
620        ranked AS (
621            SELECT *,
622                   ROW_NUMBER() OVER (
623                       PARTITION BY cluster_id, yr
624                       ORDER BY is_favorite DESC, date_taken DESC, photo_id DESC
625                   ) AS rn
626            FROM appearances
627        )
628        SELECT cluster_id, name, GROUP_CONCAT(photo_id), MIN(yr), MAX(yr),
629               COUNT(DISTINCT yr) AS year_count, COUNT(*) AS photo_count
630        FROM ranked
631        WHERE rn <= 8
632        GROUP BY cluster_id, name
633        HAVING year_count >= 3 AND photo_count >= 9
634        ORDER BY year_count DESC, photo_count DESC, name
635        LIMIT 24
636        "#,
637    )?;
638    let rows = stmt.query_map([], |row| {
639        Ok((
640            row.get::<_, i64>(0)?,
641            row.get::<_, String>(1)?,
642            row.get::<_, String>(2)?,
643            row.get::<_, i32>(3)?,
644            row.get::<_, i32>(4)?,
645        ))
646    })?;
647    let candidates = rows.collect::<SqliteResult<Vec<_>>>()?;
648    if candidates.is_empty() {
649        return Ok(None);
650    }
651    let index = today.ordinal0() as usize % candidates.len();
652    let (cluster_id, name, ids, first_year, last_year) = &candidates[index];
653    Ok(Some(Memory {
654        id: format!(
655            "person-{cluster_id}-{}-{:03}",
656            today.year(),
657            today.ordinal()
658        ),
659        kind: MemoryKind::PersonStory,
660        title: format!("{name}, through the years"),
661        photo_ids: parse_ids(ids),
662        hero_photo_id: 0,
663        hero_thumbnail_path: None,
664        score: 0.0,
665        year: *first_year.min(last_year),
666        has_faces: true,
667        favorites: 0,
668        named_person: false,
669        hide_key: String::new(),
670    }))
671}
672
673/// Rotate one non-home place photographed in at least three different years.
674fn place_story(conn: &Connection, today: NaiveDate) -> SqliteResult<Option<Memory>> {
675    // The same home the trips and titles use.
676    let home_city = crate::services::album_suggestions::home(conn).map(|(city, _, _, _)| city);
677    let mut stmt = conn.prepare(&format!(
678        r#"
679        WITH ranked AS (
680            SELECT id, location_city AS city,
681                   CAST(strftime('%Y', date_taken) AS INTEGER) AS yr,
682                   ROW_NUMBER() OVER (
683                       PARTITION BY location_city, CAST(strftime('%Y', date_taken) AS INTEGER)
684                       ORDER BY is_favorite DESC, date_taken DESC, id DESC
685                   ) AS rn
686            FROM photos p
687            WHERE is_trashed = FALSE
688              AND {NOT_SCREENSHOT}
689              AND date_taken IS NOT NULL
690              AND location_city IS NOT NULL AND location_city != ''
691              AND (?1 IS NULL OR location_city != ?1)
692        )
693        SELECT city, GROUP_CONCAT(id), MIN(yr), MAX(yr),
694               COUNT(DISTINCT yr) AS year_count, COUNT(*) AS photo_count
695        FROM ranked
696        WHERE rn <= 8
697        GROUP BY city
698        HAVING year_count >= 3 AND photo_count >= 9
699        ORDER BY year_count DESC, photo_count DESC, city
700        LIMIT 24
701        "#,
702    ))?;
703    let rows = stmt.query_map(params![home_city], |row| {
704        Ok((
705            row.get::<_, String>(0)?,
706            row.get::<_, String>(1)?,
707            row.get::<_, i32>(2)?,
708            row.get::<_, i32>(3)?,
709        ))
710    })?;
711    let candidates = rows.collect::<SqliteResult<Vec<_>>>()?;
712    if candidates.is_empty() {
713        return Ok(None);
714    }
715    let index = (today.ordinal0() as usize / 3) % candidates.len();
716    let (city, ids, first_year, last_year) = &candidates[index];
717    Ok(Some(Memory {
718        id: format!(
719            "place-{}-{}-{:03}",
720            stable_text_id(city),
721            today.year(),
722            today.ordinal()
723        ),
724        kind: MemoryKind::PlaceStory,
725        title: format!("Back to {city}, through the years"),
726        photo_ids: parse_ids(ids),
727        hero_photo_id: 0,
728        hero_thumbnail_path: None,
729        score: 0.0,
730        year: *first_year.min(last_year),
731        has_faces: false,
732        favorites: 0,
733        named_person: false,
734        hide_key: String::new(),
735    }))
736}
737
738/// FNV-1a: the same for a name in every build, so a hidden place stays
739/// hidden after an update (std's hasher makes no such promise).
740fn stable_text_id(value: &str) -> u64 {
741    value.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
742        (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
743    })
744}
745
746fn year_recap(
747    conn: &Connection,
748    today: NaiveDate,
749    _current_year: i32,
750) -> SqliteResult<Vec<Memory>> {
751    let cutoff = today - Duration::days(MIN_PHOTO_AGE_MONTHS * 30);
752    let cutoff_str = cutoff.format("%Y-%m-%d").to_string();
753
754    let mut stmt = conn.prepare(&format!(
755        r#"
756        WITH matched AS (
757            SELECT id,
758                   CAST(strftime('%Y', date_taken) AS INTEGER) AS yr,
759                   ROW_NUMBER() OVER (
760                       PARTITION BY CAST(strftime('%Y', date_taken) AS INTEGER)
761                       ORDER BY date_taken DESC, id DESC
762                   ) AS rn
763            FROM photos p
764            WHERE is_trashed = FALSE
765              AND {NOT_SCREENSHOT}
766              AND date_taken IS NOT NULL
767              AND date_taken < ?1
768        )
769        SELECT yr, GROUP_CONCAT(id) AS photo_ids
770        FROM matched
771        WHERE rn <= ?2
772        GROUP BY yr
773        ORDER BY yr DESC
774        LIMIT 5
775        "#,
776    ))?;
777
778    let rows = stmt.query_map(params![cutoff_str, YEAR_RECAP_MAX_PHOTOS as i64], |row| {
779        Ok((row.get::<_, i32>(0)?, row.get::<_, String>(1)?))
780    })?;
781
782    let mut out = Vec::new();
783    for row in rows {
784        let (yr, csv) = row?;
785        let photo_ids = parse_ids(&csv);
786        if photo_ids.is_empty() {
787            continue;
788        }
789
790        // Use July 1 of that year as a reasonable midpoint for age calculation.
791        let photo_date =
792            NaiveDate::from_ymd_opt(yr, 7, 1).unwrap_or(NaiveDate::from_ymd_opt(yr, 1, 1).unwrap());
793        let title = age_label(photo_date, today);
794        out.push(Memory {
795            id: memory_id(MemoryKind::YearRecap, yr, today),
796            kind: MemoryKind::YearRecap,
797            title,
798            photo_ids,
799            hero_photo_id: 0,
800            hero_thumbnail_path: None,
801            score: 0.0,
802            year: yr,
803            has_faces: false,
804            favorites: 0,
805            named_person: false,
806            hide_key: String::new(),
807        });
808    }
809    Ok(out)
810}
811
812fn month_name(m: u32) -> &'static str {
813    match m {
814        1 => "January",
815        2 => "February",
816        3 => "March",
817        4 => "April",
818        5 => "May",
819        6 => "June",
820        7 => "July",
821        8 => "August",
822        9 => "September",
823        10 => "October",
824        11 => "November",
825        12 => "December",
826        _ => "",
827    }
828}
829
830/// Human-readable age string from a photo date to today.
831/// Uses months when < 24 months; years otherwise.
832fn age_label(photo_date: NaiveDate, today: NaiveDate) -> String {
833    if photo_date >= today {
834        return "Recent".to_string();
835    }
836
837    let mut months = (today.year() - photo_date.year()) * 12
838        + (today.month() as i32 - photo_date.month() as i32);
839    if today.day() < photo_date.day() {
840        months -= 1;
841    }
842    let months = months.max(0);
843
844    if months < 12 {
845        match months {
846            0 => "Recent".to_string(),
847            1 => "1 month ago".to_string(),
848            _ => format!("{} months ago", months),
849        }
850    } else {
851        let years = months / 12;
852        if years == 1 {
853            "1 year ago".to_string()
854        } else {
855            format!("{} years ago", years)
856        }
857    }
858}
859
860// ---------- Curation ----------
861
862/// Keep only each memory's photos worth looking back at (see
863/// [`collage_picks::curate`]) and drop memories left with none. Returns each
864/// kept photo's quality score; videos are left out of it, so they're never
865/// a memory's cover.
866fn curate_photos(conn: &Connection, memories: &mut Vec<Memory>) -> SqliteResult<HashMap<i64, f32>> {
867    let mut scores = HashMap::new();
868    for memory in memories.iter_mut() {
869        let curated = collage_picks::curate(conn, &memory.photo_ids, MAX_SHOWN_PHOTOS, true)?;
870        memory.photo_ids = curated.iter().map(|c| c.id).collect();
871        scores.extend(curated.iter().filter(|c| !c.video).map(|c| (c.id, c.score)));
872    }
873    memories.retain(|m| !m.photo_ids.is_empty());
874    Ok(scores)
875}
876
877// ---------- Hero selection ----------
878
879/// Pick each memory's cover and fill in what ranking and hiding need, via
880/// one batched query over all its photos. The cover is the best photo by
881/// `scores` (favourites and faces first), nudged toward wide shots, which
882/// fill a card, and ones whose thumbnail is ready.
883fn populate_hero_and_faces(
884    conn: &Connection,
885    memories: &mut [Memory],
886    scores: &HashMap<i64, f32>,
887) -> SqliteResult<()> {
888    // Collect all unique photo ids.
889    let mut all_ids: HashSet<i64> = HashSet::new();
890    for m in memories.iter() {
891        all_ids.extend(m.photo_ids.iter().copied());
892    }
893    if all_ids.is_empty() {
894        for mem in memories.iter_mut() {
895            mem.hero_photo_id = 0;
896            mem.hero_thumbnail_path = None;
897            mem.has_faces = false;
898        }
899        return Ok(());
900    }
901
902    let ids_list: Vec<String> = all_ids.iter().map(|i| i.to_string()).collect();
903    let in_clause = ids_list.join(",");
904    let sql = format!(
905        r#"
906        SELECT p.id,
907               COALESCE(p.orientation, 1) AS orientation,
908               COALESCE(p.width, 0) AS width,
909               COALESCE(p.height, 0) AS height,
910               COALESCE((SELECT COUNT(*) FROM faces WHERE photo_id = p.id AND user_confirmed >= 0), 0),
911               p.thumbnail_path,
912               COALESCE(p.is_favorite, FALSE),
913               EXISTS (SELECT 1 FROM faces f JOIN face_clusters fc ON fc.id = f.cluster_id
914                       WHERE f.photo_id = p.id AND f.user_confirmed >= 0
915                         AND fc.name IS NOT NULL AND TRIM(fc.name) != ''),
916               substr(p.date_taken, 1, 10)
917        FROM photos p
918        WHERE p.id IN ({}) AND p.is_trashed = FALSE
919        "#,
920        in_clause
921    );
922
923    #[derive(Clone)]
924    struct PhotoMeta {
925        orientation: i32,
926        width: i32,
927        height: i32,
928        face_count: i64,
929        thumbnail_path: Option<String>,
930        favorite: bool,
931        named_person: bool,
932        day: Option<String>,
933    }
934
935    let mut stmt = conn.prepare(&sql)?;
936    let mut meta: HashMap<i64, PhotoMeta> = HashMap::new();
937    let rows = stmt.query_map([], |row| {
938        Ok((
939            row.get::<_, i64>(0)?,
940            PhotoMeta {
941                orientation: row.get(1)?,
942                width: row.get(2)?,
943                height: row.get(3)?,
944                face_count: row.get(4)?,
945                thumbnail_path: row.get(5)?,
946                favorite: row.get(6)?,
947                named_person: row.get(7)?,
948                day: row.get(8)?,
949            },
950        ))
951    })?;
952    for row in rows {
953        let (id, m) = row?;
954        meta.insert(id, m);
955    }
956
957    for mem in memories.iter_mut() {
958        let Some(mut best_id) = mem.photo_ids.first().copied() else {
959            mem.hero_photo_id = 0;
960            mem.hero_thumbnail_path = None;
961            mem.has_faces = false;
962            continue;
963        };
964        let mut best_score = f32::MIN;
965        let mut days: HashMap<&str, usize> = HashMap::new();
966        mem.has_faces = false;
967        mem.favorites = 0;
968        mem.named_person = false;
969
970        for pid in &mem.photo_ids {
971            let Some(m) = meta.get(pid) else { continue };
972            mem.has_faces |= m.face_count > 0;
973            mem.favorites += usize::from(m.favorite);
974            mem.named_person |= m.named_person;
975            if let Some(day) = &m.day {
976                *days.entry(day.as_str()).or_default() += 1;
977            }
978
979            // Videos have no score: a cover only when there's nothing else.
980            let mut score = scores.get(pid).copied().unwrap_or(-10.0);
981            // Landscape orientations are 1 (unrotated wide) and 3 (180).
982            // 6/8 are rotated portraits. Treat width >= height as landscape too.
983            if matches!(m.orientation, 1 | 3) && m.width >= m.height && m.width > 0 {
984                score += 0.3;
985            }
986            // Prefer photos that already have a thumbnail — avoids
987            // an empty card while on-demand generation runs in the
988            // background.
989            if m.thumbnail_path.is_some() {
990                score += 0.5;
991            }
992            // Tie-breaker toward smaller id (stable).
993            score -= (*pid as f32) * 1e-9;
994
995            if score > best_score {
996                best_score = score;
997                best_id = *pid;
998            }
999        }
1000
1001        // The day most of its photos are from, earliest on a tie.
1002        let main_day = days
1003            .into_iter()
1004            .max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(a.0)))
1005            .map(|(day, _)| day.to_string());
1006        mem.hide_key = hide_key(mem, main_day.as_deref());
1007        mem.hero_photo_id = best_id;
1008        mem.hero_thumbnail_path = meta.get(&best_id).and_then(|m| m.thumbnail_path.clone());
1009    }
1010
1011    Ok(())
1012}
1013
1014// ---------- Hiding ----------
1015
1016/// What a hidden memory stays hidden as. Unlike the memory's id, which is
1017/// per day, this names the moment itself, so "hide" holds next year and for
1018/// the neighbouring days' versions of the same memory: a day for anniversary
1019/// cards, a month, a year, a person or a place.
1020fn hide_key(memory: &Memory, main_day: Option<&str>) -> String {
1021    match memory.kind {
1022        MemoryKind::OnThisDay | MemoryKind::FallbackWindow => match main_day {
1023            Some(day) => format!("day:{day}"),
1024            None => format!("year:{}", memory.year),
1025        },
1026        MemoryKind::SeasonalRecap => match main_day {
1027            Some(day) => format!("month:{}", &day[..day.len().min(7)]),
1028            None => format!("year:{}", memory.year),
1029        },
1030        MemoryKind::YearRecap => format!("year:{}", memory.year),
1031        // "person-<cluster>-<year>-<day>" / "place-<hash>-<year>-<day>".
1032        MemoryKind::PersonStory | MemoryKind::PlaceStory => memory
1033            .id
1034            .rsplitn(3, '-')
1035            .nth(2)
1036            .map(|subject| subject.replacen('-', ":", 1))
1037            .unwrap_or_else(|| memory.id.clone()),
1038    }
1039}
1040
1041fn load_hidden(conn: &Connection) -> SqliteResult<HashSet<String>> {
1042    let mut stmt = conn.prepare("SELECT target_key FROM memory_blocks WHERE kind = ?1")?;
1043    let rows = stmt.query_map([HIDE_BLOCK_KIND], |row| row.get(0))?;
1044    rows.collect()
1045}
1046
1047/// Hide one of today's memories for good. `hide_key` comes from its card.
1048pub fn hide(conn: &Connection, hide_key: &str) -> SqliteResult<()> {
1049    conn.execute(
1050        "INSERT OR IGNORE INTO memory_blocks (kind, target_key) VALUES (?1, ?2)",
1051        params![HIDE_BLOCK_KIND, hide_key],
1052    )?;
1053    Ok(())
1054}
1055
1056/// Undo [`hide`].
1057pub fn unhide(conn: &Connection, hide_key: &str) -> SqliteResult<()> {
1058    conn.execute(
1059        "DELETE FROM memory_blocks WHERE kind = ?1 AND target_key = ?2",
1060        params![HIDE_BLOCK_KIND, hide_key],
1061    )?;
1062    Ok(())
1063}
1064
1065// ---------- Ranking ----------
1066
1067/// Order memories by how much they're likely to mean: favourites and named
1068/// people count most, then a little for age and size (capped, so the
1069/// biggest dump of photos doesn't win by bulk). Kinds the user keeps hiding
1070/// sink, and kinds alternate so the page isn't five anniversaries in a row.
1071fn rank(memories: &mut Vec<Memory>, current_year: i32, hidden: &HashSet<String>) {
1072    let hidden_of = |prefix: &str| hidden.iter().filter(|k| k.starts_with(prefix)).count();
1073    for m in memories.iter_mut() {
1074        let years_ago = (current_year - m.year).clamp(0, 10) as f32;
1075        let count_factor = ((m.photo_ids.len() as f32) + 1.0).log2().min(5.0);
1076        let age_factor = 1.0 + 0.15 * years_ago;
1077        let favorite_factor = 1.0 + 0.3 * m.favorites.min(5) as f32;
1078        let people_factor = if m.named_person {
1079            1.3
1080        } else if m.has_faces {
1081            1.1
1082        } else {
1083            1.0
1084        };
1085        let kind_factor = match m.kind {
1086            MemoryKind::SeasonalRecap => 1.5,
1087            MemoryKind::PersonStory | MemoryKind::PlaceStory => 1.8,
1088            _ => 1.0,
1089        };
1090        let less = if hidden_of(kind_prefix(m.kind)) >= HIDDEN_BEFORE_LESS {
1091            0.5
1092        } else {
1093            1.0
1094        };
1095        m.score = count_factor * age_factor * favorite_factor * people_factor * kind_factor * less;
1096    }
1097    memories.sort_by(|a, b| {
1098        b.score
1099            .partial_cmp(&a.score)
1100            .unwrap_or(std::cmp::Ordering::Equal)
1101    });
1102
1103    // Never two of a kind in a row while another kind is waiting.
1104    let mut rest = std::mem::take(memories);
1105    while !rest.is_empty() {
1106        let last = memories.last().map(|m: &Memory| kind_prefix(m.kind));
1107        let next = rest
1108            .iter()
1109            .position(|m| Some(kind_prefix(m.kind)) != last)
1110            .unwrap_or(0);
1111        memories.push(rest.remove(next));
1112    }
1113}
1114
1115/// The [`hide_key`] prefix memories of this kind are hidden under.
1116fn kind_prefix(kind: MemoryKind) -> &'static str {
1117    match kind {
1118        MemoryKind::OnThisDay | MemoryKind::FallbackWindow => "day:",
1119        MemoryKind::SeasonalRecap => "month:",
1120        MemoryKind::YearRecap => "year:",
1121        MemoryKind::PersonStory => "person:",
1122        MemoryKind::PlaceStory => "place:",
1123    }
1124}
1125
1126// ---------- Block filter ----------
1127
1128fn load_person_blocks(conn: &Connection) -> SqliteResult<HashSet<i64>> {
1129    let mut stmt = conn.prepare("SELECT target_key FROM memory_blocks WHERE kind = 'person'")?;
1130    let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
1131    let mut out = HashSet::new();
1132    for row in rows {
1133        if let Ok(id) = row?.parse::<i64>() {
1134            out.insert(id);
1135        }
1136    }
1137    Ok(out)
1138}
1139
1140/// Drop memories where > 50% of photos contain a face in a blocked cluster.
1141fn filter_blocked(
1142    conn: &Connection,
1143    memories: &mut Vec<Memory>,
1144    blocks: &HashSet<i64>,
1145) -> SqliteResult<()> {
1146    if memories.is_empty() || blocks.is_empty() {
1147        return Ok(());
1148    }
1149
1150    // Collect all photo ids.
1151    let mut all_ids: HashSet<i64> = HashSet::new();
1152    for m in memories.iter() {
1153        all_ids.extend(m.photo_ids.iter().copied());
1154    }
1155    let ids_list: Vec<String> = all_ids.iter().map(|i| i.to_string()).collect();
1156    let blocks_list: Vec<String> = blocks.iter().map(|i| i.to_string()).collect();
1157
1158    let sql = format!(
1159        "SELECT DISTINCT photo_id FROM faces
1160         WHERE cluster_id IN ({}) AND photo_id IN ({})",
1161        blocks_list.join(","),
1162        ids_list.join(",")
1163    );
1164
1165    let mut stmt = conn.prepare(&sql)?;
1166    let rows = stmt.query_map([], |row| row.get::<_, i64>(0))?;
1167    let blocked_photos: HashSet<i64> = rows.collect::<SqliteResult<HashSet<_>>>()?;
1168
1169    memories.retain(|m| {
1170        let blocked_count = m
1171            .photo_ids
1172            .iter()
1173            .filter(|id| blocked_photos.contains(id))
1174            .count();
1175        blocked_count * 2 <= m.photo_ids.len() // keep if blocked photos are not majority
1176    });
1177
1178    Ok(())
1179}
1180
1181// ---------- Tests ----------
1182
1183#[cfg(test)]
1184mod tests {
1185    use super::*;
1186    use rusqlite::Connection;
1187
1188    fn fresh_db() -> Connection {
1189        let conn = Connection::open_in_memory().unwrap();
1190        crate::db::schema::create_schema(&conn).unwrap();
1191        conn
1192    }
1193
1194    fn insert_photo(conn: &Connection, id: i64, date: &str) {
1195        conn.execute(
1196            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, width, height, orientation) \
1197             VALUES (?1, ?2, ?3, 'h' || ?1, 1, ?4, 1920, 1080, 1)",
1198            rusqlite::params![
1199                id,
1200                format!("photo{}.jpg", id),
1201                format!("photo{}.jpg", id),
1202                date,
1203            ],
1204        )
1205        .unwrap();
1206    }
1207
1208    #[test]
1209    fn empty_library_returns_empty() {
1210        let conn = fresh_db();
1211        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1212        let cards = generate_for_today(&conn, today).unwrap();
1213        assert!(cards.is_empty());
1214    }
1215
1216    #[test]
1217    fn surprise_respects_scope_exclusions_and_safety_filters() {
1218        let conn = fresh_db();
1219        for id in 1..=7 {
1220            insert_photo(&conn, id, "2017-11-12T12:00:00Z");
1221        }
1222        conn.execute_batch(
1223            "UPDATE photos SET file_hash = CAST(id AS TEXT);
1224             UPDATE photos SET is_trashed=TRUE WHERE id=2;
1225             UPDATE photos SET media_type='video' WHERE id=3;
1226             UPDATE photos SET file_name='Screenshot_2017-11-12.jpg' WHERE id=4;
1227             INSERT INTO albums(id,name) VALUES(1,'Trip');
1228             INSERT INTO album_photos(album_id,photo_id) VALUES(1,1),(1,2),(1,3),(1,4),(1,5);
1229             UPDATE photos SET is_favorite=TRUE WHERE id=1;
1230             INSERT INTO face_clusters(id,name) VALUES(1,'Blocked');
1231             INSERT INTO faces(photo_id,bbox_x,bbox_y,bbox_width,bbox_height,confidence,embedding,cluster_id)
1232             VALUES(5,0,0,1,1,0.9,zeroblob(16),1);
1233             INSERT INTO memory_blocks(kind,target_key) VALUES('person','1');"
1234        ).unwrap();
1235        assert_eq!(surprise_photos(&conn, Some(1), &[]).unwrap(), vec![1]);
1236        assert!(surprise_photos(&conn, Some(1), &[1]).unwrap().is_empty());
1237        assert_eq!(surprise_photos(&conn, Some(-1), &[]).unwrap(), vec![1]);
1238        assert!(surprise_photos(&conn, Some(999), &[]).unwrap().is_empty());
1239    }
1240
1241    #[test]
1242    fn surprise_limits_moments_and_suppresses_duplicates() {
1243        let conn = fresh_db();
1244        for id in 1..=30 {
1245            insert_photo(&conn, id, "2017-11-12T12:00:00Z");
1246        }
1247        conn.execute_batch("UPDATE photos SET file_hash=CAST(id AS TEXT)")
1248            .unwrap();
1249        let ids = surprise_photos(&conn, None, &[]).unwrap();
1250        assert_eq!(ids.len(), 3);
1251        conn.execute_batch("UPDATE photos SET file_hash='identical'")
1252            .unwrap();
1253        assert_eq!(surprise_photos(&conn, None, &[]).unwrap().len(), 1);
1254        conn.execute_batch("UPDATE photos SET file_hash=CAST(id AS TEXT), phash=0")
1255            .unwrap();
1256        assert_eq!(surprise_photos(&conn, None, &[]).unwrap().len(), 1);
1257    }
1258
1259    #[test]
1260    fn cached_cards_follow_library_changes() {
1261        let conn = fresh_db();
1262        insert_photo(&conn, 1, "2022-04-15 10:00:00");
1263        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1264        assert_eq!(generate_for_today_cached(&conn, today).unwrap().len(), 1);
1265        conn.execute("UPDATE photos SET is_trashed = TRUE WHERE id = 1", [])
1266            .unwrap();
1267        assert!(generate_for_today_cached(&conn, today).unwrap().is_empty());
1268    }
1269
1270    #[test]
1271    fn hero_selection_tolerates_empty_memory_photo_ids() {
1272        let conn = fresh_db();
1273        let mut memories = vec![Memory {
1274            id: "empty".into(),
1275            kind: MemoryKind::FallbackWindow,
1276            title: "Empty".into(),
1277            photo_ids: Vec::new(),
1278            hero_photo_id: 99,
1279            hero_thumbnail_path: Some("stale.jpg".into()),
1280            score: 0.0,
1281            year: 2020,
1282            has_faces: true,
1283            favorites: 0,
1284            named_person: false,
1285            hide_key: String::new(),
1286        }];
1287
1288        populate_hero_and_faces(&conn, &mut memories, &HashMap::new()).unwrap();
1289
1290        assert_eq!(memories[0].hero_photo_id, 0);
1291        assert!(memories[0].hero_thumbnail_path.is_none());
1292        assert!(!memories[0].has_faces);
1293    }
1294
1295    #[test]
1296    fn on_this_day_matches_prior_year() {
1297        let conn = fresh_db();
1298        insert_photo(&conn, 1, "2022-04-15 10:00:00");
1299        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1300        let cards = generate_for_today(&conn, today).unwrap();
1301        assert_eq!(cards.len(), 1);
1302        assert_eq!(cards[0].kind, MemoryKind::OnThisDay);
1303        assert_eq!(cards[0].photo_count, 1);
1304    }
1305
1306    #[test]
1307    fn dense_memory_day_shows_the_best_of_its_photos() {
1308        let conn = fresh_db();
1309        for id in 1..=(MAX_MEMORY_PHOTOS as i64 + 25) {
1310            insert_photo(&conn, id, "2022-04-15 10:00:00");
1311        }
1312
1313        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1314        let cards = generate_for_today(&conn, today).unwrap();
1315        let on_this_day = cards
1316            .iter()
1317            .find(|card| card.kind == MemoryKind::OnThisDay)
1318            .unwrap();
1319
1320        assert_eq!(on_this_day.photo_ids.len(), MAX_SHOWN_PHOTOS);
1321        assert_eq!(on_this_day.photo_count, MAX_SHOWN_PHOTOS);
1322    }
1323
1324    #[test]
1325    fn junk_stays_out_and_favourites_lead() {
1326        let conn = fresh_db();
1327        for id in 1..=4 {
1328            insert_photo(&conn, id, &format!("2022-04-15 1{id}:00:00"));
1329        }
1330        conn.execute_batch(
1331            "UPDATE photos SET file_name = 'Screenshot_20220415.png' WHERE id = 1;
1332             UPDATE photos SET width = 320, height = 240 WHERE id = 2;
1333             UPDATE photos SET is_favorite = TRUE WHERE id = 4;",
1334        )
1335        .unwrap();
1336        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1337        let card = generate_for_today(&conn, today).unwrap().remove(0);
1338        assert_eq!(card.photo_ids, vec![3, 4]);
1339        assert_eq!(card.hero_photo_id, 4);
1340    }
1341
1342    #[test]
1343    fn a_memory_of_only_junk_is_not_shown() {
1344        let conn = fresh_db();
1345        insert_photo(&conn, 1, "2022-04-15 10:00:00");
1346        conn.execute("UPDATE photos SET file_name = 'Screen Shot 1.png'", [])
1347            .unwrap();
1348        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1349        assert!(generate_for_today(&conn, today).unwrap().is_empty());
1350    }
1351
1352    #[test]
1353    fn a_hidden_memory_stays_hidden_on_later_days() {
1354        let conn = fresh_db();
1355        insert_photo(&conn, 1, "2022-04-15 10:00:00");
1356        insert_photo(&conn, 2, "2022-04-15 11:00:00");
1357        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1358        let card = generate_for_today(&conn, today).unwrap().remove(0);
1359        assert_eq!(card.hide_key, "day:2022-04-15");
1360        hide(&conn, &card.hide_key).unwrap();
1361        assert!(generate_for_today(&conn, today).unwrap().is_empty());
1362        // Two days later the same day returns as "this week": still hidden.
1363        let later = NaiveDate::from_ymd_opt(2026, 4, 17).unwrap();
1364        assert!(generate_for_today(&conn, later).unwrap().is_empty());
1365    }
1366
1367    #[test]
1368    fn story_hide_keys_name_the_person_or_place() {
1369        let memory = |kind, id: &str| Memory {
1370            id: id.into(),
1371            kind,
1372            title: String::new(),
1373            photo_ids: vec![1],
1374            hero_photo_id: 1,
1375            hero_thumbnail_path: None,
1376            score: 0.0,
1377            year: 2021,
1378            has_faces: false,
1379            favorites: 0,
1380            named_person: false,
1381            hide_key: String::new(),
1382        };
1383        let person = memory(MemoryKind::PersonStory, "person-7-2026-105");
1384        assert_eq!(hide_key(&person, Some("2021-06-01")), "person:7");
1385        let place = memory(MemoryKind::PlaceStory, "place-123-2026-105");
1386        assert_eq!(hide_key(&place, None), "place:123");
1387        let recap = memory(MemoryKind::SeasonalRecap, "sr-2021-04-15");
1388        assert_eq!(hide_key(&recap, Some("2021-04-09")), "month:2021-04");
1389        assert_eq!(stable_text_id("Goa"), stable_text_id("Goa"));
1390        assert_eq!(stable_text_id("Goa"), 16_933_378_578_193_846_910);
1391    }
1392
1393    #[test]
1394    fn ranking_alternates_kinds_and_sinks_kinds_the_user_hides() {
1395        let memory = |kind, year, photos: usize| Memory {
1396            id: format!("{kind:?}-{year}"),
1397            kind,
1398            title: String::new(),
1399            photo_ids: (0..photos as i64).collect(),
1400            hero_photo_id: 0,
1401            hero_thumbnail_path: None,
1402            score: 0.0,
1403            year,
1404            has_faces: false,
1405            favorites: 0,
1406            named_person: false,
1407            hide_key: String::new(),
1408        };
1409        let mut memories = vec![
1410            memory(MemoryKind::OnThisDay, 2016, 40),
1411            memory(MemoryKind::OnThisDay, 2017, 40),
1412            memory(MemoryKind::SeasonalRecap, 2020, 10),
1413        ];
1414        rank(&mut memories, 2026, &HashSet::new());
1415        let kinds: Vec<_> = memories.iter().map(|m| m.kind).collect();
1416        assert_eq!(kinds[1], MemoryKind::SeasonalRecap);
1417
1418        let hidden: HashSet<String> = ["day:2001-01-01", "day:2002-01-01", "day:2003-01-01"]
1419            .into_iter()
1420            .map(String::from)
1421            .collect();
1422        rank(&mut memories, 2026, &hidden);
1423        assert_eq!(memories[0].kind, MemoryKind::SeasonalRecap);
1424    }
1425
1426    #[test]
1427    fn seasonal_recap_respects_threshold() {
1428        let conn = fresh_db();
1429        // 4 photos in April 2020 — below SEASONAL_MIN_PHOTOS (5).
1430        for i in 0..4 {
1431            insert_photo(&conn, 100 + i, "2020-04-03 10:00:00");
1432        }
1433        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1434        let cards = generate_for_today(&conn, today).unwrap();
1435        assert!(cards.iter().all(|c| c.kind != MemoryKind::SeasonalRecap));
1436    }
1437
1438    #[test]
1439    fn seasonal_recap_surfaces_above_threshold() {
1440        let conn = fresh_db();
1441        // 5 photos in April 2020 — exactly at threshold.
1442        for i in 0..5 {
1443            insert_photo(&conn, 200 + i, "2020-04-03 10:00:00");
1444        }
1445        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1446        let cards = generate_for_today(&conn, today).unwrap();
1447        assert!(cards.iter().any(|c| c.kind == MemoryKind::SeasonalRecap));
1448    }
1449
1450    #[test]
1451    fn fallback_only_when_on_this_day_empty() {
1452        let conn = fresh_db();
1453        insert_photo(&conn, 1, "2023-04-13 10:00:00"); // 3 days before, NOT today
1454        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1455        let cards = generate_for_today(&conn, today).unwrap();
1456        assert_eq!(cards.len(), 1);
1457        assert_eq!(cards[0].kind, MemoryKind::FallbackWindow);
1458    }
1459
1460    #[test]
1461    fn fallback_skipped_if_on_this_day_present() {
1462        let conn = fresh_db();
1463        insert_photo(&conn, 1, "2022-04-15 10:00:00"); // exact today
1464        insert_photo(&conn, 2, "2023-04-13 10:00:00"); // ±3 window
1465        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1466        let cards = generate_for_today(&conn, today).unwrap();
1467        assert!(cards.iter().all(|c| c.kind != MemoryKind::FallbackWindow));
1468    }
1469
1470    #[test]
1471    fn year_recap_fires_when_nothing_else_qualifies() {
1472        let conn = fresh_db();
1473        // Sparse library: 5 photos all on Jan 5, 2022 - won't match today's
1474        // exact date, won't fill the ±3 day window of today (April 15), won't
1475        // hit the seasonal threshold for April. YearRecap should still fire.
1476        for i in 0..5 {
1477            insert_photo(&conn, 300 + i, "2022-01-05 10:00:00");
1478        }
1479        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1480        let cards = generate_for_today(&conn, today).unwrap();
1481        assert!(cards.iter().any(|c| c.kind == MemoryKind::YearRecap));
1482        // And no on-this-day / fallback / seasonal should be present.
1483        assert!(cards.iter().all(|c| c.kind == MemoryKind::YearRecap));
1484    }
1485
1486    #[test]
1487    fn year_recap_does_not_fire_when_others_qualify() {
1488        let conn = fresh_db();
1489        // Photo from today's date 4 years ago — on_this_day will fire.
1490        insert_photo(&conn, 1, "2022-04-15 10:00:00");
1491        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1492        let cards = generate_for_today(&conn, today).unwrap();
1493        assert!(cards.iter().any(|c| c.kind == MemoryKind::OnThisDay));
1494        assert!(cards.iter().all(|c| c.kind != MemoryKind::YearRecap));
1495    }
1496
1497    #[test]
1498    fn library_age_gate() {
1499        let conn = fresh_db();
1500        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1501
1502        // No photos → not old enough.
1503        assert!(!library_is_old_enough(&conn, today));
1504
1505        // Photo from 2 months ago → still not old enough.
1506        insert_photo(&conn, 1, "2026-02-15 10:00:00");
1507        assert!(!library_is_old_enough(&conn, today));
1508
1509        // Photo from 1 year ago → old enough.
1510        insert_photo(&conn, 2, "2025-04-15 10:00:00");
1511        assert!(library_is_old_enough(&conn, today));
1512    }
1513
1514    #[test]
1515    fn memory_id_is_stable() {
1516        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1517        let a = memory_id(MemoryKind::OnThisDay, 2022, today);
1518        let b = memory_id(MemoryKind::OnThisDay, 2022, today);
1519        assert_eq!(a, b);
1520        let c = memory_id(MemoryKind::OnThisDay, 2021, today);
1521        assert_ne!(a, c);
1522    }
1523
1524    #[test]
1525    fn named_person_across_three_years_becomes_a_personal_story() {
1526        let conn = fresh_db();
1527        conn.execute(
1528            "INSERT INTO face_clusters (id, name, is_user_named) VALUES (7, 'Asha', TRUE)",
1529            [],
1530        )
1531        .unwrap();
1532        let mut id = 1_i64;
1533        for year in 2021..=2023 {
1534            for day in 1..=3 {
1535                insert_photo(&conn, id, &format!("{year}-06-{day:02} 10:00:00"));
1536                conn.execute(
1537                    r#"INSERT INTO faces
1538                       (id, photo_id, bbox_x, bbox_y, bbox_width, bbox_height,
1539                        embedding, cluster_id, confidence)
1540                       VALUES (?1, ?1, 0.1, 0.1, 0.3, 0.3, X'00', 7, 0.99)"#,
1541                    [id],
1542                )
1543                .unwrap();
1544                id += 1;
1545            }
1546        }
1547
1548        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1549        let cards = generate_for_today(&conn, today).unwrap();
1550        let story = cards
1551            .iter()
1552            .find(|card| card.kind == MemoryKind::PersonStory)
1553            .unwrap();
1554        assert_eq!(story.title, "Asha, through the years");
1555        assert_eq!(story.photo_count, 9);
1556    }
1557
1558    #[test]
1559    fn recurring_place_story_excludes_the_inferred_home_city() {
1560        let conn = fresh_db();
1561        let mut id = 1_i64;
1562        for year in 2021..=2023 {
1563            for month in 1..=4 {
1564                insert_photo(&conn, id, &format!("{year}-{month:02}-01 10:00:00"));
1565                conn.execute(
1566                    "UPDATE photos SET location_city = 'Delhi', gps_latitude = 28.6,
1567                            gps_longitude = 77.2 WHERE id = ?1",
1568                    [id],
1569                )
1570                .unwrap();
1571                id += 1;
1572            }
1573            for day in 1..=3 {
1574                insert_photo(&conn, id, &format!("{year}-08-{day:02} 10:00:00"));
1575                conn.execute(
1576                    "UPDATE photos SET location_city = 'Goa', gps_latitude = 15.5,
1577                            gps_longitude = 73.8 WHERE id = ?1",
1578                    [id],
1579                )
1580                .unwrap();
1581                id += 1;
1582            }
1583        }
1584
1585        let today = NaiveDate::from_ymd_opt(2026, 4, 15).unwrap();
1586        let cards = generate_for_today(&conn, today).unwrap();
1587        let story = cards
1588            .iter()
1589            .find(|card| card.kind == MemoryKind::PlaceStory)
1590            .unwrap();
1591        assert_eq!(story.title, "Back to Goa, through the years");
1592    }
1593}