tp-lib-core 0.0.6

Core library for GNSS track axis projection with spatial indexing
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
//! GeoJSON parsing and writing

use crate::errors::ProjectionError;
use crate::models::{GnssPosition, NetRelation, Netelement, ProjectedPosition};
use crate::temporal::parse_timestamp_flexible;
use geo::{Coord, LineString};
use geojson::{Feature, GeoJson, Value};
use std::fs;

// Default CRS constant for GeoJSON (RFC 7946)
const DEFAULT_CRS: &str = "EPSG:4326";

/// Parse CRS from GeoJSON FeatureCollection
///
/// Extracts CRS from foreign_members or returns default WGS84
fn parse_crs_from_feature_collection(feature_collection: &geojson::FeatureCollection) -> String {
    let Some(crs_obj) = &feature_collection.foreign_members else {
        return DEFAULT_CRS.to_string();
    };

    let Some(crs_value) = crs_obj.get("crs") else {
        return DEFAULT_CRS.to_string();
    };

    // Try to extract CRS from properties.name
    crs_value
        .get("properties")
        .and_then(|props| props.get("name"))
        .and_then(|name| name.as_str())
        .and_then(|name_str| {
            // Handle URN format: "urn:ogc:def:crs:EPSG::4326"
            if name_str.contains("EPSG") {
                name_str
                    .split("::")
                    .last()
                    .map(|code| format!("EPSG:{}", code))
            } else {
                None
            }
        })
        .unwrap_or_else(|| DEFAULT_CRS.to_string())
}

/// Parse railway network from GeoJSON file
///
/// Loads both netelements and netrelations from a single GeoJSON FeatureCollection.
/// Netelements are features with LineString/MultiLineString geometry (without type="netrelation").
/// Netrelations are features with type="netrelation" property.
///
/// # Arguments
///
/// * `path` - Path to GeoJSON file containing both network elements and relations
///
/// # Returns
///
/// A tuple containing `(Vec<Netelement>, Vec<NetRelation>)`
///
/// # Example
///
/// ```no_run
/// use tp_lib_core::io::parse_network_geojson;
///
/// let (netelements, netrelations) = parse_network_geojson("network.geojson")?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn parse_network_geojson(
    path: &str,
) -> Result<(Vec<Netelement>, Vec<NetRelation>), ProjectionError> {
    let geojson_str = fs::read_to_string(path)?;
    parse_network_geojson_str(&geojson_str)
}

/// In-memory variant of [`parse_network_geojson`] that accepts the GeoJSON
/// FeatureCollection text directly. No disk I/O is performed; required by the
/// .NET bindings for database-backed callers (FR-012).
pub fn parse_network_geojson_str(
    geojson_str: &str,
) -> Result<(Vec<Netelement>, Vec<NetRelation>), ProjectionError> {
    // Parse GeoJSON
    let geojson = geojson_str
        .parse::<GeoJson>()
        .map_err(|e| ProjectionError::InvalidGeometry(format!("Failed to parse GeoJSON: {}", e)))?;

    // Extract FeatureCollection
    let feature_collection = match geojson {
        GeoJson::FeatureCollection(fc) => fc,
        _ => {
            return Err(ProjectionError::InvalidGeometry(
                "GeoJSON must be a FeatureCollection".to_string(),
            ))
        }
    };

    // Determine CRS - RFC 7946 specifies WGS84 is the default
    let crs = parse_crs_from_feature_collection(&feature_collection);

    // Validate CRS is WGS84 per RFC 7946
    if !crs.contains("4326") && !crs.contains("WGS84") {
        return Err(ProjectionError::InvalidCrs(format!(
            "GeoJSON CRS must be WGS84 (EPSG:4326) per RFC 7946, got: {}",
            crs
        )));
    }

    // Parse features, separating netelements and netrelations
    let mut netelements = Vec::new();
    let mut netrelations = Vec::new();

    for (idx, feature) in feature_collection.features.iter().enumerate() {
        // Check if this is a netrelation feature
        if let Some(props) = &feature.properties {
            if let Some(feature_type) = props.get("type") {
                if feature_type.as_str() == Some("netrelation") {
                    let netrelation = parse_netrelation_feature(feature, idx)?;
                    netrelations.push(netrelation);
                    continue;
                }
            }
        }

        // Otherwise parse as netelement
        let netelement = parse_feature(feature, &crs, idx)?;
        netelements.push(netelement);
    }

    if netelements.is_empty() {
        return Err(ProjectionError::EmptyNetwork);
    }

    Ok((netelements, netrelations))
}

/// Parse GNSS positions from GeoJSON file
///
/// Expects a FeatureCollection with Point geometries and properties:
/// - `timestamp`: RFC3339 timestamp with timezone
/// - Optional: other properties will be stored as metadata
///
/// # Arguments
///
/// * `path` - Path to GeoJSON file
/// * `crs` - Expected CRS of the coordinates (e.g., "EPSG:4326")
///
/// # Returns
///
/// Vector of GnssPosition structs
///
/// # Example GeoJSON
///
/// ```json
/// {
///   "type": "FeatureCollection",
///   "features": [
///     {
///       "type": "Feature",
///       "geometry": {
///         "type": "Point",
///         "coordinates": [4.3517, 50.8503]
///       },
///       "properties": {
///         "timestamp": "2025-12-09T14:30:00+01:00",
///         "vehicle_id": "TRAIN_001"
///       }
///     }
///   ]
/// }
/// ```
pub fn parse_gnss_geojson(path: &str, crs: &str) -> Result<Vec<GnssPosition>, ProjectionError> {
    let geojson_str = fs::read_to_string(path)?;
    parse_gnss_geojson_str(&geojson_str, crs)
}

/// In-memory variant of [`parse_gnss_geojson`] that accepts the GeoJSON
/// FeatureCollection text directly. No disk I/O is performed; required by the
/// .NET bindings for database-backed callers (FR-012).
pub fn parse_gnss_geojson_str(
    geojson_str: &str,
    crs: &str,
) -> Result<Vec<GnssPosition>, ProjectionError> {
    // Parse GeoJSON
    let geojson = geojson_str
        .parse::<GeoJson>()
        .map_err(|e| ProjectionError::GeoJsonError(format!("Failed to parse GeoJSON: {}", e)))?;

    // Extract FeatureCollection
    let feature_collection = match geojson {
        GeoJson::FeatureCollection(fc) => fc,
        _ => {
            return Err(ProjectionError::GeoJsonError(
                "GeoJSON must be a FeatureCollection".to_string(),
            ))
        }
    };

    // Parse features
    let mut positions = Vec::new();

    for (idx, feature) in feature_collection.features.iter().enumerate() {
        let position = parse_gnss_feature(feature, crs, idx)?;
        positions.push(position);
    }

    if positions.is_empty() {
        return Err(ProjectionError::GeoJsonError(
            "GeoJSON contains no valid GNSS positions".to_string(),
        ));
    }

    Ok(positions)
}

/// Parse a single GeoJSON feature into a GnssPosition
fn parse_gnss_feature(
    feature: &Feature,
    crs: &str,
    idx: usize,
) -> Result<GnssPosition, ProjectionError> {
    // Get geometry
    let geometry = feature.geometry.as_ref().ok_or_else(|| {
        ProjectionError::GeoJsonError(format!("Feature {} missing geometry", idx))
    })?;

    // Extract Point coordinates (longitude, latitude)
    let (longitude, latitude) = match &geometry.value {
        Value::Point(coords) => {
            if coords.len() < 2 {
                return Err(ProjectionError::InvalidCoordinate(format!(
                    "Feature {} Point must have at least 2 coordinates",
                    idx
                )));
            }
            (coords[0], coords[1])
        }
        _ => {
            return Err(ProjectionError::GeoJsonError(format!(
                "Feature {} must have Point geometry for GNSS position",
                idx
            )))
        }
    };

    // Validate coordinates
    if !(-90.0..=90.0).contains(&latitude) {
        return Err(ProjectionError::InvalidCoordinate(format!(
            "Feature {}: latitude {} out of range [-90, 90]",
            idx, latitude
        )));
    }
    if !(-180.0..=180.0).contains(&longitude) {
        return Err(ProjectionError::InvalidCoordinate(format!(
            "Feature {}: longitude {} out of range [-180, 180]",
            idx, longitude
        )));
    }

    // Get properties
    let properties = feature.properties.as_ref().ok_or_else(|| {
        ProjectionError::GeoJsonError(format!(
            "Feature {} missing properties (timestamp required)",
            idx
        ))
    })?;

    // Extract timestamp
    let timestamp_str = properties
        .get("timestamp")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ProjectionError::MissingTimezone(format!(
                "Feature {} missing 'timestamp' property",
                idx
            ))
        })?;

    // Parse timestamp; accept RFC3339 with timezone or naive ISO 8601
    // datetime interpreted as the host's local timezone.
    let timestamp = parse_timestamp_flexible(timestamp_str).map_err(|e| {
        ProjectionError::InvalidTimestamp(format!(
            "Feature {}: invalid timestamp '{}': {}",
            idx, timestamp_str, e
        ))
    })?;

    // Extract metadata (all properties except timestamp, heading, distance)
    let mut metadata = std::collections::HashMap::new();
    let mut heading: Option<f64> = None;
    let mut distance: Option<f64> = None;

    for (key, value) in properties {
        match key.as_str() {
            "timestamp" => {} // Skip, already extracted
            "heading" => {
                // Extract optional heading (0-360°)
                if let Some(h) = value.as_f64() {
                    if (0.0..=360.0).contains(&h) {
                        heading = Some(h);
                    } else {
                        return Err(ProjectionError::InvalidGeometry(format!(
                            "Feature {}: heading {} not in [0, 360]",
                            idx, h
                        )));
                    }
                }
            }
            "distance" => {
                // Extract optional distance (>= 0)
                if let Some(d) = value.as_f64() {
                    if d >= 0.0 {
                        distance = Some(d);
                    } else {
                        return Err(ProjectionError::InvalidGeometry(format!(
                            "Feature {}: distance {} must be >= 0",
                            idx, d
                        )));
                    }
                }
            }
            _ => {
                // Store other properties as metadata
                if let Some(str_value) = value.as_str() {
                    metadata.insert(key.clone(), str_value.to_string());
                } else {
                    metadata.insert(key.clone(), value.to_string());
                }
            }
        }
    }

    Ok(GnssPosition {
        latitude,
        longitude,
        timestamp,
        crs: crs.to_string(),
        metadata,
        heading,
        distance,
    })
}

/// Parse a single GeoJSON feature into a Netelement
fn parse_feature(feature: &Feature, crs: &str, idx: usize) -> Result<Netelement, ProjectionError> {
    // Get geometry
    let geometry = feature.geometry.as_ref().ok_or_else(|| {
        ProjectionError::InvalidGeometry(format!("Feature {} missing geometry", idx))
    })?;

    // Extract LineString
    let linestring = match &geometry.value {
        Value::LineString(coords) => {
            let geo_coords: Vec<Coord<f64>> = coords
                .iter()
                .map(|pos| Coord {
                    x: pos[0],
                    y: pos[1],
                })
                .collect();
            LineString::from(geo_coords)
        }
        Value::MultiLineString(lines) => {
            // For MultiLineString, use first line (or could concatenate)
            if lines.is_empty() {
                return Err(ProjectionError::InvalidGeometry(format!(
                    "Feature {} has empty MultiLineString",
                    idx
                )));
            }
            let geo_coords: Vec<Coord<f64>> = lines[0]
                .iter()
                .map(|pos| Coord {
                    x: pos[0],
                    y: pos[1],
                })
                .collect();
            LineString::from(geo_coords)
        }
        _ => {
            return Err(ProjectionError::InvalidGeometry(format!(
                "Feature {} must have LineString or MultiLineString geometry",
                idx
            )))
        }
    };

    // Get ID from properties (required)
    let id = if let Some(props) = &feature.properties {
        if let Some(id_value) = props.get("id") {
            id_value
                .as_str()
                .map(|s| s.to_string())
                .or_else(|| id_value.as_i64().map(|i| i.to_string()))
                .ok_or_else(|| {
                    ProjectionError::GeoJsonError(format!(
                        "Feature {} has invalid 'id' property type",
                        idx
                    ))
                })?
        } else {
            return Err(ProjectionError::GeoJsonError(format!(
                "Feature {} missing required 'id' property",
                idx
            )));
        }
    } else {
        return Err(ProjectionError::GeoJsonError(format!(
            "Feature {} missing properties object",
            idx
        )));
    };

    Netelement::new(id, linestring, crs.to_string())
}

/// Parse netrelations from GeoJSON file
///
/// Expects a FeatureCollection with features that have `type="netrelation"` property.
/// Netrelations can have optional Point geometry representing the connection point.
///
/// # Required Properties
///
/// - `type`: Must be "netrelation"
/// - `id`: Netrelation identifier
/// - `netelementA`: ID of first netelement
/// - `netelementB`: ID of second netelement
/// - `positionOnA`: Position on netelementA (0 or 1)
/// - `positionOnB`: Position on netelementB (0 or 1)
/// - `navigability`: "both", "AB", "BA", or "none"
///
/// # Arguments
///
/// * `path` - Path to GeoJSON file
///
/// # Returns
///
/// Vector of NetRelation structs
///
/// # Example GeoJSON
///
/// ```json
/// {
///   "type": "FeatureCollection",
///   "features": [
///     {
///       "type": "Feature",
///       "geometry": {
///         "type": "Point",
///         "coordinates": [4.3517, 50.8503]
///       },
///       "properties": {
///         "type": "netrelation",
///         "id": "NR_001",
///         "netelementA": "NE_001",
///         "netelementB": "NE_002",
///         "positionOnA": 1,
///         "positionOnB": 0,
///         "navigability": "both"
///       }
///     }
///   ]
/// }
/// ```
pub fn parse_netrelations_geojson(path: &str) -> Result<Vec<NetRelation>, ProjectionError> {
    // Read file
    let geojson_str = fs::read_to_string(path)?;

    // Parse GeoJSON
    let geojson = geojson_str
        .parse::<GeoJson>()
        .map_err(|e| ProjectionError::GeoJsonError(format!("Failed to parse GeoJSON: {}", e)))?;

    // Extract FeatureCollection
    let feature_collection = match geojson {
        GeoJson::FeatureCollection(fc) => fc,
        _ => {
            return Err(ProjectionError::GeoJsonError(
                "GeoJSON must be a FeatureCollection".to_string(),
            ))
        }
    };

    // Parse features, filtering for type="netrelation"
    let mut netrelations = Vec::new();

    for (idx, feature) in feature_collection.features.iter().enumerate() {
        // Check if this is a netrelation feature
        if let Some(props) = &feature.properties {
            if let Some(feature_type) = props.get("type") {
                if feature_type.as_str() == Some("netrelation") {
                    let netrelation = parse_netrelation_feature(feature, idx)?;
                    netrelations.push(netrelation);
                }
            }
        }
    }

    Ok(netrelations)
}

/// Parse a single GeoJSON feature into a NetRelation
fn parse_netrelation_feature(
    feature: &Feature,
    idx: usize,
) -> Result<NetRelation, ProjectionError> {
    // Get properties
    let properties = feature.properties.as_ref().ok_or_else(|| {
        ProjectionError::GeoJsonError(format!("Netrelation feature {} missing properties", idx))
    })?;

    // Extract ID
    let id = properties
        .get("id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ProjectionError::GeoJsonError(format!(
                "Netrelation feature {} missing 'id' property",
                idx
            ))
        })?
        .to_string();

    // Extract netelementA (support both 'from' and 'netelementA' for backwards compatibility)
    let netelement_a = properties
        .get("netelementA")
        .or_else(|| properties.get("from"))
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ProjectionError::GeoJsonError(format!(
                "Netrelation feature {} missing 'netelementA' or 'from' property",
                idx
            ))
        })?
        .to_string();

    // Extract netelementB (support both 'to' and 'netelementB' for backwards compatibility)
    let netelement_b = properties
        .get("netelementB")
        .or_else(|| properties.get("to"))
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ProjectionError::GeoJsonError(format!(
                "Netrelation feature {} missing 'netelementB' or 'to' property",
                idx
            ))
        })?
        .to_string();

    // Extract positionOnA (0 or 1) - accept both integer and float
    let position_on_a = properties
        .get("positionOnA")
        .and_then(|v| v.as_u64().or_else(|| v.as_f64().map(|f| f as u64)))
        .ok_or_else(|| {
            ProjectionError::GeoJsonError(format!(
                "Netrelation feature {} missing or invalid 'positionOnA' property",
                idx
            ))
        })? as u8;

    // Extract positionOnB (0 or 1) - accept both integer and float
    let position_on_b = properties
        .get("positionOnB")
        .and_then(|v| v.as_u64().or_else(|| v.as_f64().map(|f| f as u64)))
        .ok_or_else(|| {
            ProjectionError::GeoJsonError(format!(
                "Netrelation feature {} missing or invalid 'positionOnB' property",
                idx
            ))
        })? as u8;

    // Extract navigability and convert to boolean flags
    let navigability_str = properties
        .get("navigability")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ProjectionError::GeoJsonError(format!(
                "Netrelation feature {} missing 'navigability' property",
                idx
            ))
        })?;

    let (navigable_forward, navigable_backward) = match navigability_str.to_lowercase().as_str() {
        "both" => (true, true),
        "ab" => (true, false),
        "ba" => (false, true),
        "none" => (false, false),
        _ => return Err(ProjectionError::GeoJsonError(
            format!("Netrelation feature {}: invalid navigability value '{}' (expected: both, AB, BA, or none)", idx, navigability_str)
        )),
    };

    // Create NetRelation
    let netrelation = NetRelation::new(
        id,
        netelement_a,
        netelement_b,
        position_on_a,
        position_on_b,
        navigable_forward,
        navigable_backward,
    )?;

    Ok(netrelation)
}

/// Write a railway network (netelements + netrelations) as a GeoJSON
/// FeatureCollection that round-trips through [`parse_network_geojson_str`].
///
/// Netelements are written as LineString features with an `id` property.
/// Netrelations are written as geometry-less features tagged with
/// `type="netrelation"` and the topology properties consumed by
/// [`parse_netrelation_feature`].
pub fn write_network_geojson(
    netelements: &[Netelement],
    netrelations: &[NetRelation],
    writer: &mut impl std::io::Write,
) -> Result<(), ProjectionError> {
    use geojson::{Feature, FeatureCollection, Geometry, Value};
    use serde_json::{Map, Value as JsonValue};

    let mut features: Vec<Feature> = Vec::with_capacity(netelements.len() + netrelations.len());

    for ne in netelements {
        let coords: Vec<Vec<f64>> = ne.geometry.coords().map(|c| vec![c.x, c.y]).collect();
        let geometry = Geometry::new(Value::LineString(coords));

        let mut properties = Map::new();
        properties.insert("id".to_string(), JsonValue::from(ne.id.clone()));
        properties.insert("crs".to_string(), JsonValue::from(ne.crs.clone()));

        features.push(Feature {
            bbox: None,
            geometry: Some(geometry),
            id: None,
            properties: Some(properties),
            foreign_members: None,
        });
    }

    for nr in netrelations {
        let navigability = match (nr.navigable_forward, nr.navigable_backward) {
            (true, true) => "both",
            (true, false) => "AB",
            (false, true) => "BA",
            (false, false) => "none",
        };

        let mut properties = Map::new();
        properties.insert("type".to_string(), JsonValue::from("netrelation"));
        properties.insert("id".to_string(), JsonValue::from(nr.id.clone()));
        properties.insert(
            "netelementA".to_string(),
            JsonValue::from(nr.from_netelement_id.clone()),
        );
        properties.insert(
            "netelementB".to_string(),
            JsonValue::from(nr.to_netelement_id.clone()),
        );
        properties.insert(
            "positionOnA".to_string(),
            JsonValue::from(nr.position_on_a as u64),
        );
        properties.insert(
            "positionOnB".to_string(),
            JsonValue::from(nr.position_on_b as u64),
        );
        properties.insert("navigability".to_string(), JsonValue::from(navigability));

        features.push(Feature {
            bbox: None,
            geometry: None,
            id: None,
            properties: Some(properties),
            foreign_members: None,
        });
    }

    let feature_collection = FeatureCollection {
        bbox: None,
        features,
        foreign_members: None,
    };

    let json = serde_json::to_string_pretty(&feature_collection).map_err(|e| {
        ProjectionError::GeoJsonError(format!("Failed to serialize network GeoJSON: {}", e))
    })?;

    writer.write_all(json.as_bytes())?;
    Ok(())
}

/// Write projected positions as GeoJSON FeatureCollection
pub fn write_geojson(
    positions: &[ProjectedPosition],
    writer: &mut impl std::io::Write,
) -> Result<(), ProjectionError> {
    use geojson::{Feature, FeatureCollection, Geometry, Value};
    use serde_json::{Map, Value as JsonValue};

    let mut features = Vec::new();

    for pos in positions {
        // Create Point geometry for projected position
        let geometry = Geometry::new(Value::Point(vec![
            pos.projected_coords.x(),
            pos.projected_coords.y(),
        ]));

        // Create properties
        let mut properties = Map::new();
        properties.insert(
            "original_lat".to_string(),
            JsonValue::from(pos.original.latitude),
        );
        properties.insert(
            "original_lon".to_string(),
            JsonValue::from(pos.original.longitude),
        );
        properties.insert(
            "original_time".to_string(),
            JsonValue::from(pos.original.timestamp.to_rfc3339()),
        );
        properties.insert(
            "netelement_id".to_string(),
            JsonValue::from(pos.netelement_id.clone()),
        );
        properties.insert(
            "measure_meters".to_string(),
            JsonValue::from(pos.measure_meters),
        );
        properties.insert(
            "projection_distance_meters".to_string(),
            JsonValue::from(pos.projection_distance_meters),
        );
        properties.insert("crs".to_string(), JsonValue::from(pos.crs.clone()));

        // Add original metadata
        for (key, value) in &pos.original.metadata {
            properties.insert(format!("original_{}", key), JsonValue::from(value.clone()));
        }

        let feature = Feature {
            bbox: None,
            geometry: Some(geometry),
            id: None,
            properties: Some(properties),
            foreign_members: None,
        };

        features.push(feature);
    }

    let feature_collection = FeatureCollection {
        bbox: None,
        features,
        foreign_members: None,
    };

    let json = serde_json::to_string_pretty(&feature_collection).map_err(|e| {
        ProjectionError::GeoJsonError(format!("Failed to serialize GeoJSON: {}", e))
    })?;

    writer.write_all(json.as_bytes())?;
    Ok(())
}

/// Parse a [`TrainPath`] from a GeoJSON FeatureCollection file.
///
/// Expects the format produced by [`write_trainpath_geojson`]: a FeatureCollection where
/// each Feature carries segment properties (`netelement_id`, `probability`,
/// `start_intrinsic`, `end_intrinsic`, `gnss_start_index`, `gnss_end_index`).
/// The FeatureCollection's `properties` object (stored in `foreign_members`) may
/// optionally contain `overall_probability` (float) and `calculated_at` (RFC3339).
///
/// # Errors
///
/// Returns [`ProjectionError::GeoJsonError`] when a required property is missing or
/// has an unexpected type, or when the file is not a valid FeatureCollection.
pub fn parse_trainpath_geojson(path: &str) -> Result<crate::models::TrainPath, ProjectionError> {
    use crate::models::AssociatedNetElement;

    let geojson_str = fs::read_to_string(path)?;
    let geojson = geojson_str.parse::<GeoJson>().map_err(|e| {
        ProjectionError::GeoJsonError(format!("Failed to parse TrainPath GeoJSON: {}", e))
    })?;

    let fc = match geojson {
        GeoJson::FeatureCollection(fc) => fc,
        _ => {
            return Err(ProjectionError::GeoJsonError(
                "TrainPath GeoJSON must be a FeatureCollection".to_string(),
            ))
        }
    };

    // Extract overall_probability and calculated_at from the top-level "properties" object
    // stored in foreign_members (written by write_trainpath_geojson).
    let (overall_probability, calculated_at) = fc
        .foreign_members
        .as_ref()
        .and_then(|fm| fm.get("properties"))
        .and_then(|v| v.as_object())
        .map(|props| {
            let prob = props.get("overall_probability").and_then(|v| v.as_f64());
            let calc_at = props
                .get("calculated_at")
                .and_then(|v| v.as_str())
                .and_then(|s| parse_timestamp_flexible(s).ok())
                .map(|dt| dt.with_timezone(&chrono::Utc));
            (prob, calc_at)
        })
        .unwrap_or((None, None));

    let mut segments = Vec::new();

    for (idx, feature) in fc.features.iter().enumerate() {
        let props = feature.properties.as_ref().ok_or_else(|| {
            ProjectionError::GeoJsonError(format!("TrainPath feature {} missing properties", idx))
        })?;

        macro_rules! get_str {
            ($key:expr) => {
                props
                    .get($key)
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
                    .ok_or_else(|| {
                        ProjectionError::GeoJsonError(format!(
                            "TrainPath feature {} missing or invalid '{}' property",
                            idx, $key
                        ))
                    })
            };
        }
        macro_rules! get_f64 {
            ($key:expr) => {
                props.get($key).and_then(|v| v.as_f64()).ok_or_else(|| {
                    ProjectionError::GeoJsonError(format!(
                        "TrainPath feature {} missing or invalid '{}' property",
                        idx, $key
                    ))
                })
            };
        }
        macro_rules! get_usize {
            ($key:expr) => {
                props
                    .get($key)
                    .and_then(|v| v.as_u64())
                    .map(|v| v as usize)
                    .ok_or_else(|| {
                        ProjectionError::GeoJsonError(format!(
                            "TrainPath feature {} missing or invalid '{}' property",
                            idx, $key
                        ))
                    })
            };
        }

        let segment = AssociatedNetElement::new(
            get_str!("netelement_id")?,
            get_f64!("probability")?,
            get_f64!("start_intrinsic")?,
            get_f64!("end_intrinsic")?,
            get_usize!("gnss_start_index")?,
            get_usize!("gnss_end_index")?,
        )?;

        segments.push(segment);
    }

    let overall_prob = overall_probability.unwrap_or_else(|| {
        if segments.is_empty() {
            1.0
        } else {
            let sum: f64 = segments.iter().map(|s| s.probability).sum();
            sum / segments.len() as f64
        }
    });

    crate::models::TrainPath::new(segments, overall_prob, calculated_at, None)
}

/// Write TrainPath as GeoJSON FeatureCollection
///
/// Serializes a TrainPath to GeoJSON, with each segment as a separate feature.
/// The overall path probability and metadata are stored in the FeatureCollection properties.
///
/// # Arguments
///
/// * `train_path` - The TrainPath to serialize
/// * `netelements` - Map of netelement IDs to Netelement geometries (for creating LineString features)
/// * `writer` - Output writer
///
/// # Output Format
///
/// ```json
/// {
///   "type": "FeatureCollection",
///   "properties": {
///     "overall_probability": 0.89,
///     "calculated_at": "2025-01-15T10:30:00Z",
///     "distance_scale": 10.0,
///     "heading_scale": 2.0
///   },
///   "features": [
///     {
///       "type": "Feature",
///       "geometry": { "type": "LineString", "coordinates": [...] },
///       "properties": {
///         "netelement_id": "NE_A",
///         "probability": 0.87,
///         "start_intrinsic": 0.0,
///         "end_intrinsic": 1.0,
///         "gnss_start_index": 0,
///         "gnss_end_index": 10
///       }
///     }
///   ]
/// }
/// ```
pub fn write_trainpath_geojson(
    train_path: &crate::models::TrainPath,
    netelements: &std::collections::HashMap<String, Netelement>,
    writer: &mut impl std::io::Write,
) -> Result<(), ProjectionError> {
    use geojson::{Feature, FeatureCollection, Geometry, Value};
    use serde_json::{Map, Value as JsonValue};

    let mut features = Vec::new();

    // Create a feature for each segment
    for segment in &train_path.segments {
        // Look up the netelement geometry
        let netelement = netelements.get(&segment.netelement_id).ok_or_else(|| {
            ProjectionError::InvalidGeometry(format!(
                "Netelement {} not found in provided map",
                segment.netelement_id
            ))
        })?;

        // Extract the portion of the linestring covered by this segment
        // For simplicity, use the full linestring geometry
        // (In a production system, you'd extract the substring from start_intrinsic to end_intrinsic)
        let coords: Vec<Vec<f64>> = netelement
            .geometry
            .points()
            .map(|point| vec![point.x(), point.y()])
            .collect();

        let geometry = Geometry::new(Value::LineString(coords));

        // Create properties for this segment
        let mut properties = Map::new();
        properties.insert(
            "netelement_id".to_string(),
            JsonValue::from(segment.netelement_id.clone()),
        );
        properties.insert(
            "probability".to_string(),
            JsonValue::from(segment.probability),
        );
        properties.insert(
            "start_intrinsic".to_string(),
            JsonValue::from(segment.start_intrinsic),
        );
        properties.insert(
            "end_intrinsic".to_string(),
            JsonValue::from(segment.end_intrinsic),
        );
        properties.insert(
            "gnss_start_index".to_string(),
            JsonValue::from(segment.gnss_start_index as i64),
        );
        properties.insert(
            "gnss_end_index".to_string(),
            JsonValue::from(segment.gnss_end_index as i64),
        );

        let feature = Feature {
            bbox: None,
            geometry: Some(geometry),
            id: None,
            properties: Some(properties),
            foreign_members: None,
        };

        features.push(feature);
    }

    // Create FeatureCollection with overall properties
    let mut fc_properties = Map::new();
    fc_properties.insert(
        "overall_probability".to_string(),
        JsonValue::from(train_path.overall_probability),
    );

    if let Some(calculated_at) = &train_path.calculated_at {
        fc_properties.insert(
            "calculated_at".to_string(),
            JsonValue::from(calculated_at.to_rfc3339()),
        );
    }

    // Add metadata if present
    if let Some(metadata) = &train_path.metadata {
        fc_properties.insert(
            "distance_scale".to_string(),
            JsonValue::from(metadata.distance_scale),
        );
        fc_properties.insert(
            "heading_scale".to_string(),
            JsonValue::from(metadata.heading_scale),
        );
        fc_properties.insert(
            "cutoff_distance".to_string(),
            JsonValue::from(metadata.cutoff_distance),
        );
        fc_properties.insert(
            "heading_cutoff".to_string(),
            JsonValue::from(metadata.heading_cutoff),
        );
        fc_properties.insert(
            "probability_threshold".to_string(),
            JsonValue::from(metadata.probability_threshold),
        );
        if let Some(resampling_dist) = metadata.resampling_distance {
            fc_properties.insert(
                "resampling_distance".to_string(),
                JsonValue::from(resampling_dist),
            );
        }
        fc_properties.insert(
            "fallback_mode".to_string(),
            JsonValue::from(metadata.fallback_mode),
        );
        fc_properties.insert(
            "candidate_paths_evaluated".to_string(),
            JsonValue::from(metadata.candidate_paths_evaluated as i64),
        );
        fc_properties.insert(
            "bidirectional_path".to_string(),
            JsonValue::from(metadata.bidirectional_path),
        );
    }

    let mut foreign_members = Map::new();
    foreign_members.insert("properties".to_string(), JsonValue::Object(fc_properties));

    let feature_collection = FeatureCollection {
        bbox: None,
        features,
        foreign_members: Some(foreign_members),
    };

    let json = serde_json::to_string_pretty(&feature_collection).map_err(|e| {
        ProjectionError::GeoJsonError(format!("Failed to serialize TrainPath GeoJSON: {}", e))
    })?;

    writer.write_all(json.as_bytes())?;
    Ok(())
}

#[cfg(test)]
mod tests;

pub mod detections;