proj-wkt 0.7.0

WKT and PROJ string parser for proj-core CRS definitions
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
use crate::semantics::{
    approx_eq, linear_unit_from_meters_per_unit, normalize_key, projection_parameter_unit_kind,
    radians_to_degrees_factor, resolve_structured_datum,
    validate_supported_geographic_or_ellipsoidal_height_semantics,
    validate_supported_geographic_semantics, validate_supported_projected_semantics,
    validate_supported_vertical_coordinate_system, validate_vertical_unit_matches_authority,
    AxisDirection, CoordinateSystemSpec, DatumAliasScope, GeographicCoordinateSystemKind,
    ProjectionParameterUnitKind, StructuredEllipsoid,
};
use crate::{ParseError, Result};
use proj_core::{
    CompoundCrsDef, CrsDef, GeographicCrsDef, HorizontalCrsDef, LinearUnit, ProjectedCrsDef,
    ProjectionMethod, VerticalCrsDef,
};
use std::collections::HashMap;

/// Parse a WKT CRS string.
///
/// Strategy:
/// 1. Extract a top-level AUTHORITY["EPSG","XXXX"] or ID["EPSG",XXXX] if present
///    → look up in registry
/// 2. Otherwise, extract projection parameters from the WKT structure
pub(crate) fn parse_wkt(s: &str) -> Result<CrsDef> {
    let s = s.trim();
    let top_level_epsg = extract_top_level_epsg(s);
    let parsed = parse_wkt_structure(s)?;

    if let Some(epsg) = top_level_epsg {
        return canonicalize_authoritative_crs(parsed, epsg, "WKT");
    }

    Ok(parsed)
}

/// Extract a top-level EPSG code from AUTHORITY[...] or ID[...].
fn extract_top_level_epsg(s: &str) -> Option<u32> {
    let root_start = s.find('[')?;
    let mut depth = 1usize;
    let mut i = root_start + 1;
    let bytes = s.as_bytes();
    let mut in_string = false;

    while i < bytes.len() && depth > 0 {
        match bytes[i] {
            b'"' => {
                if in_string && bytes.get(i + 1) == Some(&b'"') {
                    i += 2;
                } else {
                    in_string = !in_string;
                    i += 1;
                }
            }
            _ if in_string => i += 1,
            b'[' => {
                depth += 1;
                i += 1;
            }
            b']' => {
                depth -= 1;
                i += 1;
            }
            _ if depth == 1 => {
                if let Some((name, inner, next)) = parse_wkt_element(s, i) {
                    if name.eq_ignore_ascii_case("AUTHORITY") || name.eq_ignore_ascii_case("ID") {
                        if let Some(epsg) = parse_epsg_element(inner) {
                            return Some(epsg);
                        }
                    }
                    i = next;
                } else {
                    i += 1;
                }
            }
            _ => i += 1,
        }
    }

    None
}

fn parse_wkt_element(s: &str, start: usize) -> Option<(&str, &str, usize)> {
    let bytes = s.as_bytes();
    let first = *bytes.get(start)?;
    if !first.is_ascii_alphabetic() {
        return None;
    }

    let mut name_end = start + 1;
    while let Some(byte) = bytes.get(name_end) {
        if byte.is_ascii_alphanumeric() || *byte == b'_' {
            name_end += 1;
        } else {
            break;
        }
    }

    let mut bracket_start = name_end;
    while let Some(byte) = bytes.get(bracket_start) {
        if byte.is_ascii_whitespace() {
            bracket_start += 1;
        } else {
            break;
        }
    }
    if bytes.get(bracket_start) != Some(&b'[') {
        return None;
    }

    let mut depth = 1usize;
    let mut i = bracket_start + 1;
    let mut in_string = false;
    while i < bytes.len() {
        match bytes[i] {
            b'"' => {
                if in_string && bytes.get(i + 1) == Some(&b'"') {
                    i += 2;
                } else {
                    in_string = !in_string;
                    i += 1;
                }
            }
            _ if in_string => i += 1,
            b'[' => {
                depth += 1;
                i += 1;
            }
            b']' => {
                depth -= 1;
                i += 1;
                if depth == 0 {
                    let name = &s[start..name_end];
                    let inner = &s[bracket_start + 1..i - 1];
                    return Some((name, inner, i));
                }
            }
            _ => i += 1,
        }
    }

    None
}

fn parse_epsg_element(inner: &str) -> Option<u32> {
    let (authority, code) = first_two_fields(inner)?;
    if !trim_wkt_token(authority).eq_ignore_ascii_case("EPSG") {
        return None;
    }
    trim_wkt_token(code).parse().ok()
}

fn first_two_fields(s: &str) -> Option<(&str, &str)> {
    let mut depth = 0usize;
    let mut in_string = false;
    let bytes = s.as_bytes();

    for (idx, byte) in bytes.iter().enumerate() {
        match *byte {
            b'"' => {
                if in_string && bytes.get(idx + 1) == Some(&b'"') {
                    continue;
                }
                in_string = !in_string;
            }
            _ if in_string => {}
            b'[' => depth += 1,
            b']' => depth = depth.saturating_sub(1),
            b',' if depth == 0 => {
                return Some((&s[..idx], &s[idx + 1..]));
            }
            _ => {}
        }
    }

    None
}

fn trim_wkt_token(token: &str) -> &str {
    token.trim().trim_matches('"')
}

/// Attempt to parse WKT structure to extract projection parameters.
fn parse_wkt_structure(s: &str) -> Result<CrsDef> {
    let Some((root_name, _, _)) = parse_wkt_element(s, 0) else {
        return Err(ParseError::Parse(format!(
            "unrecognized WKT root element: {:.40}",
            s
        )));
    };

    if root_name.eq_ignore_ascii_case("GEOGCS")
        || root_name.eq_ignore_ascii_case("GEODCRS")
        || root_name.eq_ignore_ascii_case("GEOGCRS")
    {
        return parse_wkt_geographic(s);
    }

    if root_name.eq_ignore_ascii_case("PROJCS") || root_name.eq_ignore_ascii_case("PROJCRS") {
        return parse_wkt_projected(s);
    }

    if root_name.eq_ignore_ascii_case("COMPD_CS") || root_name.eq_ignore_ascii_case("COMPOUNDCRS") {
        return parse_wkt_compound(s);
    }

    if root_name.eq_ignore_ascii_case("VERT_CS")
        || root_name.eq_ignore_ascii_case("VERTCRS")
        || root_name.eq_ignore_ascii_case("VERTICALCRS")
    {
        return Err(ParseError::UnsupportedSemantics(
            "standalone vertical CRS definitions are not supported by the horizontal transform API; use a compound CRS with an identical vertical component on both sides".into(),
        ));
    }

    Err(ParseError::Parse(format!(
        "unrecognized WKT root element: {:.40}",
        s
    )))
}

fn parse_wkt_geographic(s: &str) -> Result<CrsDef> {
    let root_inner = root_inner(s)
        .ok_or_else(|| ParseError::Parse(format!("unrecognized WKT root element: {:.40}", s)))?;
    let coordinate_system = extract_coordinate_system(root_inner);
    let angle_unit_to_degree = extract_geographic_angle_unit_to_degree(
        root_inner,
        "WKT geographic CRS",
        &coordinate_system,
    )?;
    let prime_meridian_degrees =
        extract_prime_meridian_degrees(root_inner, angle_unit_to_degree.unwrap_or(1.0));
    let coordinate_system_kind = validate_supported_geographic_or_ellipsoidal_height_semantics(
        "WKT geographic CRS",
        angle_unit_to_degree,
        prime_meridian_degrees,
        &coordinate_system,
    )?;

    let datum = infer_datum_from_geographic_inner(root_inner)?;
    let horizontal = GeographicCrsDef::new(0, datum.clone(), "");

    match coordinate_system_kind {
        GeographicCoordinateSystemKind::TwoDimensional => Ok(CrsDef::Geographic(horizontal)),
        GeographicCoordinateSystemKind::ThreeDimensionalEllipsoidalHeight => {
            let vertical = VerticalCrsDef::ellipsoidal_height(
                0,
                datum,
                extract_ellipsoidal_height_linear_unit(root_inner)
                    .unwrap_or_else(LinearUnit::metre),
                "",
            );
            Ok(CrsDef::Compound(Box::new(CompoundCrsDef::new(
                0,
                HorizontalCrsDef::Geographic(horizontal),
                vertical,
                "",
            ))))
        }
    }
}

fn parse_wkt_projected(s: &str) -> Result<CrsDef> {
    let root_inner = root_inner(s)
        .ok_or_else(|| ParseError::Parse(format!("unrecognized WKT root element: {:.40}", s)))?;
    // WKT1 uses PROJECTION["name"], WKT2 uses METHOD["name"].
    let proj_name = extract_wkt_value_case_insensitive(s, "PROJECTION")
        .or_else(|| extract_wkt_value_case_insensitive(s, "METHOD"));
    let normalized_method = proj_name.as_deref().map(normalize_key).ok_or_else(|| {
        ParseError::Parse("WKT projected CRS is missing a projection method".into())
    })?;

    let coordinate_system = extract_coordinate_system(root_inner);
    let projected_linear_unit = extract_projected_linear_unit(root_inner, &coordinate_system)?
        .unwrap_or_else(LinearUnit::metre);
    validate_supported_projected_semantics("WKT projected CRS", &coordinate_system)?;

    let base_geographic_inner =
        find_top_level_element_inner(root_inner, &["BASEGEOGCRS", "GEOGCRS", "GEODCRS", "GEOGCS"])
            .ok_or_else(|| {
                ParseError::Parse("WKT projected CRS is missing a base geographic CRS".into())
            })?;
    let base_coordinate_system = extract_coordinate_system(base_geographic_inner);
    let base_angle_unit_to_degree = extract_geographic_angle_unit_to_degree(
        base_geographic_inner,
        "WKT projected base geographic CRS",
        &base_coordinate_system,
    )?
    .unwrap_or(1.0);
    validate_supported_geographic_semantics(
        "WKT projected base geographic CRS",
        Some(base_angle_unit_to_degree),
        extract_prime_meridian_degrees(base_geographic_inner, base_angle_unit_to_degree),
        &base_coordinate_system,
    )?;
    let params = parse_wkt_parameters(s, projected_linear_unit, base_angle_unit_to_degree)?;

    // Extract common parameters
    let lon0 = first_param(
        &params,
        &[
            "centralmeridian",
            "longitudeofcenter",
            "longitudeofcentre",
            "longitudeofprojectioncenter",
            "longitudeofprojectioncentre",
            "longitudeofnaturalorigin",
            "longitudeoffalseorigin",
        ],
    )
    .unwrap_or(0.0);
    let lat0 = first_param(
        &params,
        &[
            "latitudeoforigin",
            "latitudeofcenter",
            "latitudeofcentre",
            "latitudeofprojectioncenter",
            "latitudeofprojectioncentre",
            "latitudeofnaturalorigin",
            "latitudeoffalseorigin",
        ],
    )
    .unwrap_or(0.0);
    let k0 = first_param(
        &params,
        &[
            "scalefactor",
            "scalefactoratnaturalorigin",
            "scalefactoratprojectionorigin",
            "scalefactoratprojectioncenter",
            "scalefactoratprojectioncentre",
        ],
    )
    .unwrap_or(1.0);
    let fe = first_param(
        &params,
        &[
            "falseeasting",
            "eastingatprojectioncenter",
            "eastingatprojectioncentre",
        ],
    )
    .unwrap_or(0.0);
    let fn_ = first_param(
        &params,
        &[
            "falsenorthing",
            "northingatprojectioncenter",
            "northingatprojectioncentre",
        ],
    )
    .unwrap_or(0.0);

    let datum = infer_datum_from_geographic_inner(base_geographic_inner)?;

    let method = match normalized_method.as_str() {
        "transversemercator" => ProjectionMethod::TransverseMercator {
            lon0,
            lat0,
            k0,
            false_easting: fe,
            false_northing: fn_,
        },
        name if name.starts_with("mercator") => ProjectionMethod::Mercator {
            lon0,
            lat_ts: first_param(
                &params,
                &[
                    "standardparallel1",
                    "latitudeof1ststandardparallel",
                    "latitudeofstandardparallel",
                ],
            )
            .unwrap_or(0.0),
            k0,
            false_easting: fe,
            false_northing: fn_,
        },
        "lambertconformalconic1sp" | "lambertconformalconic2sp" | "lambertconformalconic" => {
            ProjectionMethod::LambertConformalConic {
                lon0,
                lat0,
                lat1: first_param(
                    &params,
                    &["standardparallel1", "latitudeof1ststandardparallel"],
                )
                .unwrap_or(lat0),
                lat2: first_param(
                    &params,
                    &["standardparallel2", "latitudeof2ndstandardparallel"],
                )
                .unwrap_or(lat0),
                false_easting: fe,
                false_northing: fn_,
            }
        }
        "albersequalareaconic" | "albersequalarea" => ProjectionMethod::AlbersEqualArea {
            lon0,
            lat0,
            lat1: first_param(
                &params,
                &["standardparallel1", "latitudeof1ststandardparallel"],
            )
            .unwrap_or(lat0),
            lat2: first_param(
                &params,
                &["standardparallel2", "latitudeof2ndstandardparallel"],
            )
            .unwrap_or(lat0),
            false_easting: fe,
            false_northing: fn_,
        },
        "lambertazimuthalequalarea" | "lambertazimuthalequalareaellipsoidal" => {
            ProjectionMethod::LambertAzimuthalEqualArea {
                lon0,
                lat0,
                false_easting: fe,
                false_northing: fn_,
            }
        }
        "lambertazimuthalequalareaspherical" => {
            ProjectionMethod::LambertAzimuthalEqualAreaSpherical {
                lon0,
                lat0,
                false_easting: fe,
                false_northing: fn_,
            }
        }
        "obliquestereographic" | "doublestereographic" | "stereographic" => {
            ProjectionMethod::ObliqueStereographic {
                lon0,
                lat0,
                k0,
                false_easting: fe,
                false_northing: fn_,
            }
        }
        "hotineobliquemercator"
        | "hotineobliquemercatorvarianta"
        | "hotineobliquemercatorvariantb"
        | "obliquemercator"
        | "rectifiedskeworthomorphic" => {
            let variant_b = normalized_method == "hotineobliquemercatorvariantb"
                || params.contains_key("eastingatprojectioncenter")
                || params.contains_key("eastingatprojectioncentre")
                || params.contains_key("northingatprojectioncenter")
                || params.contains_key("northingatprojectioncentre");
            let azimuth = first_param(
                &params,
                &[
                    "azimuth",
                    "azimuthinitialline",
                    "azimuthofinitialline",
                    "azimuthatprojectioncenter",
                    "azimuthatprojectioncentre",
                ],
            )
            .unwrap_or(0.0);
            let rectified_grid_angle = first_param(
                &params,
                &["rectifiedgridangle", "anglefromrectifiedtoskewgrid"],
            )
            .unwrap_or(azimuth);
            ProjectionMethod::HotineObliqueMercator {
                latc: lat0,
                lonc: lon0,
                azimuth,
                rectified_grid_angle,
                k0,
                false_easting: fe,
                false_northing: fn_,
                variant_b,
            }
        }
        "cassinisoldner" | "cassini" => ProjectionMethod::CassiniSoldner {
            lon0,
            lat0,
            false_easting: fe,
            false_northing: fn_,
        },
        "polarstereographicvarianta" | "polarstereographicvariantb" | "polarstereographic" => {
            ProjectionMethod::PolarStereographic {
                lon0,
                lat_ts: first_param(
                    &params,
                    &[
                        "standardparallel",
                        "latitudeofstandardparallel",
                        "latitudeof1ststandardparallel",
                    ],
                )
                .unwrap_or(lat0),
                k0,
                false_easting: fe,
                false_northing: fn_,
            }
        }
        "equidistantcylindrical" | "platecarree" => ProjectionMethod::EquidistantCylindrical {
            lon0,
            lat_ts: first_param(
                &params,
                &[
                    "standardparallel1",
                    "latitudeof1ststandardparallel",
                    "latitudeofstandardparallel",
                ],
            )
            .unwrap_or(0.0),
            false_easting: fe,
            false_northing: fn_,
        },
        _ => {
            return Err(ParseError::Parse(format!(
                "unsupported WKT projection: {}",
                proj_name.as_deref().unwrap_or("(none)")
            )));
        }
    };

    Ok(CrsDef::Projected(ProjectedCrsDef::new(
        0,
        datum,
        method,
        projected_linear_unit,
        "",
    )))
}

fn parse_wkt_compound(s: &str) -> Result<CrsDef> {
    let root_inner = root_inner(s)
        .ok_or_else(|| ParseError::Parse(format!("unrecognized WKT root element: {:.40}", s)))?;
    let mut horizontal = None;
    let mut vertical = None;

    for_each_top_level_element(root_inner, |name, element_inner| {
        if horizontal.is_none()
            && (name.eq_ignore_ascii_case("GEOGCS")
                || name.eq_ignore_ascii_case("GEODCRS")
                || name.eq_ignore_ascii_case("GEOGCRS")
                || name.eq_ignore_ascii_case("PROJCS")
                || name.eq_ignore_ascii_case("PROJCRS"))
        {
            horizontal = Some(parse_wkt_structure(&format!("{name}[{element_inner}]")));
            return;
        }

        if vertical.is_none()
            && (name.eq_ignore_ascii_case("VERT_CS")
                || name.eq_ignore_ascii_case("VERTCRS")
                || name.eq_ignore_ascii_case("VERTICALCRS"))
        {
            vertical = Some(parse_wkt_vertical(element_inner));
        }
    });

    let horizontal = horizontal.ok_or_else(|| {
        ParseError::Parse("WKT compound CRS is missing a horizontal CRS".into())
    })??;
    if horizontal.vertical_crs().is_some() {
        return Err(ParseError::UnsupportedSemantics(
            "WKT compound CRS cannot use a 3D horizontal CRS as its horizontal component".into(),
        ));
    }

    let vertical = vertical
        .ok_or_else(|| ParseError::Parse("WKT compound CRS is missing a vertical CRS".into()))??;
    let compound = CompoundCrsDef::from_crs_def(0, horizontal, vertical, "")?;
    Ok(CrsDef::Compound(Box::new(compound)))
}

fn parse_wkt_vertical(inner: &str) -> Result<VerticalCrsDef> {
    validate_supported_vertical_coordinate_system(
        "WKT vertical CRS",
        &extract_coordinate_system(inner),
    )?;
    let linear_unit = extract_vertical_crs_linear_unit(inner).unwrap_or_else(LinearUnit::metre);
    let epsg = extract_top_level_epsg_from_inner(inner).unwrap_or(0);
    if let Some(canonical) = proj_core::lookup_vertical_epsg(epsg) {
        validate_vertical_unit_matches_authority("WKT vertical CRS", linear_unit, &canonical)?;
        return Ok(canonical);
    }

    let datum_inner =
        find_top_level_element_inner(inner, &["VERT_DATUM", "VERTICALDATUM", "VDATUM", "VRF"])
            .ok_or_else(|| {
                ParseError::Parse("WKT vertical CRS is missing a vertical datum".into())
            })?;

    let vertical_datum_epsg = extract_top_level_epsg_from_inner(datum_inner).ok_or_else(|| {
        ParseError::UnsupportedSemantics(
            "WKT gravity-related vertical CRS requires a vertical datum EPSG identifier".into(),
        )
    })?;

    Ok(VerticalCrsDef::gravity_related_height(
        epsg,
        vertical_datum_epsg,
        linear_unit,
        "",
    )?)
}

fn infer_datum_from_geographic_inner(inner: &str) -> Result<proj_core::Datum> {
    let datum_inner = find_top_level_element_inner(
        inner,
        &["DATUM", "GEODETICDATUM", "DATUMENSEMBLE", "ENSEMBLE"],
    )
    .ok_or_else(|| ParseError::Parse("WKT geographic CRS is missing a datum definition".into()))?;

    if let Some(epsg) = extract_top_level_epsg_from_inner(datum_inner) {
        return proj_core::lookup_datum_epsg(epsg)
            .ok_or_else(|| ParseError::Parse(format!("unsupported WKT datum EPSG:{epsg}")));
    }

    let fields = split_top_level_fields(datum_inner);
    let datum_name = fields
        .first()
        .map(|field| normalize_key(trim_wkt_token(field)))
        .ok_or_else(|| ParseError::Parse("WKT datum is missing a name".into()))?;
    let ellipsoid = parse_structured_ellipsoid(datum_inner)
        .ok_or_else(|| ParseError::Parse("WKT datum is missing a supported ellipsoid".into()))?;

    resolve_structured_datum(DatumAliasScope::Wkt, &datum_name, &ellipsoid)
        .ok_or_else(|| ParseError::Parse("unsupported or unrecognized WKT datum".into()))
}

fn canonicalize_authoritative_crs(parsed: CrsDef, epsg: u32, format: &str) -> Result<CrsDef> {
    let registry = proj_core::lookup_epsg(epsg)
        .ok_or_else(|| ParseError::Parse(format!("unsupported EPSG code in {format}: {epsg}")))?;
    if parsed.semantically_equivalent(&registry) {
        Ok(registry)
    } else {
        Err(ParseError::UnsupportedSemantics(format!(
            "{format} definition tagged as EPSG:{epsg} does not match the embedded EPSG semantics"
        )))
    }
}

fn parse_structured_ellipsoid(inner: &str) -> Option<StructuredEllipsoid> {
    let ellipsoid_inner = find_top_level_element_inner(inner, &["SPHEROID", "ELLIPSOID"])?;
    let fields = split_top_level_fields(ellipsoid_inner);
    let name = normalize_key(trim_wkt_token(fields.first()?));
    let semi_major_axis = fields.get(1)?.trim().parse().ok()?;
    let inverse_flattening = fields.get(2)?.trim().parse().ok()?;
    Some(StructuredEllipsoid {
        epsg: extract_top_level_epsg_from_inner(ellipsoid_inner),
        name,
        semi_major_axis,
        inverse_flattening,
    })
}

fn extract_top_level_epsg_from_inner(inner: &str) -> Option<u32> {
    let mut found = None;
    for_each_top_level_element(inner, |name, element_inner| {
        if found.is_none()
            && (name.eq_ignore_ascii_case("AUTHORITY") || name.eq_ignore_ascii_case("ID"))
        {
            found = parse_epsg_element(element_inner);
        }
    });
    found
}

/// Extract a quoted value like PROJECTION["Transverse_Mercator"].
fn extract_wkt_value_case_insensitive(s: &str, key: &str) -> Option<String> {
    let marker = format!("{key}[\"");
    let pos = find_ascii_case_insensitive(s, &marker)?;
    let start = pos + marker.len();
    let rest = &s[start..];
    let end = rest.find('"')?;
    Some(rest[..end].to_string())
}

fn parse_wkt_parameters(
    s: &str,
    projected_linear_unit: LinearUnit,
    base_angle_unit_to_degree: f64,
) -> Result<HashMap<String, f64>> {
    let mut params = HashMap::new();
    let mut search_start = 0usize;

    while let Some(rel) = find_ascii_case_insensitive(&s[search_start..], "PARAMETER[") {
        let start = search_start + rel;
        if let Some((name, inner, next)) = parse_wkt_element(s, start) {
            if name.eq_ignore_ascii_case("PARAMETER") {
                let (key, value) = parse_parameter_element(
                    inner,
                    projected_linear_unit,
                    base_angle_unit_to_degree,
                )?;
                params.insert(key, value);
                search_start = next;
                continue;
            }
        }
        search_start = start + "PARAMETER[".len();
    }

    Ok(params)
}

fn parse_parameter_element(
    inner: &str,
    projected_linear_unit: LinearUnit,
    base_angle_unit_to_degree: f64,
) -> Result<(String, f64)> {
    let fields = split_top_level_fields(inner);
    let name = fields
        .first()
        .map(|field| trim_wkt_token(field))
        .unwrap_or("");
    if name.is_empty() {
        return Err(ParseError::Parse(
            "WKT projection parameter is missing a name".into(),
        ));
    }
    if fields.len() < 2 {
        return Err(ParseError::Parse(format!(
            "WKT projection parameter `{name}` is missing a numeric value"
        )));
    }

    let normalized_name = normalize_key(name);
    let value = parse_wkt_projection_parameter_number(name, fields[1].trim())?;
    let unit_kind = projection_parameter_unit_kind(&normalized_name);

    let mut nested_factor = None;
    for field in fields.iter().skip(2) {
        let field = field.trim();
        let Some((unit_name, unit_inner, _)) = parse_wkt_element(field, 0) else {
            continue;
        };
        nested_factor = match unit_name.to_ascii_uppercase().as_str() {
            "ANGLEUNIT" => Some(radians_to_degrees_factor(parse_wkt_parameter_unit_factor(
                name, unit_inner,
            )?)),
            "LENGTHUNIT" | "UNIT" | "SCALEUNIT" => {
                Some(parse_wkt_parameter_unit_factor(name, unit_inner)?)
            }
            _ => None,
        };
        if nested_factor.is_some() {
            break;
        }
    }

    let default_factor = match unit_kind {
        ProjectionParameterUnitKind::Angle => base_angle_unit_to_degree,
        ProjectionParameterUnitKind::Length => projected_linear_unit.meters_per_unit(),
        ProjectionParameterUnitKind::Scale | ProjectionParameterUnitKind::Other => 1.0,
    };

    Ok((
        normalized_name,
        value * nested_factor.unwrap_or(default_factor),
    ))
}

fn parse_wkt_projection_parameter_number(name: &str, raw: &str) -> Result<f64> {
    let value = raw.parse::<f64>().map_err(|_| {
        ParseError::Parse(format!(
            "invalid WKT projection parameter `{name}` value: {raw}"
        ))
    })?;
    if !value.is_finite() {
        return Err(ParseError::Parse(format!(
            "WKT projection parameter `{name}` value must be finite"
        )));
    }
    Ok(value)
}

fn parse_wkt_parameter_unit_factor(parameter_name: &str, inner: &str) -> Result<f64> {
    let factor = parse_unit_factor(inner).ok_or_else(|| {
        ParseError::Parse(format!(
            "invalid WKT projection parameter `{parameter_name}` unit factor"
        ))
    })?;
    if !factor.is_finite() {
        return Err(ParseError::Parse(format!(
            "WKT projection parameter `{parameter_name}` unit factor must be finite"
        )));
    }
    Ok(factor)
}

fn split_top_level_fields(s: &str) -> Vec<&str> {
    let mut fields = Vec::new();
    let mut field_start = 0usize;
    let mut depth = 0usize;
    let mut in_string = false;
    let bytes = s.as_bytes();
    let mut i = 0usize;

    while i < bytes.len() {
        match bytes[i] {
            b'"' => {
                if in_string && bytes.get(i + 1) == Some(&b'"') {
                    i += 2;
                    continue;
                }
                in_string = !in_string;
            }
            _ if in_string => {}
            b'[' => depth += 1,
            b']' => depth = depth.saturating_sub(1),
            b',' if depth == 0 => {
                fields.push(s[field_start..i].trim());
                field_start = i + 1;
            }
            _ => {}
        }
        i += 1;
    }

    fields.push(s[field_start..].trim());
    fields
}

fn root_inner(s: &str) -> Option<&str> {
    parse_wkt_element(s, 0).map(|(_, inner, _)| inner)
}

fn extract_projected_linear_unit(
    inner: &str,
    coordinate_system: &CoordinateSystemSpec,
) -> Result<Option<LinearUnit>> {
    let top_level_linear_unit = extract_top_level_length_unit(inner, true);
    let axis_linear_unit = coordinate_system_linear_unit("WKT projected CRS", coordinate_system)?;
    if let (Some(top_level_linear_unit), Some(axis_linear_unit)) =
        (top_level_linear_unit, axis_linear_unit)
    {
        if !approx_eq(
            top_level_linear_unit.meters_per_unit(),
            axis_linear_unit.meters_per_unit(),
        ) {
            return Err(ParseError::UnsupportedSemantics(
                "WKT projected CRS declares conflicting projected linear units".into(),
            ));
        }
    }
    Ok(top_level_linear_unit.or(axis_linear_unit))
}

fn extract_top_level_angle_unit_to_degree(inner: &str) -> Option<f64> {
    let mut factor = None;
    for_each_top_level_element(inner, |unit_name, unit_inner| {
        if unit_name.eq_ignore_ascii_case("UNIT") || unit_name.eq_ignore_ascii_case("ANGLEUNIT") {
            factor = parse_unit_factor(unit_inner).map(radians_to_degrees_factor);
        }
    });
    factor
}

fn extract_geographic_angle_unit_to_degree(
    inner: &str,
    context: &str,
    coordinate_system: &CoordinateSystemSpec,
) -> Result<Option<f64>> {
    let top_level_angle_unit_to_degree = extract_top_level_angle_unit_to_degree(inner);
    let axis_angle_unit_to_degree =
        coordinate_system_angle_unit_to_degree(context, coordinate_system)?;
    if let (Some(top_level_angle_unit_to_degree), Some(axis_angle_unit_to_degree)) =
        (top_level_angle_unit_to_degree, axis_angle_unit_to_degree)
    {
        if !approx_eq(top_level_angle_unit_to_degree, axis_angle_unit_to_degree) {
            return Err(ParseError::UnsupportedSemantics(format!(
                "{context} declares conflicting angular units"
            )));
        }
    }
    Ok(top_level_angle_unit_to_degree.or(axis_angle_unit_to_degree))
}

fn extract_prime_meridian_degrees(inner: &str, default_angle_unit_to_degree: f64) -> Option<f64> {
    let mut prime_meridian = None;
    for_each_top_level_element(inner, |name, element_inner| {
        if !name.eq_ignore_ascii_case("PRIMEM") {
            return;
        }

        let fields = split_top_level_fields(element_inner);
        let Some(value) = fields
            .get(1)
            .and_then(|field| field.trim().parse::<f64>().ok())
        else {
            return;
        };

        let factor = fields
            .iter()
            .skip(2)
            .find_map(|field| {
                let field = field.trim();
                let (unit_name, unit_inner, _) = parse_wkt_element(field, 0)?;
                if unit_name.eq_ignore_ascii_case("UNIT")
                    || unit_name.eq_ignore_ascii_case("ANGLEUNIT")
                {
                    parse_unit_factor(unit_inner).map(radians_to_degrees_factor)
                } else {
                    None
                }
            })
            .unwrap_or(default_angle_unit_to_degree);

        prime_meridian = Some(value * factor);
    });
    prime_meridian
}

fn extract_coordinate_system(inner: &str) -> CoordinateSystemSpec {
    let mut coordinate_system = CoordinateSystemSpec::default();
    for_each_top_level_element(inner, |name, element_inner| {
        if name.eq_ignore_ascii_case("CS") {
            let fields = split_top_level_fields(element_inner);
            coordinate_system.subtype = fields
                .first()
                .map(|field| trim_wkt_token(field).to_string());
            coordinate_system.dimension = fields.get(1).and_then(|field| field.trim().parse().ok());
            return;
        }

        if name.eq_ignore_ascii_case("AXIS") {
            let axis_direction = parse_axis_direction(element_inner);
            coordinate_system.axes.push(axis_direction);
            coordinate_system
                .axis_linear_units
                .push(axis_linear_unit(element_inner));
            coordinate_system
                .axis_angle_unit_to_degree
                .push(axis_angle_unit_to_degree(element_inner));
        }
    });
    coordinate_system
}

fn coordinate_system_linear_unit(
    context: &str,
    coordinate_system: &CoordinateSystemSpec,
) -> Result<Option<LinearUnit>> {
    let mut linear_unit: Option<LinearUnit> = None;
    for axis_unit in coordinate_system
        .axis_linear_units
        .iter()
        .flatten()
        .copied()
    {
        if let Some(existing_linear_unit) = linear_unit {
            if !approx_eq(
                existing_linear_unit.meters_per_unit(),
                axis_unit.meters_per_unit(),
            ) {
                return Err(ParseError::UnsupportedSemantics(format!(
                    "{context} uses inconsistent projected axis units"
                )));
            }
        } else {
            linear_unit = Some(axis_unit);
        }
    }

    Ok(linear_unit)
}

fn coordinate_system_angle_unit_to_degree(
    context: &str,
    coordinate_system: &CoordinateSystemSpec,
) -> Result<Option<f64>> {
    let mut angle_unit_to_degree = None;
    for axis_angle_unit_to_degree in coordinate_system
        .axis_angle_unit_to_degree
        .iter()
        .flatten()
        .copied()
    {
        if let Some(existing_angle_unit_to_degree) = angle_unit_to_degree {
            if !approx_eq(existing_angle_unit_to_degree, axis_angle_unit_to_degree) {
                return Err(ParseError::UnsupportedSemantics(format!(
                    "{context} uses inconsistent angular axis units"
                )));
            }
        } else {
            angle_unit_to_degree = Some(axis_angle_unit_to_degree);
        }
    }

    Ok(angle_unit_to_degree)
}

fn parse_axis_direction(inner: &str) -> AxisDirection {
    split_top_level_fields(inner)
        .get(1)
        .map(|field| AxisDirection::from_str(trim_wkt_token(field)))
        .unwrap_or(AxisDirection::Other)
}

fn extract_vertical_axis_linear_unit(inner: &str) -> Option<LinearUnit> {
    let mut linear_unit = None;
    for_each_top_level_element(inner, |name, element_inner| {
        if linear_unit.is_some() || !name.eq_ignore_ascii_case("AXIS") {
            return;
        }
        if parse_axis_direction(element_inner) != AxisDirection::Up {
            return;
        }
        linear_unit = axis_linear_unit(element_inner);
    });
    linear_unit
}

fn extract_ellipsoidal_height_linear_unit(inner: &str) -> Option<LinearUnit> {
    extract_vertical_axis_linear_unit(inner).or_else(|| extract_top_level_length_unit(inner, false))
}

fn extract_vertical_crs_linear_unit(inner: &str) -> Option<LinearUnit> {
    extract_vertical_axis_linear_unit(inner).or_else(|| extract_top_level_length_unit(inner, true))
}

fn extract_top_level_length_unit(inner: &str, include_legacy_unit: bool) -> Option<LinearUnit> {
    let mut linear_unit = None;
    for_each_top_level_element(inner, |name, element_inner| {
        if linear_unit.is_some() {
            return;
        }
        if name.eq_ignore_ascii_case("LENGTHUNIT")
            || (include_legacy_unit && name.eq_ignore_ascii_case("UNIT"))
        {
            linear_unit =
                parse_unit_factor(element_inner).and_then(linear_unit_from_meters_per_unit);
        }
    });
    linear_unit
}

fn axis_linear_unit(axis_inner: &str) -> Option<LinearUnit> {
    split_top_level_fields(axis_inner)
        .iter()
        .skip(2)
        .find_map(|field| {
            let (unit_name, unit_inner, _) = parse_wkt_element(field.trim(), 0)?;
            if unit_name.eq_ignore_ascii_case("LENGTHUNIT")
                || unit_name.eq_ignore_ascii_case("UNIT")
            {
                parse_unit_factor(unit_inner).and_then(linear_unit_from_meters_per_unit)
            } else {
                None
            }
        })
}

fn axis_angle_unit_to_degree(axis_inner: &str) -> Option<f64> {
    split_top_level_fields(axis_inner)
        .iter()
        .skip(2)
        .find_map(|field| {
            let (unit_name, unit_inner, _) = parse_wkt_element(field.trim(), 0)?;
            if unit_name.eq_ignore_ascii_case("ANGLEUNIT") || unit_name.eq_ignore_ascii_case("UNIT")
            {
                parse_unit_factor(unit_inner).map(radians_to_degrees_factor)
            } else {
                None
            }
        })
}

fn find_top_level_element_inner<'a>(inner: &'a str, names: &[&str]) -> Option<&'a str> {
    let mut found = None;
    for_each_top_level_element(inner, |name, element_inner| {
        if found.is_none()
            && names
                .iter()
                .any(|expected| name.eq_ignore_ascii_case(expected))
        {
            found = Some(element_inner);
        }
    });
    found
}

fn for_each_top_level_element<'a, F>(inner: &'a str, mut f: F)
where
    F: FnMut(&'a str, &'a str),
{
    let mut i = 0usize;
    let bytes = inner.as_bytes();
    let mut depth = 0usize;
    let mut in_string = false;

    while i < bytes.len() {
        match bytes[i] {
            b'"' => {
                if in_string && bytes.get(i + 1) == Some(&b'"') {
                    i += 2;
                    continue;
                }
                in_string = !in_string;
                i += 1;
            }
            _ if in_string => i += 1,
            b'[' => {
                depth += 1;
                i += 1;
            }
            b']' => {
                depth = depth.saturating_sub(1);
                i += 1;
            }
            _ if depth == 0 => {
                if let Some((name, element_inner, next)) = parse_wkt_element(inner, i) {
                    f(name, element_inner);
                    i = next;
                } else {
                    i += 1;
                }
            }
            _ => i += 1,
        }
    }
}

fn parse_unit_factor(inner: &str) -> Option<f64> {
    let fields = split_top_level_fields(inner);
    fields.get(1)?.trim().parse::<f64>().ok()
}

fn first_param(params: &HashMap<String, f64>, names: &[&str]) -> Option<f64> {
    names
        .iter()
        .find_map(|name| params.get(&normalize_key(name)).copied())
}

fn find_ascii_case_insensitive(haystack: &str, needle: &str) -> Option<usize> {
    if needle.is_empty() {
        return Some(0);
    }

    haystack.char_indices().find_map(|(idx, _)| {
        haystack
            .get(idx..idx + needle.len())
            .filter(|slice| slice.eq_ignore_ascii_case(needle))
            .map(|_| idx)
    })
}

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

    const US_FOOT_TO_METER: f64 = 0.3048006096012192;

    #[test]
    fn extract_top_level_epsg_from_wkt() {
        let wkt = r#"GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],AUTHORITY["EPSG","4326"]]"#;
        assert_eq!(extract_top_level_epsg(wkt), Some(4326));
    }

    #[test]
    fn parse_wkt_geogcs_with_authority() {
        let wkt = r#"GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],AUTHORITY["EPSG","4326"]]"#;
        let crs = parse_wkt(wkt).unwrap();
        assert!(crs.is_geographic());
        assert_eq!(crs.epsg(), 4326);
    }

    #[test]
    fn parse_wkt_projcs_utm() {
        let wkt = r#"PROJCS["WGS 84 / UTM zone 18N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-75],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],AUTHORITY["EPSG","32618"]]"#;
        let crs = parse_wkt(wkt).unwrap();
        assert!(crs.is_projected());
        assert_eq!(crs.epsg(), 32618);
    }

    #[test]
    fn parse_wkt_without_authority() {
        let wkt = r#"GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]]"#;
        let crs = parse_wkt(wkt).unwrap();
        assert!(crs.is_geographic());
    }

    #[test]
    fn parse_wkt2_geographic_3d_as_compound_ellipsoidal_height() {
        let wkt = r#"GEODCRS["WGS 84 3D",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],CS[ellipsoidal,3],AXIS["longitude",east,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["latitude",north,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],AXIS["ellipsoidal height",up,ORDER[3],LENGTHUNIT["metre",1]]]"#;
        let crs = parse_wkt(wkt).unwrap();
        assert!(crs.is_compound());
        assert!(crs.is_geographic());
        assert!(crs.vertical_crs().is_some());
    }

    #[test]
    fn parse_wkt_compound_with_vertical_crs() {
        let wkt = r#"COMPOUNDCRS["WGS 84 + NAVD88 height",GEODCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],CS[ellipsoidal,2],AXIS["longitude",east],AXIS["latitude",north],ANGLEUNIT["degree",0.0174532925199433]],VERTCRS["NAVD88 height",VDATUM["North American Vertical Datum 1988",ID["EPSG",5103]],CS[vertical,1],AXIS["gravity-related height",up,LENGTHUNIT["metre",1]],LENGTHUNIT["metre",1]]]"#;
        let crs = parse_wkt(wkt).unwrap();
        assert!(crs.is_compound());
        assert!(crs.is_geographic());
        assert_eq!(
            crs.vertical_crs().unwrap().linear_unit_to_meter(),
            LinearUnit::metre().meters_per_unit()
        );
    }

    #[test]
    fn parse_wkt_vertical_crs_canonicalized_from_crs_epsg() {
        let wkt = r#"COMPOUNDCRS["WGS 84 + NAVD88 height",GEODCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],CS[ellipsoidal,2],AXIS["longitude",east],AXIS["latitude",north],ANGLEUNIT["degree",0.0174532925199433]],VERTCRS["NAVD88 height",VDATUM["North American Vertical Datum 1988"],CS[vertical,1],AXIS["gravity-related height",up,LENGTHUNIT["metre",1]],LENGTHUNIT["metre",1],ID["EPSG",5703]]]"#;
        let crs = parse_wkt(wkt).unwrap();
        let vertical = crs.vertical_crs().unwrap();
        assert_eq!(vertical.epsg(), 5703);
        assert_eq!(vertical.vertical_datum_epsg(), Some(5103));
    }

    #[test]
    fn reject_standalone_vertical_wkt() {
        let wkt = r#"VERTCRS["NAVD88 height",VDATUM["North American Vertical Datum 1988",ID["EPSG",5103]],CS[vertical,1],AXIS["gravity-related height",up,LENGTHUNIT["metre",1]],LENGTHUNIT["metre",1]]"#;
        let err = parse_wkt(wkt).unwrap_err();
        assert!(err.to_string().contains("standalone vertical CRS"));
    }

    #[test]
    fn reject_geographic_wkt_with_non_degree_unit() {
        let err = parse_wkt(
            r#"GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],UNIT["radian",1]]"#,
        )
        .unwrap_err();
        assert!(err.to_string().contains("angular units other than degrees"));
    }

    #[test]
    fn reject_geographic_wkt_with_reversed_axes() {
        let err = parse_wkt(
            r#"GEOGCRS["Custom",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],CS[ellipsoidal,2],AXIS["latitude",north],AXIS["longitude",east],ANGLEUNIT["degree",0.0174532925199433]]"#,
        )
        .unwrap_err();
        assert!(err
            .to_string()
            .contains("unsupported axis order/directions"));
    }

    #[test]
    fn parse_wkt_projcs_no_authority() {
        let wkt = r#"PROJCS["custom",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-75],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0]]"#;
        let crs = parse_wkt(wkt).unwrap();
        assert!(crs.is_projected());
    }

    #[test]
    fn reject_projected_wkt_with_invalid_parameter_value() {
        let wkt = r#"PROJCS["custom",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian","not-a-number"],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0]]"#;
        let err = parse_wkt(wkt).unwrap_err();
        assert!(err
            .to_string()
            .contains("invalid WKT projection parameter `central_meridian` value"));
    }

    #[test]
    fn reject_projected_wkt_with_missing_parameter_value() {
        let wkt = r#"PROJCS["custom",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian"],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0]]"#;
        let err = parse_wkt(wkt).unwrap_err();
        assert!(err
            .to_string()
            .contains("WKT projection parameter `central_meridian` is missing a numeric value"));
    }

    #[test]
    fn parse_wkt_projcs_ignores_nested_base_authority() {
        let wkt = r#"PROJCS["custom",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-75],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0]]"#;
        let crs = parse_wkt(wkt).unwrap();
        assert!(crs.is_projected());
        assert_eq!(crs.epsg(), 0);
    }

    #[test]
    fn reject_unknown_geographic_datum() {
        let err =
            parse_wkt(r#"GEOGCS["Unknown",DATUM["Custom",SPHEROID["Custom",1,1]]]"#).unwrap_err();
        assert!(err
            .to_string()
            .contains("unsupported or unrecognized WKT datum"));
    }

    #[test]
    fn parse_wkt2_projected_without_authority() {
        let wkt = r#"PROJCRS["WGS 84 / UTM zone 18N",BASEGEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]]],CONVERSION["UTM zone 18N",METHOD["Transverse Mercator"],PARAMETER["Latitude of natural origin",0,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Longitude of natural origin",-75,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Scale factor at natural origin",0.9996,SCALEUNIT["unity",1]],PARAMETER["False easting",500000,LENGTHUNIT["metre",1]],PARAMETER["False northing",0,LENGTHUNIT["metre",1]]],CS[Cartesian,2],AXIS["easting",east],AXIS["northing",north],LENGTHUNIT["metre",1]]"#;
        let crs = parse_wkt(wkt).unwrap();
        assert!(crs.is_projected());
    }

    #[test]
    fn parse_wkt2_projected_with_axis_only_foot_units() {
        let meter_wkt = r#"PROJCRS["WGS 84 / UTM zone 18N metre",BASEGEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]]],CONVERSION["UTM zone 18N",METHOD["Transverse Mercator"],PARAMETER["Latitude of natural origin",0,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Longitude of natural origin",-75,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Scale factor at natural origin",0.9996,SCALEUNIT["unity",1]],PARAMETER["False easting",500000],PARAMETER["False northing",0]],CS[Cartesian,2],AXIS["easting",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["northing",north,ORDER[2],LENGTHUNIT["metre",1]]]"#;
        let foot_wkt = r#"PROJCRS["WGS 84 / UTM zone 18N ftUS",BASEGEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]]],CONVERSION["UTM zone 18N",METHOD["Transverse Mercator"],PARAMETER["Latitude of natural origin",0,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Longitude of natural origin",-75,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Scale factor at natural origin",0.9996,SCALEUNIT["unity",1]],PARAMETER["False easting",1640416.6666666667],PARAMETER["False northing",0]],CS[Cartesian,2],AXIS["easting",east,ORDER[1],LENGTHUNIT["US survey foot",0.3048006096012192]],AXIS["northing",north,ORDER[2],LENGTHUNIT["US survey foot",0.3048006096012192]]]"#;

        let meter_crs = parse_wkt(meter_wkt).unwrap();
        let foot_crs = parse_wkt(foot_wkt).unwrap();
        let from = proj_core::lookup_epsg(4326).unwrap();

        let meter_tx = proj_core::Transform::from_crs_defs(&from, &meter_crs).unwrap();
        let foot_tx = proj_core::Transform::from_crs_defs(&from, &foot_crs).unwrap();

        let (mx, my) = meter_tx.convert((-74.006, 40.7128)).unwrap();
        let (fx, fy) = foot_tx.convert((-74.006, 40.7128)).unwrap();

        assert!((fx * US_FOOT_TO_METER - mx).abs() < 0.02, "x mismatch");
        assert!((fy * US_FOOT_TO_METER - my).abs() < 0.02, "y mismatch");
    }

    #[test]
    fn reject_wkt2_geographic_with_axis_only_grad_units() {
        let err = parse_wkt(
            r#"GEODCRS["Custom grad",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],CS[ellipsoidal,2],AXIS["longitude",east,ORDER[1],ANGLEUNIT["grad",0.015707963267949]],AXIS["latitude",north,ORDER[2],ANGLEUNIT["grad",0.015707963267949]]]"#,
        )
        .unwrap_err();

        assert!(matches!(&err, ParseError::UnsupportedSemantics(_)));
        assert!(err.to_string().contains("angular units other than degrees"));
    }

    #[test]
    fn reject_wkt2_projected_with_inconsistent_axis_units() {
        let err = parse_wkt(
            r#"PROJCRS["Custom inconsistent axes",BASEGEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]]],CONVERSION["UTM zone 18N",METHOD["Transverse Mercator"],PARAMETER["Latitude of natural origin",0,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Longitude of natural origin",-75,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Scale factor at natural origin",0.9996,SCALEUNIT["unity",1]],PARAMETER["False easting",500000],PARAMETER["False northing",0]],CS[Cartesian,2],AXIS["easting",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["northing",north,ORDER[2],LENGTHUNIT["US survey foot",0.3048006096012192]]]"#,
        )
        .unwrap_err();

        assert!(matches!(&err, ParseError::UnsupportedSemantics(_)));
        assert!(err
            .to_string()
            .contains("inconsistent projected axis units"));
    }

    #[test]
    fn parse_wkt_projcs_with_foot_units() {
        let meter_wkt = r#"PROJCS["UTM 18N metre",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-75],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1]]"#;
        let foot_wkt = r#"PROJCS["UTM 18N ftUS",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-75],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",1640416.6666666667],PARAMETER["false_northing",0],UNIT["Foot_US",0.3048006096012192]]"#;

        let meter_crs = parse_wkt(meter_wkt).unwrap();
        let foot_crs = parse_wkt(foot_wkt).unwrap();
        let from = proj_core::lookup_epsg(4326).unwrap();

        let meter_tx = proj_core::Transform::from_crs_defs(&from, &meter_crs).unwrap();
        let foot_tx = proj_core::Transform::from_crs_defs(&from, &foot_crs).unwrap();

        let (mx, my) = meter_tx.convert((-74.006, 40.7128)).unwrap();
        let (fx, fy) = foot_tx.convert((-74.006, 40.7128)).unwrap();

        assert!((fx * US_FOOT_TO_METER - mx).abs() < 0.02, "x mismatch");
        assert!((fy * US_FOOT_TO_METER - my).abs() < 0.02, "y mismatch");
    }

    #[test]
    fn reject_projected_wkt_with_non_greenwich_base_prime_meridian() {
        let err = parse_wkt(
            r#"PROJCS["custom",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Paris",2.33722917],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-75],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1]]"#,
        )
        .unwrap_err();
        assert!(err.to_string().contains("non-Greenwich prime meridian"));
    }

    #[test]
    fn reject_projected_wkt_with_reversed_projected_axes() {
        let err = parse_wkt(
            r#"PROJCRS["Custom",BASEGEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],CS[ellipsoidal,2],AXIS["longitude",east],AXIS["latitude",north],ANGLEUNIT["degree",0.0174532925199433]],CONVERSION["UTM zone 18N",METHOD["Transverse Mercator"],PARAMETER["Latitude of natural origin",0,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Longitude of natural origin",-75,ANGLEUNIT["degree",0.0174532925199433]],PARAMETER["Scale factor at natural origin",0.9996,SCALEUNIT["unity",1]],PARAMETER["False easting",500000,LENGTHUNIT["metre",1]],PARAMETER["False northing",0,LENGTHUNIT["metre",1]]],CS[Cartesian,2],AXIS["northing",north],AXIS["easting",east],LENGTHUNIT["metre",1]]"#,
        )
        .unwrap_err();
        assert!(err
            .to_string()
            .contains("unsupported axis order/directions"));
    }

    #[test]
    fn parse_wkt2_geographic_with_id() {
        let wkt = r#"GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],CS[ellipsoidal,2],AXIS["longitude",east],AXIS["latitude",north],ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",4326]]"#;
        let crs = parse_wkt(wkt).unwrap();
        assert!(crs.is_geographic());
        assert_eq!(crs.epsg(), 4326);
    }

    #[test]
    fn reject_wkt_with_top_level_epsg_mismatch() {
        let err = parse_wkt(
            r#"GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],CS[ellipsoidal,2],AXIS["longitude",east],AXIS["latitude",north],ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",4269]]"#,
        )
        .unwrap_err();
        assert!(err
            .to_string()
            .contains("does not match the embedded EPSG semantics"));
    }

    #[test]
    fn reject_wkt_with_top_level_epsg_and_reversed_axes() {
        let err = parse_wkt(
            r#"GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563]],CS[ellipsoidal,2],AXIS["latitude",north],AXIS["longitude",east],ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",4326]]"#,
        )
        .unwrap_err();
        assert!(err
            .to_string()
            .contains("unsupported axis order/directions"));
    }

    #[test]
    fn reject_custom_airy_datum_without_structured_match() {
        let err = parse_wkt(
            r#"GEOGCRS["Custom Airy",DATUM["Custom Airy Datum",ELLIPSOID["Airy 1830",6377563.396,299.3249646]],CS[ellipsoidal,2],AXIS["longitude",east],AXIS["latitude",north],ANGLEUNIT["degree",0.0174532925199433]]"#,
        )
        .unwrap_err();
        assert!(err
            .to_string()
            .contains("unsupported or unrecognized WKT datum"));
    }
}