tracematch 0.0.1

High-performance GPS route matching and activity analysis
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
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
//! # Route Engine
//!
//! Stateful route management engine that keeps all route data in Rust.
//! This eliminates FFI overhead for ongoing operations by maintaining state
//! on the Rust side rather than passing data back and forth with JS.
//!
//! ## Architecture
//!
//! The engine is a singleton that manages:
//! - Activities with their GPS coordinates
//! - Pre-computed route signatures
//! - Route groupings (similar routes)
//! - Frequent sections
//! - Spatial index for viewport queries
//!
//! JS/mobile code interacts through thin FFI calls that trigger computation
//! but don't require large data transfers.

use std::collections::{HashMap, HashSet};
use std::sync::Mutex;

use once_cell::sync::Lazy;
use rstar::{RTree, RTreeObject, AABB};

use crate::{
    ActivityMetrics, Bounds, FrequentSection, GpsPoint, MatchConfig, RouteGroup, RoutePerformance,
    RoutePerformanceResult, RouteSignature, SectionConfig, SectionLap, SectionPerformanceRecord,
    SectionPerformanceResult,
};

#[cfg(not(feature = "parallel"))]
use crate::group_signatures;

#[cfg(feature = "parallel")]
use crate::{group_incremental, group_signatures_parallel};

// ============================================================================
// Core Types
// ============================================================================

/// Activity data stored in the engine
#[derive(Debug, Clone)]
pub struct ActivityData {
    pub id: String,
    pub coords: Vec<GpsPoint>,
    pub sport_type: String,
    pub bounds: Option<Bounds>,
}

/// Bounds wrapper for R-tree spatial indexing
#[derive(Debug, Clone)]
pub struct ActivityBounds {
    pub activity_id: String,
    pub min_lat: f64,
    pub max_lat: f64,
    pub min_lng: f64,
    pub max_lng: f64,
}

impl RTreeObject for ActivityBounds {
    type Envelope = AABB<[f64; 2]>;

    fn envelope(&self) -> Self::Envelope {
        AABB::from_corners([self.min_lng, self.min_lat], [self.max_lng, self.max_lat])
    }
}

/// Engine event types for notifying JS of changes
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "ffi", derive(uniffi::Enum))]
pub enum EngineEvent {
    ActivitiesChanged,
    GroupsChanged,
    SectionsChanged,
}

// ============================================================================
// Route Engine
// ============================================================================

/// The main stateful route engine.
///
/// Maintains all route-related state in Rust, eliminating FFI overhead
/// for ongoing operations. State is incrementally updated as activities
/// are added or removed.
pub struct RouteEngine {
    // Core state
    activities: HashMap<String, ActivityData>,
    signatures: HashMap<String, RouteSignature>,
    groups: Vec<RouteGroup>,
    sections: Vec<FrequentSection>,

    // Spatial index for viewport queries
    spatial_index: RTree<ActivityBounds>,

    // Caches
    consensus_cache: HashMap<String, Vec<GpsPoint>>,

    // Custom route names (route_id -> custom_name)
    route_names: HashMap<String, String>,

    // Dirty tracking for incremental updates
    dirty_signatures: HashSet<String>,
    /// Track which signatures are "new" (just computed, not yet grouped)
    new_signatures: HashSet<String>,
    groups_dirty: bool,
    sections_dirty: bool,
    spatial_dirty: bool,

    // Configuration
    match_config: MatchConfig,
    section_config: SectionConfig,

    // Performance data
    /// Activity metadata for performance calculations
    activity_metrics: HashMap<String, ActivityMetrics>,
    /// Time streams for section calculations (activity_id -> time values in seconds)
    time_streams: HashMap<String, Vec<u32>>,
}

impl RouteEngine {
    /// Create a new route engine with default configuration.
    pub fn new() -> Self {
        Self {
            activities: HashMap::new(),
            signatures: HashMap::new(),
            groups: Vec::new(),
            sections: Vec::new(),
            spatial_index: RTree::new(),
            consensus_cache: HashMap::new(),
            route_names: HashMap::new(),
            dirty_signatures: HashSet::new(),
            new_signatures: HashSet::new(),
            groups_dirty: false,
            sections_dirty: false,
            spatial_dirty: false,
            match_config: MatchConfig::default(),
            section_config: SectionConfig::default(),
            activity_metrics: HashMap::new(),
            time_streams: HashMap::new(),
        }
    }

    /// Create a new route engine with custom configuration.
    pub fn with_config(match_config: MatchConfig, section_config: SectionConfig) -> Self {
        Self {
            match_config,
            section_config,
            ..Self::new()
        }
    }

    // ========================================================================
    // Activity Management
    // ========================================================================

    /// Add an activity with its GPS coordinates.
    ///
    /// The signature is computed lazily when needed. This allows batch
    /// additions to be more efficient.
    pub fn add_activity(&mut self, id: String, coords: Vec<GpsPoint>, sport_type: String) {
        let bounds = Bounds::from_points(&coords);

        let activity = ActivityData {
            id: id.clone(),
            coords,
            sport_type,
            bounds,
        };

        self.activities.insert(id.clone(), activity);
        self.dirty_signatures.insert(id);
        self.groups_dirty = true;
        self.sections_dirty = true;
        self.spatial_dirty = true;
    }

    /// Add an activity from flat coordinate buffer.
    ///
    /// Coordinates are [lat1, lng1, lat2, lng2, ...].
    pub fn add_activity_flat(&mut self, id: String, flat_coords: &[f64], sport_type: String) {
        let coords: Vec<GpsPoint> = flat_coords
            .chunks_exact(2)
            .map(|chunk| GpsPoint::new(chunk[0], chunk[1]))
            .collect();
        self.add_activity(id, coords, sport_type);
    }

    /// Add multiple activities from flat coordinate buffers.
    ///
    /// This is the most efficient way to bulk-add activities from JS.
    pub fn add_activities_flat(
        &mut self,
        activity_ids: &[String],
        all_coords: &[f64],
        offsets: &[u32],
        sport_types: &[String],
    ) {
        for (i, id) in activity_ids.iter().enumerate() {
            let start = offsets[i] as usize;
            let end = offsets
                .get(i + 1)
                .map(|&o| o as usize)
                .unwrap_or(all_coords.len() / 2);

            let coords: Vec<GpsPoint> = (start..end)
                .filter_map(|j| {
                    let idx = j * 2;
                    if idx + 1 < all_coords.len() {
                        Some(GpsPoint::new(all_coords[idx], all_coords[idx + 1]))
                    } else {
                        None
                    }
                })
                .collect();

            let sport = sport_types.get(i).cloned().unwrap_or_default();
            self.add_activity(id.clone(), coords, sport);
        }
    }

    /// Remove an activity.
    ///
    /// Note: Removal requires full recomputation of groups (can't be done incrementally).
    pub fn remove_activity(&mut self, id: &str) {
        self.activities.remove(id);
        self.signatures.remove(id);
        self.dirty_signatures.remove(id);
        self.new_signatures.remove(id);
        // Force full recomputation by clearing new_signatures and groups
        self.new_signatures.clear();
        self.groups.clear();
        self.consensus_cache.clear(); // Invalidate all consensus caches
        self.groups_dirty = true;
        self.sections_dirty = true;
        self.spatial_dirty = true;
    }

    /// Remove multiple activities.
    ///
    /// Note: Removal requires full recomputation of groups (can't be done incrementally).
    pub fn remove_activities(&mut self, ids: &[String]) {
        for id in ids {
            self.activities.remove(id);
            self.signatures.remove(id);
            self.dirty_signatures.remove(id);
            self.new_signatures.remove(id);
        }
        if !ids.is_empty() {
            // Force full recomputation
            self.new_signatures.clear();
            self.groups.clear();
            self.consensus_cache.clear();
            self.groups_dirty = true;
            self.sections_dirty = true;
            self.spatial_dirty = true;
        }
    }

    /// Clear all activities and reset state.
    pub fn clear(&mut self) {
        self.activities.clear();
        self.signatures.clear();
        self.groups.clear();
        self.sections.clear();
        self.spatial_index = RTree::new();
        self.consensus_cache.clear();
        self.dirty_signatures.clear();
        self.new_signatures.clear();
        self.groups_dirty = false;
        self.sections_dirty = false;
        self.spatial_dirty = false;
        self.activity_metrics.clear();
        self.time_streams.clear();
    }

    /// Get all activity IDs.
    pub fn get_activity_ids(&self) -> Vec<String> {
        self.activities.keys().cloned().collect()
    }

    /// Get the number of activities.
    pub fn activity_count(&self) -> usize {
        self.activities.len()
    }

    /// Check if an activity exists.
    pub fn has_activity(&self, id: &str) -> bool {
        self.activities.contains_key(id)
    }

    // ========================================================================
    // Signature Operations
    // ========================================================================

    /// Ensure all dirty signatures are computed.
    /// Newly computed signatures are tracked in `new_signatures` for incremental grouping.
    fn ensure_signatures(&mut self) {
        if self.dirty_signatures.is_empty() {
            return;
        }

        let dirty_ids: Vec<String> = self.dirty_signatures.drain().collect();

        for id in dirty_ids {
            if let Some(activity) = self.activities.get(&id) {
                if let Some(sig) =
                    RouteSignature::from_points(&activity.id, &activity.coords, &self.match_config)
                {
                    self.signatures.insert(id.clone(), sig);
                    // Track as new signature for incremental grouping
                    self.new_signatures.insert(id);
                }
            }
        }
    }

    /// Get a signature for an activity.
    pub fn get_signature(&mut self, id: &str) -> Option<&RouteSignature> {
        // Ensure signature is computed
        if self.dirty_signatures.contains(id) {
            self.ensure_signatures();
        }
        self.signatures.get(id)
    }

    /// Get all signatures.
    pub fn get_all_signatures(&mut self) -> Vec<&RouteSignature> {
        self.ensure_signatures();
        self.signatures.values().collect()
    }

    /// Get signature points for an activity as JSON.
    /// Returns empty string if activity not found.
    pub fn get_signature_points_json(&mut self, id: &str) -> String {
        if let Some(sig) = self.get_signature(id) {
            serde_json::to_string(&sig.points).unwrap_or_else(|_| "[]".to_string())
        } else {
            "[]".to_string()
        }
    }

    /// Get signature points for multiple activities as JSON.
    /// Returns a map of activity_id -> points array.
    pub fn get_signatures_for_group_json(&mut self, group_id: &str) -> String {
        self.ensure_groups();

        // Find the group
        let activity_ids: Vec<String> = self
            .groups
            .iter()
            .find(|g| g.group_id == group_id)
            .map(|g| g.activity_ids.clone())
            .unwrap_or_default();

        // Build map of activity_id -> points
        let mut result: std::collections::HashMap<String, Vec<GpsPoint>> =
            std::collections::HashMap::new();
        for id in &activity_ids {
            if let Some(sig) = self.get_signature(id) {
                result.insert(id.clone(), sig.points.clone());
            }
        }

        serde_json::to_string(&result).unwrap_or_else(|_| "{}".to_string())
    }

    // ========================================================================
    // Grouping
    // ========================================================================

    /// Ensure groups are computed.
    ///
    /// Uses incremental grouping when:
    /// - We have existing groups (not starting fresh)
    /// - We have new signatures to add
    ///
    /// Falls back to full grouping when:
    /// - No existing groups (first computation)
    /// - Activity removal requires full recomputation
    fn ensure_groups(&mut self) {
        if !self.groups_dirty {
            return;
        }

        self.ensure_signatures();

        #[cfg(feature = "parallel")]
        {
            // Check if we can use incremental grouping
            let can_use_incremental = !self.groups.is_empty()
                && !self.new_signatures.is_empty()
                && self.signatures.len() > self.new_signatures.len();

            if can_use_incremental {
                // Incremental: only compare new signatures vs existing + new vs new
                // This is O(n×m) instead of O(n²)
                let new_sigs: Vec<RouteSignature> = self
                    .new_signatures
                    .iter()
                    .filter_map(|id| self.signatures.get(id).cloned())
                    .collect();

                let existing_sigs: Vec<RouteSignature> = self
                    .signatures
                    .iter()
                    .filter(|(id, _)| !self.new_signatures.contains(*id))
                    .map(|(_, sig)| sig.clone())
                    .collect();

                self.groups =
                    group_incremental(&new_sigs, &self.groups, &existing_sigs, &self.match_config);
            } else {
                // Full recomputation needed
                let signatures: Vec<RouteSignature> = self.signatures.values().cloned().collect();
                self.groups = group_signatures_parallel(&signatures, &self.match_config);
            }
        }

        #[cfg(not(feature = "parallel"))]
        {
            // Non-parallel: always use full grouping (incremental requires rayon)
            let signatures: Vec<RouteSignature> = self.signatures.values().cloned().collect();
            self.groups = group_signatures(&signatures, &self.match_config);
        }

        // Clear new signatures tracker - they're now part of groups
        self.new_signatures.clear();

        // Populate sport_type and custom_name for each group
        for group in &mut self.groups {
            if let Some(activity) = self.activities.get(&group.representative_id) {
                group.sport_type = activity.sport_type.clone();
            }
            // Apply custom name if one exists
            if let Some(name) = self.route_names.get(&group.group_id) {
                group.custom_name = Some(name.clone());
            }
        }

        self.groups_dirty = false;
    }

    /// Get all route groups.
    pub fn get_groups(&mut self) -> &[RouteGroup] {
        self.ensure_groups();
        &self.groups
    }

    // ========================================================================
    // Route Names
    // ========================================================================

    /// Set a custom name for a route.
    /// Pass empty string to clear the custom name.
    pub fn set_route_name(&mut self, route_id: &str, name: &str) {
        if name.is_empty() {
            self.route_names.remove(route_id);
            // Update in-memory group
            if let Some(group) = self.groups.iter_mut().find(|g| g.group_id == route_id) {
                group.custom_name = None;
            }
        } else {
            self.route_names
                .insert(route_id.to_string(), name.to_string());
            // Update in-memory group
            if let Some(group) = self.groups.iter_mut().find(|g| g.group_id == route_id) {
                group.custom_name = Some(name.to_string());
            }
        }
    }

    /// Get the custom name for a route.
    /// Returns None if no custom name is set.
    pub fn get_route_name(&self, route_id: &str) -> Option<&String> {
        self.route_names.get(route_id)
    }

    /// Get the group containing a specific activity.
    pub fn get_group_for_activity(&mut self, activity_id: &str) -> Option<&RouteGroup> {
        self.ensure_groups();
        self.groups
            .iter()
            .find(|g| g.activity_ids.contains(&activity_id.to_string()))
    }

    /// Get groups as JSON string (for efficient FFI).
    pub fn get_groups_json(&mut self) -> String {
        self.ensure_groups();
        serde_json::to_string(&self.groups).unwrap_or_else(|_| "[]".to_string())
    }

    // ========================================================================
    // Sections
    // ========================================================================

    /// Ensure sections are detected.
    fn ensure_sections(&mut self) {
        if !self.sections_dirty {
            return;
        }

        self.ensure_groups();

        // Build tracks from activities
        let tracks: Vec<(String, Vec<GpsPoint>)> = self
            .activities
            .values()
            .map(|a| (a.id.clone(), a.coords.clone()))
            .collect();

        // Build sport type map
        let sport_map: HashMap<String, String> = self
            .activities
            .values()
            .map(|a| (a.id.clone(), a.sport_type.clone()))
            .collect();

        self.sections = crate::sections::detect_sections_from_tracks(
            &tracks,
            &sport_map,
            &self.groups,
            &self.section_config,
        );

        self.sections_dirty = false;
    }

    /// Get all detected sections.
    pub fn get_sections(&mut self) -> &[FrequentSection] {
        self.ensure_sections();
        &self.sections
    }

    /// Get sections filtered by sport type.
    pub fn get_sections_for_sport(&mut self, sport_type: &str) -> Vec<&FrequentSection> {
        self.ensure_sections();
        self.sections
            .iter()
            .filter(|s| s.sport_type == sport_type)
            .collect()
    }

    /// Get sections as JSON string (for efficient FFI).
    pub fn get_sections_json(&mut self) -> String {
        self.ensure_sections();
        serde_json::to_string(&self.sections).unwrap_or_else(|_| "[]".to_string())
    }

    // ========================================================================
    // Spatial Queries
    // ========================================================================

    /// Ensure spatial index is built.
    fn ensure_spatial_index(&mut self) {
        if !self.spatial_dirty {
            return;
        }

        let bounds: Vec<ActivityBounds> = self
            .activities
            .values()
            .filter_map(|a| {
                a.bounds.map(|b| ActivityBounds {
                    activity_id: a.id.clone(),
                    min_lat: b.min_lat,
                    max_lat: b.max_lat,
                    min_lng: b.min_lng,
                    max_lng: b.max_lng,
                })
            })
            .collect();

        self.spatial_index = RTree::bulk_load(bounds);
        self.spatial_dirty = false;
    }

    /// Query activities within a viewport.
    pub fn query_viewport(&mut self, bounds: &Bounds) -> Vec<String> {
        self.ensure_spatial_index();

        let search_bounds = AABB::from_corners(
            [bounds.min_lng, bounds.min_lat],
            [bounds.max_lng, bounds.max_lat],
        );

        self.spatial_index
            .locate_in_envelope_intersecting(&search_bounds)
            .map(|b| b.activity_id.clone())
            .collect()
    }

    /// Query activities within a viewport (raw coordinates).
    pub fn query_viewport_raw(
        &mut self,
        min_lat: f64,
        max_lat: f64,
        min_lng: f64,
        max_lng: f64,
    ) -> Vec<String> {
        self.query_viewport(&Bounds {
            min_lat,
            max_lat,
            min_lng,
            max_lng,
        })
    }

    /// Find activities near a point.
    pub fn find_nearby(&mut self, lat: f64, lng: f64, radius_degrees: f64) -> Vec<String> {
        self.query_viewport_raw(
            lat - radius_degrees,
            lat + radius_degrees,
            lng - radius_degrees,
            lng + radius_degrees,
        )
    }

    // ========================================================================
    // Consensus Route
    // ========================================================================

    /// Get or compute the consensus route for a group.
    ///
    /// The consensus route is the "average" path of all activities in the group.
    pub fn get_consensus_route(&mut self, group_id: &str) -> Option<Vec<GpsPoint>> {
        // Check cache first
        if let Some(cached) = self.consensus_cache.get(group_id) {
            return Some(cached.clone());
        }

        // Find the group
        self.ensure_groups();
        let group = self.groups.iter().find(|g| g.group_id == group_id)?;

        if group.activity_ids.is_empty() {
            return None;
        }

        // Get all tracks for this group
        let tracks: Vec<&Vec<GpsPoint>> = group
            .activity_ids
            .iter()
            .filter_map(|id| self.activities.get(id).map(|a| &a.coords))
            .collect();

        if tracks.is_empty() {
            return None;
        }

        // Simple consensus: use the medoid (track closest to all others)
        // This produces a smooth, real GPS trace rather than averaged points
        let consensus = self.compute_medoid_track(&tracks);

        // Cache the result
        self.consensus_cache
            .insert(group_id.to_string(), consensus.clone());

        Some(consensus)
    }

    /// Compute the medoid track (the track most representative of the group).
    fn compute_medoid_track(&self, tracks: &[&Vec<GpsPoint>]) -> Vec<GpsPoint> {
        if tracks.is_empty() {
            return vec![];
        }
        if tracks.len() == 1 {
            return tracks[0].clone();
        }

        // Find track with minimum total distance to all other tracks
        let mut best_idx = 0;
        let mut best_total_dist = f64::MAX;

        for (i, track_i) in tracks.iter().enumerate() {
            let total_dist: f64 = tracks
                .iter()
                .enumerate()
                .filter(|(j, _)| *j != i)
                .map(|(_, track_j)| self.track_distance(track_i, track_j))
                .sum();

            if total_dist < best_total_dist {
                best_total_dist = total_dist;
                best_idx = i;
            }
        }

        tracks[best_idx].clone()
    }

    /// Compute distance between two tracks using AMD.
    fn track_distance(&self, track1: &[GpsPoint], track2: &[GpsPoint]) -> f64 {
        if track1.is_empty() || track2.is_empty() {
            return f64::MAX;
        }

        // Sample points for efficiency
        let sample_size = 20.min(track1.len().min(track2.len()));
        let step1 = track1.len() / sample_size;
        let step2 = track2.len() / sample_size;

        let sampled1: Vec<&GpsPoint> = (0..sample_size).map(|i| &track1[i * step1]).collect();
        let sampled2: Vec<&GpsPoint> = (0..sample_size).map(|i| &track2[i * step2]).collect();

        // Average minimum distance
        let amd: f64 = sampled1
            .iter()
            .map(|p1| {
                sampled2
                    .iter()
                    .map(|p2| crate::geo_utils::haversine_distance(p1, p2))
                    .fold(f64::MAX, f64::min)
            })
            .sum::<f64>()
            / sample_size as f64;

        amd
    }

    // ========================================================================
    // Configuration
    // ========================================================================

    /// Update match configuration.
    ///
    /// This invalidates all computed state and requires full recomputation.
    pub fn set_match_config(&mut self, config: MatchConfig) {
        self.match_config = config;
        // Invalidate all computed state
        self.dirty_signatures = self.activities.keys().cloned().collect();
        self.new_signatures.clear();
        self.groups.clear();
        self.groups_dirty = true;
        self.sections_dirty = true;
    }

    /// Update section configuration.
    pub fn set_section_config(&mut self, config: SectionConfig) {
        self.section_config = config;
        self.sections_dirty = true;
    }

    /// Get current match configuration.
    pub fn get_match_config(&self) -> &MatchConfig {
        &self.match_config
    }

    /// Get current section configuration.
    pub fn get_section_config(&self) -> &SectionConfig {
        &self.section_config
    }

    // ========================================================================
    // Activity Bounds & Signatures Export
    // ========================================================================

    /// Get all activity bounds info for map display.
    /// Returns activity id, bounds, type, and distance.
    pub fn get_all_activity_bounds_info(&self) -> Vec<ActivityBoundsInfo> {
        self.activities
            .values()
            .filter_map(|activity| {
                let bounds = activity.bounds?;
                let distance = self.compute_track_distance(&activity.coords);
                Some(ActivityBoundsInfo {
                    id: activity.id.clone(),
                    bounds: [
                        [bounds.min_lat, bounds.min_lng],
                        [bounds.max_lat, bounds.max_lng],
                    ],
                    activity_type: activity.sport_type.clone(),
                    distance,
                })
            })
            .collect()
    }

    /// Get all activity bounds as JSON.
    pub fn get_all_activity_bounds_json(&self) -> String {
        let info = self.get_all_activity_bounds_info();
        serde_json::to_string(&info).unwrap_or_else(|_| "[]".to_string())
    }

    /// Get all signatures info for trace rendering.
    /// Returns activity_id -> {points, center}.
    pub fn get_all_signatures_info(&mut self) -> std::collections::HashMap<String, SignatureInfo> {
        self.ensure_signatures();
        self.signatures
            .iter()
            .map(|(id, sig)| {
                (
                    id.clone(),
                    SignatureInfo {
                        points: sig.points.clone(),
                        center: sig.center,
                    },
                )
            })
            .collect()
    }

    /// Get all signatures as JSON.
    pub fn get_all_signatures_json(&mut self) -> String {
        let info = self.get_all_signatures_info();
        serde_json::to_string(&info).unwrap_or_else(|_| "{}".to_string())
    }

    /// Compute total distance of a GPS track in meters.
    fn compute_track_distance(&self, coords: &[GpsPoint]) -> f64 {
        if coords.len() < 2 {
            return 0.0;
        }
        coords
            .windows(2)
            .map(|pair| crate::geo_utils::haversine_distance(&pair[0], &pair[1]))
            .sum()
    }

    // ========================================================================
    // Statistics
    // ========================================================================

    /// Get engine statistics.
    pub fn stats(&mut self) -> EngineStats {
        self.ensure_groups();
        self.ensure_sections();

        EngineStats {
            activity_count: self.activities.len() as u32,
            signature_count: self.signatures.len() as u32,
            group_count: self.groups.len() as u32,
            section_count: self.sections.len() as u32,
            cached_consensus_count: self.consensus_cache.len() as u32,
        }
    }

    // ========================================================================
    // Performance Calculations
    // ========================================================================

    /// Set activity metrics for performance calculations.
    /// Call this after syncing activities with metadata from the API.
    pub fn set_activity_metrics(&mut self, metrics: Vec<ActivityMetrics>) {
        for m in metrics {
            self.activity_metrics.insert(m.activity_id.clone(), m);
        }
    }

    /// Set a single activity's metrics.
    pub fn set_activity_metric(&mut self, metric: ActivityMetrics) {
        self.activity_metrics
            .insert(metric.activity_id.clone(), metric);
    }

    /// Get activity metrics by ID.
    pub fn get_activity_metrics(&self, activity_id: &str) -> Option<&ActivityMetrics> {
        self.activity_metrics.get(activity_id)
    }

    /// Calculate route performances for all activities in a group.
    /// Returns performances sorted by date with best and current rank.
    pub fn get_route_performances(
        &mut self,
        route_group_id: &str,
        current_activity_id: Option<&str>,
    ) -> RoutePerformanceResult {
        self.ensure_groups();

        // Find the group
        let group = match self.groups.iter().find(|g| g.group_id == route_group_id) {
            Some(g) => g,
            None => {
                return RoutePerformanceResult {
                    performances: vec![],
                    best: None,
                    current_rank: None,
                }
            }
        };

        // Build performances from metrics
        let mut performances: Vec<RoutePerformance> = group
            .activity_ids
            .iter()
            .filter_map(|id| {
                let metrics = self.activity_metrics.get(id)?;
                let speed = if metrics.moving_time > 0 {
                    metrics.distance / metrics.moving_time as f64
                } else {
                    0.0
                };

                Some(RoutePerformance {
                    activity_id: id.clone(),
                    name: metrics.name.clone(),
                    date: metrics.date,
                    speed,
                    duration: metrics.elapsed_time,
                    moving_time: metrics.moving_time,
                    distance: metrics.distance,
                    elevation_gain: metrics.elevation_gain,
                    avg_hr: metrics.avg_hr,
                    avg_power: metrics.avg_power,
                    is_current: current_activity_id == Some(id.as_str()),
                    direction: "same".to_string(),
                    match_percentage: 100.0,
                })
            })
            .collect();

        // Sort by date (oldest first for charting)
        performances.sort_by_key(|p| p.date);

        // Find best (fastest speed)
        let best = performances
            .iter()
            .max_by(|a, b| {
                a.speed
                    .partial_cmp(&b.speed)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .cloned();

        // Calculate current rank (1 = fastest)
        let current_rank = current_activity_id.and_then(|current_id| {
            let mut by_speed = performances.clone();
            by_speed.sort_by(|a, b| {
                b.speed
                    .partial_cmp(&a.speed)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            by_speed
                .iter()
                .position(|p| p.activity_id == current_id)
                .map(|idx| (idx + 1) as u32)
        });

        RoutePerformanceResult {
            performances,
            best,
            current_rank,
        }
    }

    /// Get route performances as JSON string.
    pub fn get_route_performances_json(
        &mut self,
        route_group_id: &str,
        current_activity_id: Option<&str>,
    ) -> String {
        let result = self.get_route_performances(route_group_id, current_activity_id);
        serde_json::to_string(&result).unwrap_or_else(|_| "{}".to_string())
    }

    // ========================================================================
    // Time Streams for Section Calculations
    // ========================================================================

    /// Set time stream for an activity (for section lap calculations).
    /// Only stores the time array, not the full stream data.
    pub fn set_time_stream(&mut self, activity_id: String, times: Vec<u32>) {
        self.time_streams.insert(activity_id, times);
    }

    /// Set multiple time streams from flat buffer.
    /// Format: activity_ids, all times concatenated, offsets into all_times
    pub fn set_time_streams_flat(
        &mut self,
        activity_ids: &[String],
        all_times: &[u32],
        offsets: &[u32],
    ) {
        for (i, activity_id) in activity_ids.iter().enumerate() {
            let start = offsets[i] as usize;
            let end = offsets
                .get(i + 1)
                .map(|&o| o as usize)
                .unwrap_or(all_times.len());
            let times = all_times[start..end].to_vec();
            self.time_streams.insert(activity_id.clone(), times);
        }
    }

    /// Calculate section performances from cached time streams.
    /// Returns performance records sorted by date with best record.
    pub fn get_section_performances(&mut self, section_id: &str) -> SectionPerformanceResult {
        self.ensure_sections();

        // Find the section
        let section = match self.sections.iter().find(|s| s.id == section_id) {
            Some(s) => s,
            None => {
                return SectionPerformanceResult {
                    records: vec![],
                    best_record: None,
                }
            }
        };

        // Group portions by activity
        let mut portions_by_activity: HashMap<&str, Vec<&crate::SectionPortion>> = HashMap::new();
        for portion in &section.activity_portions {
            portions_by_activity
                .entry(&portion.activity_id)
                .or_default()
                .push(portion);
        }

        // Calculate records for each activity
        let mut records: Vec<SectionPerformanceRecord> = portions_by_activity
            .iter()
            .filter_map(|(activity_id, portions)| {
                let metrics = self.activity_metrics.get(*activity_id)?;
                let times = self.time_streams.get(*activity_id)?;

                // Calculate laps
                let laps: Vec<SectionLap> = portions
                    .iter()
                    .enumerate()
                    .filter_map(|(i, portion)| {
                        let start_idx = portion.start_index as usize;
                        let end_idx = portion.end_index as usize;

                        if start_idx >= times.len() || end_idx >= times.len() {
                            return None;
                        }

                        let lap_time = (times[end_idx] as f64 - times[start_idx] as f64).abs();
                        if lap_time <= 0.0 {
                            return None;
                        }

                        let pace = portion.distance_meters / lap_time;

                        Some(SectionLap {
                            id: format!("{}_lap{}", activity_id, i),
                            activity_id: activity_id.to_string(),
                            time: lap_time,
                            pace,
                            distance: portion.distance_meters,
                            direction: portion.direction.clone(),
                            start_index: portion.start_index,
                            end_index: portion.end_index,
                        })
                    })
                    .collect();

                if laps.is_empty() {
                    return None;
                }

                // Aggregate stats
                let best_time = laps.iter().map(|l| l.time).fold(f64::MAX, f64::min);
                let best_pace = laps.iter().map(|l| l.pace).fold(0.0f64, f64::max);
                let avg_time = laps.iter().map(|l| l.time).sum::<f64>() / laps.len() as f64;
                let avg_pace = laps.iter().map(|l| l.pace).sum::<f64>() / laps.len() as f64;

                Some(SectionPerformanceRecord {
                    activity_id: activity_id.to_string(),
                    activity_name: metrics.name.clone(),
                    activity_date: metrics.date,
                    lap_count: laps.len() as u32,
                    best_time,
                    best_pace,
                    avg_time,
                    avg_pace,
                    direction: laps[0].direction.clone(),
                    section_distance: laps[0].distance,
                    laps,
                })
            })
            .collect();

        // Sort by date
        records.sort_by_key(|r| r.activity_date);

        // Find best (fastest time)
        let best_record = records
            .iter()
            .min_by(|a, b| {
                a.best_time
                    .partial_cmp(&b.best_time)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .cloned();

        SectionPerformanceResult {
            records,
            best_record,
        }
    }

    /// Get section performances as JSON string.
    pub fn get_section_performances_json(&mut self, section_id: &str) -> String {
        let result = self.get_section_performances(section_id);
        serde_json::to_string(&result).unwrap_or_else(|_| "{}".to_string())
    }
}

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

/// Engine statistics for monitoring.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "ffi", derive(uniffi::Record))]
pub struct EngineStats {
    pub activity_count: u32,
    pub signature_count: u32,
    pub group_count: u32,
    pub section_count: u32,
    pub cached_consensus_count: u32,
}

/// Activity bounds info for map display
#[derive(Debug, Clone, serde::Serialize)]
pub struct ActivityBoundsInfo {
    pub id: String,
    pub bounds: [[f64; 2]; 2], // [[minLat, minLng], [maxLat, maxLng]]
    pub activity_type: String,
    pub distance: f64, // meters, computed from coords
}

/// Signature info for trace rendering
#[derive(Debug, Clone, serde::Serialize)]
pub struct SignatureInfo {
    pub points: Vec<GpsPoint>,
    pub center: GpsPoint,
}

// ============================================================================
// Global Singleton
// ============================================================================

/// Global engine instance.
///
/// This singleton allows FFI calls to access a shared engine without
/// passing state back and forth across the FFI boundary.
pub static ENGINE: Lazy<Mutex<RouteEngine>> = Lazy::new(|| Mutex::new(RouteEngine::new()));

/// Get a lock on the global engine.
pub fn with_engine<F, R>(f: F) -> R
where
    F: FnOnce(&mut RouteEngine) -> R,
{
    let mut engine = ENGINE.lock().unwrap();
    f(&mut engine)
}

// ============================================================================
// FFI Exports
// ============================================================================

#[cfg(feature = "ffi")]
pub mod engine_ffi {
    use super::*;
    use log::info;

    /// Initialize the engine (call once at app startup).
    #[uniffi::export]
    pub fn engine_init() {
        crate::init_logging();
        info!("[RouteEngine] Initialized");
    }

    /// Clear all engine state.
    #[uniffi::export]
    pub fn engine_clear() {
        with_engine(|e| e.clear());
        info!("[RouteEngine] Cleared");
    }

    /// Add activities from flat coordinate buffers.
    #[uniffi::export]
    pub fn engine_add_activities(
        activity_ids: Vec<String>,
        all_coords: Vec<f64>,
        offsets: Vec<u32>,
        sport_types: Vec<String>,
    ) {
        info!(
            "[RouteEngine] Adding {} activities ({} coords)",
            activity_ids.len(),
            all_coords.len() / 2
        );

        with_engine(|e| {
            e.add_activities_flat(&activity_ids, &all_coords, &offsets, &sport_types);
        });
    }

    /// Remove activities.
    #[uniffi::export]
    pub fn engine_remove_activities(activity_ids: Vec<String>) {
        info!("[RouteEngine] Removing {} activities", activity_ids.len());
        with_engine(|e| e.remove_activities(&activity_ids));
    }

    /// Get all activity IDs.
    #[uniffi::export]
    pub fn engine_get_activity_ids() -> Vec<String> {
        with_engine(|e| e.get_activity_ids())
    }

    /// Get activity count.
    #[uniffi::export]
    pub fn engine_get_activity_count() -> u32 {
        with_engine(|e| e.activity_count() as u32)
    }

    /// Get route groups as JSON.
    #[uniffi::export]
    pub fn engine_get_groups_json() -> String {
        with_engine(|e| e.get_groups_json())
    }

    /// Get sections as JSON.
    #[uniffi::export]
    pub fn engine_get_sections_json() -> String {
        with_engine(|e| e.get_sections_json())
    }

    /// Get signature points for all activities in a group.
    /// Returns JSON: { "activity_id": [{"latitude": x, "longitude": y}, ...], ... }
    #[uniffi::export]
    pub fn engine_get_signatures_for_group_json(group_id: String) -> String {
        with_engine(|e| e.get_signatures_for_group_json(&group_id))
    }

    /// Set a custom name for a route.
    /// Pass empty string to clear the custom name.
    #[uniffi::export]
    pub fn engine_set_route_name(route_id: String, name: String) {
        with_engine(|e| e.set_route_name(&route_id, &name))
    }

    /// Get the custom name for a route.
    /// Returns empty string if no custom name is set.
    #[uniffi::export]
    pub fn engine_get_route_name(route_id: String) -> String {
        with_engine(|e| e.get_route_name(&route_id).cloned().unwrap_or_default())
    }

    /// Query activities in viewport.
    #[uniffi::export]
    pub fn engine_query_viewport(
        min_lat: f64,
        max_lat: f64,
        min_lng: f64,
        max_lng: f64,
    ) -> Vec<String> {
        with_engine(|e| e.query_viewport_raw(min_lat, max_lat, min_lng, max_lng))
    }

    /// Find activities near a point.
    #[uniffi::export]
    pub fn engine_find_nearby(lat: f64, lng: f64, radius_degrees: f64) -> Vec<String> {
        with_engine(|e| e.find_nearby(lat, lng, radius_degrees))
    }

    /// Get consensus route for a group as flat coordinates.
    #[uniffi::export]
    pub fn engine_get_consensus_route(group_id: String) -> Vec<f64> {
        with_engine(|e| {
            e.get_consensus_route(&group_id)
                .map(|points| {
                    points
                        .iter()
                        .flat_map(|p| vec![p.latitude, p.longitude])
                        .collect()
                })
                .unwrap_or_default()
        })
    }

    /// Get engine statistics.
    #[uniffi::export]
    pub fn engine_get_stats() -> EngineStats {
        with_engine(|e| e.stats())
    }

    /// Set match configuration.
    #[uniffi::export]
    pub fn engine_set_match_config(config: crate::MatchConfig) {
        with_engine(|e| e.set_match_config(config));
    }

    /// Set section configuration.
    #[uniffi::export]
    pub fn engine_set_section_config(config: crate::SectionConfig) {
        with_engine(|e| e.set_section_config(config));
    }

    /// Get all activity bounds info as JSON for map display.
    /// Returns: [{"id": "...", "bounds": [[minLat, minLng], [maxLat, maxLng]], "activity_type": "...", "distance": ...}, ...]
    #[uniffi::export]
    pub fn engine_get_all_activity_bounds_json() -> String {
        with_engine(|e| e.get_all_activity_bounds_json())
    }

    /// Get all signatures as JSON for trace rendering.
    /// Returns: {"activity_id": {"points": [{latitude, longitude}, ...], "center": {latitude, longitude}}, ...}
    #[uniffi::export]
    pub fn engine_get_all_signatures_json() -> String {
        with_engine(|e| e.get_all_signatures_json())
    }

    // ========================================================================
    // Performance FFI Exports
    // ========================================================================

    /// Set activity metrics for performance calculations.
    /// Called after activities are synced with metadata from the API.
    #[uniffi::export]
    pub fn engine_set_activity_metrics(metrics: Vec<crate::ActivityMetrics>) {
        info!(
            "[RouteEngine] Setting metrics for {} activities",
            metrics.len()
        );
        with_engine(|e| e.set_activity_metrics(metrics));
    }

    /// Set a single activity's metrics.
    #[uniffi::export]
    pub fn engine_set_activity_metric(metric: crate::ActivityMetrics) {
        with_engine(|e| e.set_activity_metric(metric));
    }

    /// Get route performances for a group.
    /// Returns JSON with performances sorted by date, best, and current rank.
    #[uniffi::export]
    pub fn engine_get_route_performances_json(
        route_group_id: String,
        current_activity_id: Option<String>,
    ) -> String {
        with_engine(|e| {
            e.get_route_performances_json(&route_group_id, current_activity_id.as_deref())
        })
    }

    /// Set time streams for section calculations.
    /// Format: activity_ids, all times concatenated, offsets into all_times
    #[uniffi::export]
    pub fn engine_set_time_streams(
        activity_ids: Vec<String>,
        all_times: Vec<u32>,
        offsets: Vec<u32>,
    ) {
        info!(
            "[RouteEngine] Setting time streams for {} activities",
            activity_ids.len()
        );
        with_engine(|e| e.set_time_streams_flat(&activity_ids, &all_times, &offsets));
    }

    /// Get section performances.
    /// Returns JSON with performance records sorted by date and best record.
    #[uniffi::export]
    pub fn engine_get_section_performances_json(section_id: String) -> String {
        with_engine(|e| e.get_section_performances_json(&section_id))
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_coords() -> Vec<GpsPoint> {
        (0..10)
            .map(|i| GpsPoint::new(51.5074 + i as f64 * 0.001, -0.1278))
            .collect()
    }

    #[test]
    fn test_engine_add_activity() {
        let mut engine = RouteEngine::new();
        engine.add_activity("test-1".to_string(), sample_coords(), "cycling".to_string());

        assert_eq!(engine.activity_count(), 1);
        assert!(engine.has_activity("test-1"));
    }

    #[test]
    fn test_engine_add_flat() {
        let mut engine = RouteEngine::new();
        let flat_coords: Vec<f64> = sample_coords()
            .iter()
            .flat_map(|p| vec![p.latitude, p.longitude])
            .collect();

        engine.add_activity_flat("test-1".to_string(), &flat_coords, "cycling".to_string());

        assert_eq!(engine.activity_count(), 1);
    }

    #[test]
    fn test_engine_get_signature() {
        let mut engine = RouteEngine::new();
        engine.add_activity("test-1".to_string(), sample_coords(), "cycling".to_string());

        let sig = engine.get_signature("test-1");
        assert!(sig.is_some());
        assert_eq!(sig.unwrap().activity_id, "test-1");
    }

    #[test]
    fn test_engine_grouping() {
        let mut engine = RouteEngine::new();
        let coords = sample_coords();

        engine.add_activity("test-1".to_string(), coords.clone(), "cycling".to_string());
        engine.add_activity("test-2".to_string(), coords.clone(), "cycling".to_string());

        let groups = engine.get_groups();
        assert_eq!(groups.len(), 1); // Both should be in same group
        assert_eq!(groups[0].activity_ids.len(), 2);
    }

    #[test]
    fn test_engine_viewport_query() {
        let mut engine = RouteEngine::new();
        engine.add_activity("test-1".to_string(), sample_coords(), "cycling".to_string());

        // Query containing the activity
        let results = engine.query_viewport_raw(51.5, 51.52, -0.15, -0.10);
        assert_eq!(results.len(), 1);

        // Query not containing the activity
        let results = engine.query_viewport_raw(40.0, 41.0, -75.0, -74.0);
        assert!(results.is_empty());
    }

    #[test]
    fn test_engine_remove() {
        let mut engine = RouteEngine::new();
        engine.add_activity("test-1".to_string(), sample_coords(), "cycling".to_string());
        engine.add_activity("test-2".to_string(), sample_coords(), "cycling".to_string());

        engine.remove_activity("test-1");

        assert_eq!(engine.activity_count(), 1);
        assert!(!engine.has_activity("test-1"));
        assert!(engine.has_activity("test-2"));
    }

    #[test]
    fn test_engine_clear() {
        let mut engine = RouteEngine::new();
        engine.add_activity("test-1".to_string(), sample_coords(), "cycling".to_string());
        engine.clear();

        assert_eq!(engine.activity_count(), 0);
    }

    #[test]
    fn test_engine_incremental_grouping() {
        let mut engine = RouteEngine::new();
        let coords = sample_coords();

        // Add initial activities and trigger grouping
        engine.add_activity("test-1".to_string(), coords.clone(), "cycling".to_string());
        engine.add_activity("test-2".to_string(), coords.clone(), "cycling".to_string());

        // Trigger initial grouping
        let groups = engine.get_groups();
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].activity_ids.len(), 2);

        // Add more activities (should use incremental grouping)
        engine.add_activity("test-3".to_string(), coords.clone(), "cycling".to_string());

        // Add a different route that shouldn't match
        let different_coords: Vec<GpsPoint> = (0..10)
            .map(|i| GpsPoint::new(40.7128 + i as f64 * 0.001, -74.0060)) // NYC instead of London
            .collect();
        engine.add_activity(
            "test-4".to_string(),
            different_coords,
            "cycling".to_string(),
        );

        // Verify grouping results
        let groups = engine.get_groups();

        // Should have 2 groups: one with test-1,2,3 (similar routes) and one with test-4 (different location)
        assert_eq!(groups.len(), 2);

        // Find the group with more activities (the London routes)
        let large_group = groups.iter().find(|g| g.activity_ids.len() == 3);
        assert!(
            large_group.is_some(),
            "Should have a group with 3 activities"
        );

        // Find the group with single activity (the NYC route)
        let small_group = groups.iter().find(|g| g.activity_ids.len() == 1);
        assert!(small_group.is_some(), "Should have a group with 1 activity");
        assert!(small_group
            .unwrap()
            .activity_ids
            .contains(&"test-4".to_string()));
    }

    #[test]
    fn test_engine_new_signatures_tracking() {
        let mut engine = RouteEngine::new();
        let coords = sample_coords();

        // Add activity - should be tracked as new
        engine.add_activity("test-1".to_string(), coords.clone(), "cycling".to_string());
        assert!(engine.dirty_signatures.contains("test-1"));

        // Trigger signature computation
        let _sig = engine.get_signature("test-1");
        assert!(engine.dirty_signatures.is_empty());
        assert!(engine.new_signatures.contains("test-1"));

        // Trigger grouping - should clear new_signatures
        let _groups = engine.get_groups();
        assert!(engine.new_signatures.is_empty());
    }
}