oxigdal-proj 0.1.5

Pure Rust coordinate transformation and projection support for OxiGDAL - EPSG database and CRS operations
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
//! Well-Known Text (WKT) parser for CRS definitions.
//!
//! This module provides parsing capabilities for WKT (Well-Known Text) format CRS definitions.
//! WKT is a text markup language for representing coordinate reference systems and geometric objects.

use crate::error::{Error, Result};
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeMap as HashMap;
#[cfg(not(feature = "std"))]
use alloc::format;
#[cfg(not(feature = "std"))]
use alloc::string::{String, ToString};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::collections::HashMap;

/// WKT parser for coordinate reference systems.
pub struct WktParser {
    input: String,
    position: usize,
}

/// Parsed WKT node representing a CRS component.
#[derive(Debug, Clone, PartialEq)]
pub struct WktNode {
    /// Node type (e.g., "GEOGCS", "PROJCS", "DATUM")
    pub node_type: String,
    /// Node value (first string in brackets, if present)
    pub value: Option<String>,
    /// Child nodes
    pub children: Vec<WktNode>,
    /// Parameters (key-value pairs)
    pub parameters: HashMap<String, String>,
}

/// Direction of a coordinate axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AxisDirection {
    /// North
    North,
    /// South
    South,
    /// East
    East,
    /// West
    West,
    /// Up
    Up,
    /// Down
    Down,
    /// Other / unrecognised direction
    Other,
}

impl AxisDirection {
    /// Parse a direction keyword (case-insensitive).
    pub fn from_keyword(s: &str) -> Self {
        match s.to_uppercase().as_str() {
            "NORTH" => Self::North,
            "SOUTH" => Self::South,
            "EAST" => Self::East,
            "WEST" => Self::West,
            "UP" => Self::Up,
            "DOWN" => Self::Down,
            _ => Self::Other,
        }
    }
}

/// Information about a single coordinate axis extracted from a WKT `AXIS` node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AxisInfo {
    /// Axis name (e.g. "Latitude", "Easting").
    pub name: String,
    /// Axis direction.
    pub direction: AxisDirection,
}

impl WktParser {
    /// Creates a new WKT parser.
    pub fn new<S: Into<String>>(input: S) -> Self {
        Self {
            input: input.into(),
            position: 0,
        }
    }

    /// Parses the WKT string.
    ///
    /// # Errors
    ///
    /// Returns an error if the WKT string is malformed.
    pub fn parse(&mut self) -> Result<WktNode> {
        self.skip_whitespace();
        self.parse_node()
    }

    /// Parses a WKT node.
    fn parse_node(&mut self) -> Result<WktNode> {
        // Parse node type
        let node_type = self.parse_identifier()?;

        self.skip_whitespace();

        // Expect opening bracket
        if !self.expect_char('[')? {
            return Err(Error::wkt_parse_error(
                self.position,
                format!("Expected '[' after {}", node_type),
            ));
        }

        self.skip_whitespace();

        // Parse node value (first string, if present)
        let value = if self.peek_char() == Some('"') {
            Some(self.parse_string()?)
        } else {
            None
        };

        let mut children = Vec::new();
        let mut parameters = HashMap::new();
        let mut first_item = value.is_none(); // Track if we're parsing first item after name

        // Parse children and parameters
        loop {
            self.skip_whitespace();

            // Check for closing bracket
            if self.peek_char() == Some(']') {
                self.advance();
                break;
            }

            // Expect comma separator (except before first item)
            if !first_item {
                if !self.expect_char(',')? {
                    return Err(Error::wkt_parse_error(
                        self.position,
                        "Expected ',' or ']'".to_string(),
                    ));
                }
                self.skip_whitespace();
            }
            first_item = false;

            // Try to parse as child node or parameter
            // Look ahead to determine if this is a node (IDENTIFIER[) or parameter
            let saved_pos = self.position;

            if self.is_identifier_start() {
                // Try to parse identifier
                let _ident_result = self.parse_identifier();
                if _ident_result.is_ok() {
                    self.skip_whitespace();

                    if self.peek_char() == Some('[') {
                        // This is a node - reset and parse as node
                        self.position = saved_pos;
                        children.push(self.parse_node()?);
                    } else {
                        // This is a parameter - reset and parse as parameter
                        self.position = saved_pos;
                        let (key, value) = self.parse_parameter()?;
                        parameters.insert(key, value);
                    }
                } else {
                    // Failed to parse identifier, try as parameter
                    self.position = saved_pos;
                    let (key, value) = self.parse_parameter()?;
                    parameters.insert(key, value);
                }
            } else {
                // Not an identifier start, parse as parameter (number or string)
                let (key, value) = self.parse_parameter()?;
                parameters.insert(key, value);
            }
        }

        Ok(WktNode {
            node_type,
            value,
            children,
            parameters,
        })
    }

    /// Parses an identifier (e.g., GEOGCS, DATUM).
    fn parse_identifier(&mut self) -> Result<String> {
        let mut ident = String::new();

        while let Some(ch) = self.peek_char() {
            if ch.is_ascii_alphanumeric() || ch == '_' {
                ident.push(ch);
                self.advance();
            } else {
                break;
            }
        }

        if ident.is_empty() {
            Err(Error::wkt_parse_error(
                self.position,
                "Expected identifier".to_string(),
            ))
        } else {
            Ok(ident)
        }
    }

    /// Parses a quoted string.
    fn parse_string(&mut self) -> Result<String> {
        if !self.expect_char('"')? {
            return Err(Error::wkt_parse_error(
                self.position,
                "Expected '\"'".to_string(),
            ));
        }

        let mut value = String::new();

        loop {
            match self.peek_char() {
                Some('"') => {
                    self.advance();
                    break;
                }
                Some('\\') => {
                    self.advance();
                    if let Some(ch) = self.peek_char() {
                        value.push(ch);
                        self.advance();
                    } else {
                        return Err(Error::wkt_parse_error(
                            self.position,
                            "Unexpected end of string".to_string(),
                        ));
                    }
                }
                Some(ch) => {
                    value.push(ch);
                    self.advance();
                }
                None => {
                    return Err(Error::wkt_parse_error(
                        self.position,
                        "Unterminated string".to_string(),
                    ));
                }
            }
        }

        Ok(value)
    }

    /// Parses a parameter (key-value pair or just value).
    fn parse_parameter(&mut self) -> Result<(String, String)> {
        // Try to parse as identifier=value or just value
        let saved_pos = self.position;

        if let Ok(ident) = self.parse_identifier() {
            self.skip_whitespace();
            if self.peek_char() == Some('=') {
                self.advance();
                self.skip_whitespace();
                let value = self.parse_value()?;
                return Ok((ident, value));
            }
        }

        // Reset and parse as just a value
        self.position = saved_pos;
        let value = self.parse_value()?;
        Ok((format!("param_{}", self.position), value))
    }

    /// Parses a value (string or number).
    fn parse_value(&mut self) -> Result<String> {
        self.skip_whitespace();

        if self.peek_char() == Some('"') {
            self.parse_string()
        } else {
            self.parse_number()
        }
    }

    /// Parses a number.
    fn parse_number(&mut self) -> Result<String> {
        let mut number = String::new();

        // Handle negative sign
        if self.peek_char() == Some('-') {
            number.push('-');
            self.advance();
        }

        while let Some(ch) = self.peek_char() {
            if ch.is_ascii_digit() || ch == '.' || ch == 'e' || ch == 'E' || ch == '+' || ch == '-'
            {
                number.push(ch);
                self.advance();
            } else {
                break;
            }
        }

        if number.is_empty() || number == "-" {
            Err(Error::wkt_parse_error(
                self.position,
                "Expected number".to_string(),
            ))
        } else {
            Ok(number)
        }
    }

    /// Checks if the current character is the start of an identifier.
    fn is_identifier_start(&self) -> bool {
        matches!(self.peek_char(), Some(ch) if ch.is_ascii_alphabetic() || ch == '_')
    }

    /// Expects a specific character.
    fn expect_char(&mut self, expected: char) -> Result<bool> {
        if self.peek_char() == Some(expected) {
            self.advance();
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Peeks at the current character without consuming it.
    fn peek_char(&self) -> Option<char> {
        self.input.chars().nth(self.position)
    }

    /// Advances to the next character.
    fn advance(&mut self) {
        if self.position < self.input.len() {
            self.position += 1;
        }
    }

    /// Skips whitespace characters.
    fn skip_whitespace(&mut self) {
        while let Some(ch) = self.peek_char() {
            if ch.is_whitespace() {
                self.advance();
            } else {
                break;
            }
        }
    }
}

impl WktNode {
    /// Finds a child node by type.
    pub fn find_child(&self, node_type: &str) -> Option<&WktNode> {
        self.children
            .iter()
            .find(|child| child.node_type == node_type)
    }

    /// Finds all child nodes of a given type.
    pub fn find_children(&self, node_type: &str) -> Vec<&WktNode> {
        self.children
            .iter()
            .filter(|child| child.node_type == node_type)
            .collect()
    }

    /// Gets a parameter value by key.
    pub fn get_parameter(&self, key: &str) -> Option<&str> {
        self.parameters.get(key).map(|s| s.as_str())
    }

    /// Finds a child node matching any of the given type names.
    ///
    /// This is useful for WKT1/WKT2 aliases (e.g. `SPHEROID` vs `ELLIPSOID`).
    pub fn find_child_any(&self, node_types: &[&str]) -> Option<&WktNode> {
        self.children
            .iter()
            .find(|child| node_types.iter().any(|t| child.node_type == *t))
    }

    /// Converts the WKT node to a string representation.
    pub fn to_string_repr(&self) -> String {
        let mut result = self.node_type.clone();
        result.push('[');

        if let Some(value) = &self.value {
            result.push('"');
            result.push_str(value);
            result.push('"');

            if !self.children.is_empty() || !self.parameters.is_empty() {
                result.push(',');
            }
        }

        for (i, child) in self.children.iter().enumerate() {
            if i > 0 || self.value.is_some() {
                result.push(',');
            }
            result.push_str(&child.to_string_repr());
        }

        for (i, (key, value)) in self.parameters.iter().enumerate() {
            if i > 0 || !self.children.is_empty() || self.value.is_some() {
                result.push(',');
            }
            result.push_str(key);
            result.push('=');
            result.push_str(value);
        }

        result.push(']');
        result
    }
}

/// Parses a WKT string into a node structure.
///
/// # Arguments
///
/// * `wkt` - WKT string to parse
///
/// # Errors
///
/// Returns an error if the WKT string is malformed.
pub fn parse_wkt<S: Into<String>>(wkt: S) -> Result<WktNode> {
    let mut parser = WktParser::new(wkt);
    parser.parse()
}

// =============================================================================
// WKT version and error types
// =============================================================================

/// WKT format version.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WktVersion {
    /// WKT 1 (uses PROJCS / GEOGCS keywords).
    Wkt1,
    /// WKT 2 (ISO 19162:2019, uses PROJCRS / GEOGCRS keywords).
    Wkt2,
    /// Version could not be determined.
    Unknown,
}

/// Error type for WKT parsing failures.
#[derive(Debug, Clone)]
pub struct WktError {
    /// Human-readable error message.
    pub message: String,
    /// Byte offset in the input string where the error was detected, if known.
    pub position: Option<usize>,
}

impl WktError {
    /// Construct a new `WktError`.
    pub fn new(message: impl Into<String>, position: Option<usize>) -> Self {
        Self {
            message: message.into(),
            position,
        }
    }
}

#[cfg(feature = "std")]
impl std::fmt::Display for WktError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.position {
            Some(pos) => write!(f, "WKT parse error at position {}: {}", pos, self.message),
            None => write!(f, "WKT parse error: {}", self.message),
        }
    }
}

#[cfg(not(feature = "std"))]
impl core::fmt::Display for WktError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self.position {
            Some(pos) => write!(f, "WKT parse error at position {}: {}", pos, self.message),
            None => write!(f, "WKT parse error: {}", self.message),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for WktError {}

// =============================================================================
// Static / free-function methods on WktParser
// =============================================================================

impl WktParser {
    /// Detect the WKT version of the given string.
    ///
    /// - Returns `WktVersion::Wkt2` if the string contains WKT 2 keywords
    ///   (`PROJCRS`, `GEOGCRS`, `GEODCRS`, `ENGCRS`, `VERTCRS`, `COMPOUNDCRS`).
    /// - Returns `WktVersion::Wkt1` if it contains WKT 1 keywords
    ///   (`PROJCS`, `GEOGCS`, `GEOCCS`, `VERT_CS`, `COMPD_CS`).
    /// - Returns `WktVersion::Unknown` otherwise.
    pub fn detect_version(wkt: &str) -> WktVersion {
        let upper = wkt.to_uppercase();
        // WKT2 keywords (longer/newer forms come first to avoid false matches)
        if upper.contains("PROJCRS")
            || upper.contains("GEOGCRS")
            || upper.contains("GEODCRS")
            || upper.contains("ENGCRS")
            || upper.contains("VERTCRS")
            || upper.contains("COMPOUNDCRS")
        {
            return WktVersion::Wkt2;
        }
        // WKT1 keywords
        if upper.contains("PROJCS")
            || upper.contains("GEOGCS")
            || upper.contains("GEOCCS")
            || upper.contains("VERT_CS")
            || upper.contains("COMPD_CS")
        {
            return WktVersion::Wkt1;
        }
        WktVersion::Unknown
    }

    /// Extract the top-level name from a WKT string.
    ///
    /// For example:
    /// - `PROJCS["WGS 84 / UTM zone 32N",...]` → `Some("WGS 84 / UTM zone 32N")`
    /// - `GEOGCS["WGS 84",...]` → `Some("WGS 84")`
    pub fn extract_name(wkt: &str) -> Option<String> {
        // Find the first '[' after the leading keyword
        let bracket_pos = wkt.find('[')?;
        let after_bracket = &wkt[bracket_pos + 1..];

        // Find the first '"'
        let quote_start = after_bracket.find('"')?;
        let after_quote = &after_bracket[quote_start + 1..];

        // Find closing '"'
        let quote_end = after_quote.find('"')?;
        Some(after_quote[..quote_end].to_string())
    }

    /// Extract the EPSG code from a WKT string.
    ///
    /// Searches for:
    /// - `AUTHORITY["EPSG","<code>"]`  (WKT 1)
    /// - `ID["EPSG",<code>]`           (WKT 2)
    pub fn extract_epsg(wkt: &str) -> Option<i32> {
        // Try WKT1 form: AUTHORITY["EPSG","4326"]
        if let Some(idx) = wkt.find("AUTHORITY[\"EPSG\",\"") {
            let after = &wkt[idx + "AUTHORITY[\"EPSG\",\"".len()..];
            let end = after.find('"')?;
            let code_str = &after[..end];
            return code_str.parse::<i32>().ok();
        }
        // Try WKT2 form: ID["EPSG",4326]
        if let Some(idx) = wkt.find("ID[\"EPSG\",") {
            let after = &wkt[idx + "ID[\"EPSG\",".len()..];
            // code may be quoted or unquoted
            let after = after.trim_start();
            let after = after.trim_start_matches('"');
            let end = after.find(|c: char| !c.is_ascii_digit())?;
            let code_str = &after[..end];
            return code_str.parse::<i32>().ok();
        }
        None
    }

    /// Extract the unit name and conversion factor from a WKT string.
    ///
    /// Searches for `UNIT["<name>",<factor>]` or `LENGTHUNIT["<name>",<factor>]`.
    pub fn extract_unit(wkt: &str) -> Option<(String, f64)> {
        // Try UNIT[ first, then LENGTHUNIT[
        let search_terms = ["UNIT[\"", "LENGTHUNIT[\"", "ANGLEUNIT[\""];
        for term in &search_terms {
            if let Some(idx) = wkt.find(term) {
                let after = &wkt[idx + term.len()..];
                let name_end = after.find('"')?;
                let unit_name = after[..name_end].to_string();
                // skip past name,"
                let rest = &after[name_end + 1..];
                let comma_pos = rest.find(',')?;
                let rest_after_comma = rest[comma_pos + 1..].trim_start();
                // extract number up to ']' or ','
                let num_end = rest_after_comma
                    .find([']', ','])
                    .unwrap_or(rest_after_comma.len());
                let factor_str = rest_after_comma[..num_end].trim();
                if let Ok(factor) = factor_str.parse::<f64>() {
                    return Some((unit_name, factor));
                }
            }
        }
        None
    }

    /// Extract axis information from a WKT string.
    ///
    /// Finds all `AXIS["<name>",<direction>]` nodes in the raw WKT text and returns
    /// an ordered list of [`AxisInfo`].
    pub fn extract_axes(wkt: &str) -> Vec<AxisInfo> {
        let mut axes = Vec::new();
        let mut search_from = 0;

        while let Some(idx) = wkt[search_from..].find("AXIS[\"") {
            let abs_idx = search_from + idx;
            let after = &wkt[abs_idx + "AXIS[\"".len()..];

            // Extract axis name up to the closing quote
            let name_end = match after.find('"') {
                Some(e) => e,
                None => break,
            };
            let axis_name = after[..name_end].to_string();

            // After the name there should be a comma and then the direction keyword
            let rest = &after[name_end + 1..];
            let comma_pos = match rest.find(',') {
                Some(p) => p,
                None => break,
            };
            let after_comma = rest[comma_pos + 1..].trim_start();
            // direction ends at ']' or ','
            let dir_end = after_comma.find([']', ',']).unwrap_or(after_comma.len());
            let direction_str = after_comma[..dir_end].trim();
            let direction = AxisDirection::from_keyword(direction_str);

            axes.push(AxisInfo {
                name: axis_name,
                direction,
            });

            // Move past this AXIS node
            search_from = abs_idx + "AXIS[\"".len() + name_end + 1;
        }

        axes
    }

    /// Extract the ellipsoid name from a WKT string.
    ///
    /// Supports both WKT1 `SPHEROID["<name>"...]` and WKT2 `ELLIPSOID["<name>"...]`.
    pub fn extract_ellipsoid_name(wkt: &str) -> Option<String> {
        for keyword in &["ELLIPSOID[\"", "SPHEROID[\""] {
            if let Some(idx) = wkt.find(keyword) {
                let after = &wkt[idx + keyword.len()..];
                let end = after.find('"')?;
                return Some(after[..end].to_string());
            }
        }
        None
    }

    /// Parse a WKT string into a `CrsDefinition` (best-effort).
    ///
    /// This performs syntactic analysis only; it does not validate geodetic parameters.
    #[cfg(feature = "std")]
    pub fn parse_crs(
        wkt: &str,
    ) -> core::result::Result<crate::crs_registry::CrsDefinition, WktError> {
        use crate::crs_registry::{AreaOfUse, CrsDefinition, CrsType, CrsUnit};

        if wkt.trim().is_empty() {
            return Err(WktError::new("WKT string is empty", Some(0)));
        }

        let name = match Self::extract_name(wkt) {
            Some(n) => n,
            None => return Err(WktError::new("Could not extract CRS name from WKT", None)),
        };

        let epsg_code = Self::extract_epsg(wkt);

        // Detect CRS type from leading keyword
        let upper = wkt.trim_start().to_uppercase();
        let crs_type = if upper.starts_with("PROJCRS") || upper.starts_with("PROJCS") {
            CrsType::Projected
        } else if upper.starts_with("GEOGCRS") || upper.starts_with("GEOGCS") {
            CrsType::Geographic2D
        } else if upper.starts_with("GEOCCS") || upper.starts_with("GEODCRS") {
            CrsType::Geocentric
        } else if upper.starts_with("VERT_CS") || upper.starts_with("VERTCRS") {
            CrsType::Vertical
        } else if upper.starts_with("COMPD_CS") || upper.starts_with("COMPOUNDCRS") {
            CrsType::Compound
        } else {
            CrsType::Geographic2D // fallback
        };

        // Attempt to extract datum name (simple heuristic: value of DATUM node)
        let datum = extract_datum_name(wkt).unwrap_or_default();

        // Attempt to extract unit
        let unit = match Self::extract_unit(wkt) {
            Some((_, factor)) if (factor - 1.0).abs() < f64::EPSILON => CrsUnit::Metre,
            Some((ref name_str, _)) if name_str.to_lowercase().contains("degree") => {
                CrsUnit::Degree
            }
            Some((ref name_str, _)) if name_str.to_lowercase().contains("foot") => {
                CrsUnit::FootIntl
            }
            _ => match crs_type {
                CrsType::Projected => CrsUnit::Metre,
                _ => CrsUnit::Degree,
            },
        };

        Ok(CrsDefinition {
            epsg_code,
            name: name.clone(),
            crs_type,
            datum,
            unit,
            proj_string: None,
            wkt_name: Some(name),
            area_of_use: None::<AreaOfUse>,
            deprecated: false,
        })
    }
}

/// Extract the datum name from a WKT string by finding `DATUM["<name>"`.
fn extract_datum_name(wkt: &str) -> Option<String> {
    let idx = wkt.find("DATUM[\"").or_else(|| wkt.find("DATUM [\""))?;
    let after = &wkt[idx..];
    let bracket_pos = after.find('[')?;
    let after_bracket = &after[bracket_pos + 1..];
    let quote_start = after_bracket.find('"')?;
    let after_quote = &after_bracket[quote_start + 1..];
    let quote_end = after_quote.find('"')?;
    Some(after_quote[..quote_end].to_string())
}

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

    #[test]
    fn test_parse_simple_geogcs() {
        let wkt = r#"GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]]"#;
        let result = parse_wkt(wkt);
        assert!(result.is_ok());

        let node = result.expect("should parse");
        assert_eq!(node.node_type, "GEOGCS");
        assert_eq!(node.value, Some("WGS 84".to_string()));
        assert!(node.find_child("DATUM").is_some());
    }

    #[test]
    fn test_parse_projcs() {
        let wkt = r#"PROJCS["WGS 84 / UTM zone 33N",GEOGCS["WGS 84",DATUM["WGS_1984"]]]"#;
        let result = parse_wkt(wkt);
        assert!(result.is_ok());

        let node = result.expect("should parse");
        assert_eq!(node.node_type, "PROJCS");
        assert_eq!(node.value, Some("WGS 84 / UTM zone 33N".to_string()));
        assert!(node.find_child("GEOGCS").is_some());
    }

    #[test]
    fn test_parse_with_parameters() {
        let wkt = r#"SPHEROID["WGS 84",6378137,298.257223563]"#;
        let result = parse_wkt(wkt);
        assert!(result.is_ok());

        let node = result.expect("should parse");
        assert_eq!(node.node_type, "SPHEROID");
        assert_eq!(node.value, Some("WGS 84".to_string()));
    }

    #[test]
    fn test_parse_nested() {
        let wkt = r#"DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]"#;
        let result = parse_wkt(wkt);
        assert!(result.is_ok());

        let node = result.expect("should parse");
        assert_eq!(node.node_type, "DATUM");
        assert_eq!(node.value, Some("WGS_1984".to_string()));

        let spheroid = node.find_child("SPHEROID");
        assert!(spheroid.is_some());
        let spheroid = spheroid.expect("should have spheroid");
        assert_eq!(spheroid.value, Some("WGS 84".to_string()));
    }

    #[test]
    fn test_parse_invalid_wkt() {
        // Missing closing bracket
        let result = parse_wkt(r#"GEOGCS["WGS 84""#);
        assert!(result.is_err());

        // Missing opening bracket
        let result = parse_wkt(r#"GEOGCS"WGS 84"]"#);
        assert!(result.is_err());

        // Empty string
        let result = parse_wkt("");
        assert!(result.is_err());
    }

    #[test]
    fn test_find_child() {
        let wkt = r#"GEOGCS["WGS 84",DATUM["WGS_1984"],PRIMEM["Greenwich",0]]"#;
        let node = parse_wkt(wkt).expect("should parse");

        assert!(node.find_child("DATUM").is_some());
        assert!(node.find_child("PRIMEM").is_some());
        assert!(node.find_child("NONEXISTENT").is_none());
    }

    #[test]
    fn test_find_children() {
        let wkt = r#"COMPD_CS["name",GEOGCS["WGS 84"],VERT_CS["height"]]"#;
        let node = parse_wkt(wkt).expect("should parse");

        let geogcs = node.find_children("GEOGCS");
        assert_eq!(geogcs.len(), 1);

        let vert_cs = node.find_children("VERT_CS");
        assert_eq!(vert_cs.len(), 1);
    }

    #[test]
    fn test_node_to_string() {
        let wkt = r#"SPHEROID["WGS 84",6378137,298.257223563]"#;
        let node = parse_wkt(wkt).expect("should parse");
        let result = node.to_string_repr();

        // Should contain the essential components
        assert!(result.contains("SPHEROID"));
        assert!(result.contains("WGS 84"));
    }

    // =========================================================================
    // WKT2:2019 parsing tests
    // =========================================================================

    #[test]
    fn test_parse_wkt2_geogcrs() {
        let wkt = r#"GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],ID["EPSG",4326]]"#;
        let node = parse_wkt(wkt).expect("should parse WKT2 GEOGCRS");
        assert_eq!(node.node_type, "GEOGCRS");
        assert_eq!(node.value, Some("WGS 84".to_string()));
        assert!(node.find_child("DATUM").is_some());
        assert!(node.find_child("ID").is_some());

        // ELLIPSOID should be parsed as a child of DATUM
        let datum = node.find_child("DATUM").expect("should have DATUM");
        let ellipsoid = datum.find_child("ELLIPSOID");
        assert!(ellipsoid.is_some());
        let ellipsoid = ellipsoid.expect("should have ELLIPSOID");
        assert_eq!(ellipsoid.value, Some("WGS 84".to_string()));
    }

    #[test]
    fn test_parse_wkt2_projcrs() {
        let wkt = r#"PROJCRS["WGS 84 / UTM zone 33N",BASEGEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]]],ID["EPSG",32633]]"#;
        let node = parse_wkt(wkt).expect("should parse WKT2 PROJCRS");
        assert_eq!(node.node_type, "PROJCRS");
        assert_eq!(node.value, Some("WGS 84 / UTM zone 33N".to_string()));
        assert!(node.find_child("BASEGEOGCRS").is_some());
    }

    #[test]
    fn test_ellipsoid_keyword_parsed() {
        // WKT2 uses ELLIPSOID instead of SPHEROID
        let wkt = r#"ELLIPSOID["WGS 84",6378137,298.257223563]"#;
        let node = parse_wkt(wkt).expect("should parse ELLIPSOID node");
        assert_eq!(node.node_type, "ELLIPSOID");
        assert_eq!(node.value, Some("WGS 84".to_string()));
    }

    #[test]
    fn test_find_child_any_spheroid_or_ellipsoid() {
        // WKT1 with SPHEROID
        let wkt1 = r#"DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]"#;
        let node1 = parse_wkt(wkt1).expect("parse wkt1");
        let found1 = node1.find_child_any(&["SPHEROID", "ELLIPSOID"]);
        assert!(found1.is_some());
        assert_eq!(found1.expect("found").node_type, "SPHEROID");

        // WKT2 with ELLIPSOID
        let wkt2 =
            r#"DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]]"#;
        let node2 = parse_wkt(wkt2).expect("parse wkt2");
        let found2 = node2.find_child_any(&["SPHEROID", "ELLIPSOID"]);
        assert!(found2.is_some());
        assert_eq!(found2.expect("found").node_type, "ELLIPSOID");
    }

    #[test]
    fn test_extract_ellipsoid_name_wkt1() {
        let wkt = r#"GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]]"#;
        let name = WktParser::extract_ellipsoid_name(wkt);
        assert_eq!(name, Some("WGS 84".to_string()));
    }

    #[test]
    fn test_extract_ellipsoid_name_wkt2() {
        let wkt =
            r#"GEOGCRS["WGS 84",DATUM["WGS 1984",ELLIPSOID["WGS 84",6378137,298.257223563]]]"#;
        let name = WktParser::extract_ellipsoid_name(wkt);
        assert_eq!(name, Some("WGS 84".to_string()));
    }

    #[test]
    fn test_extract_axes() {
        let wkt = r#"GEOGCRS["WGS 84",AXIS["Latitude",NORTH],AXIS["Longitude",EAST]]"#;
        let axes = WktParser::extract_axes(wkt);
        assert_eq!(axes.len(), 2);

        assert_eq!(axes[0].name, "Latitude");
        assert_eq!(axes[0].direction, AxisDirection::North);
        assert_eq!(axes[1].name, "Longitude");
        assert_eq!(axes[1].direction, AxisDirection::East);
    }

    #[test]
    fn test_extract_axes_projected() {
        let wkt = r#"PROJCRS["UTM 33N",AXIS["Easting",EAST],AXIS["Northing",NORTH]]"#;
        let axes = WktParser::extract_axes(wkt);
        assert_eq!(axes.len(), 2);

        assert_eq!(axes[0].name, "Easting");
        assert_eq!(axes[0].direction, AxisDirection::East);
        assert_eq!(axes[1].name, "Northing");
        assert_eq!(axes[1].direction, AxisDirection::North);
    }

    #[test]
    fn test_extract_axes_with_up() {
        let wkt = r#"VERTCRS["Height",AXIS["Height",UP]]"#;
        let axes = WktParser::extract_axes(wkt);
        assert_eq!(axes.len(), 1);
        assert_eq!(axes[0].name, "Height");
        assert_eq!(axes[0].direction, AxisDirection::Up);
    }

    #[test]
    fn test_extract_axes_empty() {
        let wkt = r#"GEOGCS["WGS 84",DATUM["WGS_1984"]]"#;
        let axes = WktParser::extract_axes(wkt);
        assert!(axes.is_empty());
    }

    #[test]
    fn test_detect_version_wkt2() {
        let wkt = r#"GEOGCRS["WGS 84",DATUM["WGS 1984"]]"#;
        assert_eq!(WktParser::detect_version(wkt), WktVersion::Wkt2);

        let wkt2 = r#"PROJCRS["UTM",BASEGEOGCRS["WGS 84"]]"#;
        assert_eq!(WktParser::detect_version(wkt2), WktVersion::Wkt2);
    }

    #[test]
    fn test_extract_epsg_wkt2() {
        let wkt = r#"GEOGCRS["WGS 84",DATUM["WGS 1984"],ID["EPSG",4326]]"#;
        let epsg = WktParser::extract_epsg(wkt);
        assert_eq!(epsg, Some(4326));
    }
}