immich-lib 1.2.0

A Rust library for the Immich API focused on duplicate management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
//! Letterbox detection and pairing for iPhone 4:3/16:9 crop duplicates.
//!
//! This module identifies duplicate pairs where iPhone photos exist as both:
//! - 4:3 aspect ratio (full sensor, more pixels)
//! - 16:9 aspect ratio (cropped version)
//!
//! The 4:3 version is always preferred as the "keeper" since it contains the full scene.

use std::collections::HashMap;

use chrono::Utc;
use serde::{Deserialize, Serialize};

use crate::models::AssetResponse;

/// Aspect ratio classification for iPhone photos.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AspectRatio {
    /// 4:3 ratio (1.333) - Full sensor capture
    FourThree,
    /// 16:9 ratio (1.778) - Cropped version
    SixteenNine,
}

/// Tolerance for aspect ratio matching.
const RATIO_TOLERANCE: f64 = 0.01;

/// 4:3 aspect ratio value.
const RATIO_4_3: f64 = 4.0 / 3.0; // 1.333...

/// 16:9 aspect ratio value.
const RATIO_16_9: f64 = 16.0 / 9.0; // 1.777...

/// Detect the aspect ratio of an image from its dimensions.
///
/// Uses orientation-agnostic calculation (max/min) to handle both
/// portrait and landscape orientations correctly.
///
/// # Arguments
///
/// * `width` - Image width in pixels
/// * `height` - Image height in pixels
///
/// # Returns
///
/// * `Some(AspectRatio::FourThree)` if ratio is 4:3 (within tolerance)
/// * `Some(AspectRatio::SixteenNine)` if ratio is 16:9 (within tolerance)
/// * `None` for other aspect ratios
///
/// # Examples
///
/// ```
/// use immich_lib::letterbox::detect_aspect_ratio;
///
/// // Landscape 4:3
/// assert!(detect_aspect_ratio(5712, 4284).is_some());
///
/// // Portrait 4:3 (same ratio, just rotated)
/// assert!(detect_aspect_ratio(4284, 5712).is_some());
/// ```
pub fn detect_aspect_ratio(width: u32, height: u32) -> Option<AspectRatio> {
    if width == 0 || height == 0 {
        return None;
    }

    // Use max/min for orientation-agnostic ratio
    let max_dim = width.max(height) as f64;
    let min_dim = width.min(height) as f64;
    let ratio = max_dim / min_dim;

    if (ratio - RATIO_4_3).abs() < RATIO_TOLERANCE {
        Some(AspectRatio::FourThree)
    } else if (ratio - RATIO_16_9).abs() < RATIO_TOLERANCE {
        Some(AspectRatio::SixteenNine)
    } else {
        None
    }
}

/// A detected letterbox pair (4:3 original + 16:9 crop).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LetterboxPair {
    /// The 4:3 version to keep (more pixels, full scene)
    pub keeper: AssetResponse,
    /// The 16:9 version to delete (cropped)
    pub delete: AssetResponse,
    /// Shared capture timestamp
    pub timestamp: String,
    /// Camera identifier (e.g., "Apple iPhone 15 Pro Max")
    pub camera: String,
}

/// Internal key for grouping assets by capture moment.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct PairingKey {
    /// dateTimeOriginal truncated to second
    timestamp_second: String,
    /// Camera manufacturer (e.g., "Apple")
    make: String,
    /// Camera model (e.g., "iPhone 15 Pro Max")
    model: String,
    /// GPS coordinates rounded to 4 decimals, if available
    gps_key: Option<String>,
}

impl PairingKey {
    /// Create a pairing key from an asset.
    ///
    /// Returns None if required fields are missing.
    fn from_asset(asset: &AssetResponse) -> Option<Self> {
        let exif = asset.exif_info.as_ref()?;

        // Require timestamp
        let timestamp = exif.date_time_original.as_ref()?;

        // Truncate to second (remove sub-second precision)
        // Format: "2024-12-23T10:30:45.123Z" -> "2024-12-23T10:30:45"
        let timestamp_second = if let Some(dot_pos) = timestamp.find('.') {
            timestamp[..dot_pos].to_string()
        } else if let Some(z_pos) = timestamp.find('Z') {
            timestamp[..z_pos].to_string()
        } else {
            timestamp.clone()
        };

        // Require make and model
        let make = exif.make.clone()?;
        let model = exif.model.clone()?;

        // Optional GPS key for disambiguation
        let gps_key = match (exif.latitude, exif.longitude) {
            (Some(lat), Some(lon)) => {
                // Round to 4 decimal places (~11 meters precision)
                Some(format!("{:.4},{:.4}", lat, lon))
            }
            _ => None,
        };

        Some(Self {
            timestamp_second,
            make,
            model,
            gps_key,
        })
    }
}

/// Check if an asset is from an iPhone.
fn is_iphone_asset(asset: &AssetResponse) -> bool {
    let Some(exif) = &asset.exif_info else {
        return false;
    };

    let is_apple = exif
        .make
        .as_ref()
        .is_some_and(|make| make.to_lowercase().contains("apple"));

    let is_iphone = exif
        .model
        .as_ref()
        .is_some_and(|model| model.to_lowercase().contains("iphone"));

    is_apple && is_iphone
}

/// Get aspect ratio from asset dimensions.
fn get_asset_aspect_ratio(asset: &AssetResponse) -> Option<AspectRatio> {
    let exif = asset.exif_info.as_ref()?;
    let width = exif.exif_image_width?;
    let height = exif.exif_image_height?;
    detect_aspect_ratio(width, height)
}

/// Find letterbox pairs in a collection of assets.
///
/// Identifies pairs of iPhone photos where one is 4:3 (full sensor)
/// and the other is 16:9 (cropped). These pairs are created when
/// iPhone users take photos in certain modes.
///
/// # Algorithm
///
/// 1. Filter to iPhone images only (make="Apple", model contains "iPhone")
/// 2. Group by pairing key (timestamp + make + model + GPS)
/// 3. For each group with exactly one 4:3 and one 16:9, create a pair
/// 4. Skip ambiguous groups (multiple images of same ratio)
///
/// # Arguments
///
/// * `assets` - Slice of assets to analyze
///
/// # Returns
///
/// Vector of detected letterbox pairs, with 4:3 as keeper and 16:9 as delete.
pub fn find_letterbox_pairs(assets: &[AssetResponse]) -> Vec<LetterboxPair> {
    // Group assets by pairing key
    let mut groups: HashMap<PairingKey, Vec<&AssetResponse>> = HashMap::new();

    for asset in assets {
        // Skip non-iPhone assets
        if !is_iphone_asset(asset) {
            continue;
        }

        // Skip trashed assets
        if asset.is_trashed {
            continue;
        }

        // Skip assets without valid aspect ratio
        if get_asset_aspect_ratio(asset).is_none() {
            continue;
        }

        // Group by pairing key
        if let Some(key) = PairingKey::from_asset(asset) {
            groups.entry(key).or_default().push(asset);
        }
    }

    // Find pairs within each group
    let mut pairs = Vec::new();

    for (key, group_assets) in groups {
        // Separate by aspect ratio
        let mut four_three: Vec<&AssetResponse> = Vec::new();
        let mut sixteen_nine: Vec<&AssetResponse> = Vec::new();

        for asset in group_assets {
            match get_asset_aspect_ratio(asset) {
                Some(AspectRatio::FourThree) => four_three.push(asset),
                Some(AspectRatio::SixteenNine) => sixteen_nine.push(asset),
                None => {}
            }
        }

        // Only create pair if exactly one of each
        if four_three.len() == 1 && sixteen_nine.len() == 1 {
            let keeper = four_three[0];
            let delete = sixteen_nine[0];

            pairs.push(LetterboxPair {
                keeper: keeper.clone(),
                delete: delete.clone(),
                timestamp: key.timestamp_second.clone(),
                camera: format!("{} {}", key.make, key.model),
            });
        }
        // Skip ambiguous groups (multiple of same ratio at same timestamp)
    }

    pairs
}

/// Analysis report for letterbox duplicates.
///
/// This is the serializable output format for letterbox detection,
/// following the same pattern as `DuplicateAnalysis` for consistency.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LetterboxAnalysis {
    /// Detected letterbox pairs (4:3 keeper + 16:9 to delete)
    pub pairs: Vec<LetterboxPair>,

    /// Total number of pairs detected
    pub total_pairs: usize,

    /// Sum of file sizes of assets marked for deletion (bytes)
    pub total_space_recoverable: u64,

    /// Groups skipped due to ambiguity (multiple pairs at same timestamp)
    pub skipped_ambiguous: usize,

    /// Non-Apple assets encountered (ignored for letterbox detection)
    pub skipped_non_iphone: usize,

    /// ISO 8601 timestamp when analysis was performed
    pub analyzed_at: String,
}

impl LetterboxAnalysis {
    /// Build a letterbox analysis from a collection of assets.
    ///
    /// Internally calls `find_letterbox_pairs` and computes summary statistics.
    ///
    /// # Arguments
    ///
    /// * `assets` - Slice of assets to analyze for letterbox pairs
    ///
    /// # Returns
    ///
    /// Analysis report with detected pairs and statistics.
    pub fn from_assets(assets: &[AssetResponse]) -> Self {
        // Count non-iPhone assets
        let skipped_non_iphone = assets
            .iter()
            .filter(|a| !is_iphone_asset(a))
            .count();

        // Count iPhone assets grouped by pairing key
        let mut groups: HashMap<PairingKey, Vec<&AssetResponse>> = HashMap::new();
        for asset in assets {
            if !is_iphone_asset(asset) {
                continue;
            }
            if asset.is_trashed {
                continue;
            }
            if get_asset_aspect_ratio(asset).is_none() {
                continue;
            }
            if let Some(key) = PairingKey::from_asset(asset) {
                groups.entry(key).or_default().push(asset);
            }
        }

        // Count ambiguous groups (more than one of same ratio)
        let skipped_ambiguous = groups
            .values()
            .filter(|group| {
                let four_three_count = group
                    .iter()
                    .filter(|a| get_asset_aspect_ratio(a) == Some(AspectRatio::FourThree))
                    .count();
                let sixteen_nine_count = group
                    .iter()
                    .filter(|a| get_asset_aspect_ratio(a) == Some(AspectRatio::SixteenNine))
                    .count();
                // Ambiguous if >1 of either ratio with at least one of the other
                (four_three_count > 1 && sixteen_nine_count > 0)
                    || (sixteen_nine_count > 1 && four_three_count > 0)
            })
            .count();

        // Find pairs
        let pairs = find_letterbox_pairs(assets);

        // Calculate space recoverable from delete assets
        let total_space_recoverable = pairs
            .iter()
            .filter_map(|pair| {
                pair.delete
                    .exif_info
                    .as_ref()
                    .and_then(|e| e.file_size_in_byte)
            })
            .sum();

        Self {
            total_pairs: pairs.len(),
            pairs,
            total_space_recoverable,
            skipped_ambiguous,
            skipped_non_iphone,
            analyzed_at: Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
        }
    }

    /// Returns asset IDs of all assets marked for deletion.
    pub fn delete_ids(&self) -> Vec<&str> {
        self.pairs.iter().map(|p| p.delete.id.as_str()).collect()
    }

    /// Returns asset IDs of all keepers.
    pub fn keeper_ids(&self) -> Vec<&str> {
        self.pairs.iter().map(|p| p.keeper.id.as_str()).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{AssetType, ExifInfo};

    /// Helper to create a mock asset with configurable EXIF data.
    fn mock_asset(
        id: &str,
        width: Option<u32>,
        height: Option<u32>,
        make: Option<&str>,
        model: Option<&str>,
        timestamp: Option<&str>,
        lat: Option<f64>,
        lon: Option<f64>,
    ) -> AssetResponse {
        let exif = ExifInfo {
            exif_image_width: width,
            exif_image_height: height,
            make: make.map(String::from),
            model: model.map(String::from),
            date_time_original: timestamp.map(String::from),
            latitude: lat,
            longitude: lon,
            // Required fields with defaults
            city: None,
            state: None,
            country: None,
            time_zone: None,
            lens_model: None,
            exposure_time: None,
            f_number: None,
            focal_length: None,
            iso: None,
            file_size_in_byte: None,
            description: None,
            rating: None,
            orientation: None,
            modify_date: None,
            projection_type: None,
        };

        AssetResponse {
            id: id.to_string(),
            original_file_name: format!("{}.HEIC", id),
            file_created_at: "2024-12-23T10:30:45Z".to_string(),
            local_date_time: "2024-12-23T10:30:45".to_string(),
            asset_type: AssetType::Image,
            exif_info: Some(exif),
            checksum: "abc123".to_string(),
            is_trashed: false,
            is_favorite: false,
            is_archived: false,
            has_metadata: true,
            duration: "0:00:00.000000".to_string(),
            owner_id: "owner-1".to_string(),
            original_mime_type: Some("image/heic".to_string()),
            duplicate_id: None,
            thumbhash: None,
        }
    }

    // ============ Aspect Ratio Detection Tests ============

    #[test]
    fn test_detect_4_3_landscape() {
        // iPhone 15 Pro Max 4:3 dimensions
        assert_eq!(
            detect_aspect_ratio(5712, 4284),
            Some(AspectRatio::FourThree)
        );
    }

    #[test]
    fn test_detect_4_3_portrait() {
        // Portrait orientation (rotated 90 degrees)
        assert_eq!(
            detect_aspect_ratio(4284, 5712),
            Some(AspectRatio::FourThree)
        );
    }

    #[test]
    fn test_detect_16_9_landscape() {
        // iPhone 15 Pro Max 16:9 dimensions
        assert_eq!(
            detect_aspect_ratio(5712, 3213),
            Some(AspectRatio::SixteenNine)
        );
    }

    #[test]
    fn test_detect_16_9_portrait() {
        // Portrait orientation
        assert_eq!(
            detect_aspect_ratio(3213, 5712),
            Some(AspectRatio::SixteenNine)
        );
    }

    #[test]
    fn test_detect_other_ratio_1_1() {
        // Square image - not 4:3 or 16:9
        assert_eq!(detect_aspect_ratio(1000, 1000), None);
    }

    #[test]
    fn test_detect_other_ratio_3_2() {
        // 3:2 ratio (common in DSLRs) - not 4:3 or 16:9
        assert_eq!(detect_aspect_ratio(3000, 2000), None);
    }

    #[test]
    fn test_detect_with_tolerance_4_3_edge() {
        // Edge case near 4:3 boundary
        // 4:3 = 1.333..., tolerance = 0.01
        // 1.333 + 0.009 = 1.342 should still match
        // 1000 / 745 = 1.342
        assert_eq!(
            detect_aspect_ratio(1000, 745),
            Some(AspectRatio::FourThree)
        );
    }

    #[test]
    fn test_detect_with_tolerance_16_9_edge() {
        // Edge case near 16:9 boundary
        // 16:9 = 1.778..., tolerance = 0.01
        // 1778 / 1000 = 1.778 should match
        assert_eq!(
            detect_aspect_ratio(1778, 1000),
            Some(AspectRatio::SixteenNine)
        );
    }

    #[test]
    fn test_detect_zero_dimension() {
        assert_eq!(detect_aspect_ratio(0, 100), None);
        assert_eq!(detect_aspect_ratio(100, 0), None);
        assert_eq!(detect_aspect_ratio(0, 0), None);
    }

    #[test]
    fn test_detect_hd_16_9() {
        // Standard HD 16:9 dimensions
        assert_eq!(
            detect_aspect_ratio(1920, 1080),
            Some(AspectRatio::SixteenNine)
        );
    }

    #[test]
    fn test_detect_4k_16_9() {
        // 4K 16:9 dimensions
        assert_eq!(
            detect_aspect_ratio(3840, 2160),
            Some(AspectRatio::SixteenNine)
        );
    }

    // ============ Pairing Tests ============

    #[test]
    fn test_find_pair_basic() {
        // One 4:3 + one 16:9 at same timestamp from iPhone
        let assets = vec![
            mock_asset(
                "asset-4-3",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45.123Z"),
                Some(51.5074),
                Some(-0.1278),
            ),
            mock_asset(
                "asset-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45.456Z"),
                Some(51.5074),
                Some(-0.1278),
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);

        assert_eq!(pairs.len(), 1);
        assert_eq!(pairs[0].keeper.id, "asset-4-3");
        assert_eq!(pairs[0].delete.id, "asset-16-9");
        assert_eq!(pairs[0].camera, "Apple iPhone 15 Pro Max");
    }

    #[test]
    fn test_skip_non_iphone() {
        // Android assets should be ignored
        let assets = vec![
            mock_asset(
                "asset-4-3",
                Some(4000),
                Some(3000),
                Some("Samsung"),
                Some("Galaxy S23"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
            mock_asset(
                "asset-16-9",
                Some(4000),
                Some(2250),
                Some("Samsung"),
                Some("Galaxy S23"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        assert!(pairs.is_empty());
    }

    #[test]
    fn test_skip_missing_timestamp() {
        // Assets without dateTimeOriginal should be skipped
        let assets = vec![
            mock_asset(
                "asset-4-3",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                None, // No timestamp
                None,
                None,
            ),
            mock_asset(
                "asset-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                None, // No timestamp
                None,
                None,
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        assert!(pairs.is_empty());
    }

    #[test]
    fn test_skip_ambiguous_two_4_3() {
        // Two 4:3 at same timestamp = ambiguous, skip
        let assets = vec![
            mock_asset(
                "asset-4-3-a",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
            mock_asset(
                "asset-4-3-b",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
            mock_asset(
                "asset-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        assert!(pairs.is_empty()); // Ambiguous, so no pair
    }

    #[test]
    fn test_skip_ambiguous_two_16_9() {
        // Two 16:9 at same timestamp = ambiguous, skip
        let assets = vec![
            mock_asset(
                "asset-4-3",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
            mock_asset(
                "asset-16-9-a",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
            mock_asset(
                "asset-16-9-b",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        assert!(pairs.is_empty()); // Ambiguous, so no pair
    }

    #[test]
    fn test_multiple_pairs_different_timestamps() {
        // Two separate pairs at different timestamps
        let assets = vec![
            // Pair 1 at 10:30:45
            mock_asset(
                "pair1-4-3",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
            mock_asset(
                "pair1-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
            // Pair 2 at 11:00:00
            mock_asset(
                "pair2-4-3",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T11:00:00Z"),
                None,
                None,
            ),
            mock_asset(
                "pair2-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T11:00:00Z"),
                None,
                None,
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        assert_eq!(pairs.len(), 2);
    }

    #[test]
    fn test_gps_disambiguation() {
        // Same timestamp but different GPS = separate groups (no pairs formed)
        let assets = vec![
            mock_asset(
                "loc1-4-3",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(51.5074), // London
                Some(-0.1278),
            ),
            mock_asset(
                "loc2-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(40.7128), // New York
                Some(-74.0060),
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        // Different GPS means different groups, so no pair
        assert!(pairs.is_empty());
    }

    #[test]
    fn test_gps_same_location_pairs() {
        // Same timestamp AND same GPS = should pair
        let assets = vec![
            mock_asset(
                "asset-4-3",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(51.5074),
                Some(-0.1278),
            ),
            mock_asset(
                "asset-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(51.5074), // Same GPS
                Some(-0.1278),
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        assert_eq!(pairs.len(), 1);
    }

    #[test]
    fn test_skip_trashed_assets() {
        let mut asset_4_3 = mock_asset(
            "asset-4-3",
            Some(5712),
            Some(4284),
            Some("Apple"),
            Some("iPhone 15 Pro Max"),
            Some("2024-12-23T10:30:45Z"),
            None,
            None,
        );
        asset_4_3.is_trashed = true;

        let asset_16_9 = mock_asset(
            "asset-16-9",
            Some(5712),
            Some(3213),
            Some("Apple"),
            Some("iPhone 15 Pro Max"),
            Some("2024-12-23T10:30:45Z"),
            None,
            None,
        );

        let assets = vec![asset_4_3, asset_16_9];
        let pairs = find_letterbox_pairs(&assets);
        assert!(pairs.is_empty()); // 4:3 is trashed, no pair
    }

    #[test]
    fn test_skip_missing_dimensions() {
        // Assets without dimensions should be skipped
        let assets = vec![
            mock_asset(
                "asset-4-3",
                None, // No width
                None, // No height
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
            mock_asset(
                "asset-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        assert!(pairs.is_empty());
    }

    #[test]
    fn test_different_iphone_models_no_pair() {
        // Same timestamp but different iPhone models = different groups
        let assets = vec![
            mock_asset(
                "asset-4-3",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
            mock_asset(
                "asset-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 14 Pro"), // Different model
                Some("2024-12-23T10:30:45Z"),
                None,
                None,
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        assert!(pairs.is_empty()); // Different models, no pair
    }

    #[test]
    fn test_only_4_3_no_pair() {
        // Only 4:3 images, no 16:9 = no pair
        let assets = vec![mock_asset(
            "asset-4-3",
            Some(5712),
            Some(4284),
            Some("Apple"),
            Some("iPhone 15 Pro Max"),
            Some("2024-12-23T10:30:45Z"),
            None,
            None,
        )];

        let pairs = find_letterbox_pairs(&assets);
        assert!(pairs.is_empty());
    }

    #[test]
    fn test_only_16_9_no_pair() {
        // Only 16:9 images, no 4:3 = no pair
        let assets = vec![mock_asset(
            "asset-16-9",
            Some(5712),
            Some(3213),
            Some("Apple"),
            Some("iPhone 15 Pro Max"),
            Some("2024-12-23T10:30:45Z"),
            None,
            None,
        )];

        let pairs = find_letterbox_pairs(&assets);
        assert!(pairs.is_empty());
    }

    #[test]
    fn test_subsecond_timestamp_handling() {
        // Different sub-second precision should still match (truncated to second)
        let assets = vec![
            mock_asset(
                "asset-4-3",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45.123Z"),
                None,
                None,
            ),
            mock_asset(
                "asset-16-9",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45.999Z"), // Different sub-second
                None,
                None,
            ),
        ];

        let pairs = find_letterbox_pairs(&assets);
        assert_eq!(pairs.len(), 1); // Should pair (same second)
    }

    // ============ LetterboxAnalysis Tests ============

    /// Helper to create mock asset with file size.
    fn mock_asset_with_size(
        id: &str,
        width: Option<u32>,
        height: Option<u32>,
        make: Option<&str>,
        model: Option<&str>,
        timestamp: Option<&str>,
        file_size: Option<u64>,
    ) -> AssetResponse {
        let exif = ExifInfo {
            exif_image_width: width,
            exif_image_height: height,
            make: make.map(String::from),
            model: model.map(String::from),
            date_time_original: timestamp.map(String::from),
            latitude: None,
            longitude: None,
            city: None,
            state: None,
            country: None,
            time_zone: None,
            lens_model: None,
            exposure_time: None,
            f_number: None,
            focal_length: None,
            iso: None,
            file_size_in_byte: file_size,
            description: None,
            rating: None,
            orientation: None,
            modify_date: None,
            projection_type: None,
        };

        AssetResponse {
            id: id.to_string(),
            original_file_name: format!("{}.HEIC", id),
            file_created_at: "2024-12-23T10:30:45Z".to_string(),
            local_date_time: "2024-12-23T10:30:45".to_string(),
            asset_type: AssetType::Image,
            exif_info: Some(exif),
            checksum: "abc123".to_string(),
            is_trashed: false,
            is_favorite: false,
            is_archived: false,
            has_metadata: true,
            duration: "0:00:00.000000".to_string(),
            owner_id: "owner-1".to_string(),
            original_mime_type: Some("image/heic".to_string()),
            duplicate_id: None,
            thumbhash: None,
        }
    }

    #[test]
    fn test_letterbox_analysis_from_assets() {
        let assets = vec![
            // Valid pair
            mock_asset_with_size(
                "keeper-1",
                Some(5712),
                Some(4284), // 4:3
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(10_000_000), // 10MB
            ),
            mock_asset_with_size(
                "delete-1",
                Some(5712),
                Some(3213), // 16:9
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(8_000_000), // 8MB
            ),
            // Non-iPhone asset (should be skipped)
            mock_asset_with_size(
                "android-1",
                Some(4000),
                Some(3000),
                Some("Samsung"),
                Some("Galaxy S23"),
                Some("2024-12-23T11:00:00Z"),
                Some(5_000_000),
            ),
        ];

        let analysis = LetterboxAnalysis::from_assets(&assets);

        assert_eq!(analysis.total_pairs, 1);
        assert_eq!(analysis.pairs.len(), 1);
        assert_eq!(analysis.total_space_recoverable, 8_000_000);
        assert_eq!(analysis.skipped_non_iphone, 1);
        assert_eq!(analysis.skipped_ambiguous, 0);
        assert!(!analysis.analyzed_at.is_empty());
    }

    #[test]
    fn test_letterbox_analysis_delete_ids() {
        let assets = vec![
            mock_asset_with_size(
                "keeper-1",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(10_000_000),
            ),
            mock_asset_with_size(
                "delete-1",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(8_000_000),
            ),
        ];

        let analysis = LetterboxAnalysis::from_assets(&assets);
        let delete_ids = analysis.delete_ids();

        assert_eq!(delete_ids.len(), 1);
        assert_eq!(delete_ids[0], "delete-1");
    }

    #[test]
    fn test_letterbox_analysis_keeper_ids() {
        let assets = vec![
            mock_asset_with_size(
                "keeper-1",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(10_000_000),
            ),
            mock_asset_with_size(
                "delete-1",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(8_000_000),
            ),
        ];

        let analysis = LetterboxAnalysis::from_assets(&assets);
        let keeper_ids = analysis.keeper_ids();

        assert_eq!(keeper_ids.len(), 1);
        assert_eq!(keeper_ids[0], "keeper-1");
    }

    #[test]
    fn test_letterbox_analysis_serialization() {
        let assets = vec![
            mock_asset_with_size(
                "keeper-1",
                Some(5712),
                Some(4284),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(10_000_000),
            ),
            mock_asset_with_size(
                "delete-1",
                Some(5712),
                Some(3213),
                Some("Apple"),
                Some("iPhone 15 Pro Max"),
                Some("2024-12-23T10:30:45Z"),
                Some(8_000_000),
            ),
        ];

        let analysis = LetterboxAnalysis::from_assets(&assets);

        // Test JSON serialization
        let json = serde_json::to_string_pretty(&analysis).expect("should serialize to JSON");
        assert!(json.contains("total_pairs"));
        assert!(json.contains("total_space_recoverable"));
        assert!(json.contains("keeper"));
        assert!(json.contains("delete"));

        // Test JSON deserialization round-trip
        let parsed: LetterboxAnalysis =
            serde_json::from_str(&json).expect("should deserialize from JSON");
        assert_eq!(parsed.total_pairs, analysis.total_pairs);
        assert_eq!(
            parsed.total_space_recoverable,
            analysis.total_space_recoverable
        );
    }

    #[test]
    fn test_letterbox_analysis_empty() {
        let assets: Vec<AssetResponse> = vec![];
        let analysis = LetterboxAnalysis::from_assets(&assets);

        assert_eq!(analysis.total_pairs, 0);
        assert_eq!(analysis.pairs.len(), 0);
        assert_eq!(analysis.total_space_recoverable, 0);
        assert_eq!(analysis.skipped_non_iphone, 0);
        assert_eq!(analysis.skipped_ambiguous, 0);
    }
}