oxigdal-cli 0.1.4

Command-line interface for OxiGDAL geospatial operations
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
//! Vector format conversion utilities
//!
//! Provides format-to-format vector conversion with optional attribute filtering.
//! Supports GeoJSON, Shapefile, and FlatGeobuf as input and output formats.

use anyhow::{Context, Result, anyhow};
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;

// ─── Public enums / structs ───────────────────────────────────────────────────

/// Supported vector output formats for CLI conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VectorFormat {
    /// GeoJSON format (`.geojson`, `.json`).
    GeoJson,
    /// ESRI Shapefile format (`.shp`).
    Shapefile,
    /// FlatGeobuf format (`.fgb`).
    FlatGeobuf,
}

impl VectorFormat {
    /// Detect format from file extension.
    pub fn from_path(path: &Path) -> Option<Self> {
        path.extension()
            .and_then(|e| e.to_str())
            .and_then(|e| match e.to_lowercase().as_str() {
                "geojson" | "json" => Some(Self::GeoJson),
                "shp" => Some(Self::Shapefile),
                "fgb" => Some(Self::FlatGeobuf),
                _ => None,
            })
    }
}

/// Attribute filter operator.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FilterOp {
    /// Exact string equality (case-insensitive).
    Eq,
    /// Inequality (case-insensitive).
    Ne,
    /// Substring containment (case-insensitive).
    Contains,
}

/// Attribute filter: matches a named field against a value using an operator.
#[derive(Debug, Clone)]
pub struct AttributeFilter {
    /// The name of the feature attribute field to filter on.
    pub field: String,
    /// The comparison operator to apply.
    pub op: FilterOp,
    /// The value to compare against.
    pub value: String,
}

impl AttributeFilter {
    /// Test whether a JSON properties map matches this filter.
    pub fn matches_json(&self, props: &serde_json::Map<String, serde_json::Value>) -> bool {
        match props.get(&self.field) {
            None => false,
            Some(v) => {
                let candidate = json_value_to_string(v).to_lowercase();
                let target = self.value.to_lowercase();
                match self.op {
                    FilterOp::Eq => candidate == target,
                    FilterOp::Ne => candidate != target,
                    FilterOp::Contains => candidate.contains(&target),
                }
            }
        }
    }

    /// Test whether an `oxigdal_core::vector::FieldValue` map matches this filter.
    pub fn matches_field_map(
        &self,
        props: &std::collections::HashMap<String, oxigdal_core::vector::FieldValue>,
    ) -> bool {
        match props.get(&self.field) {
            None => false,
            Some(v) => {
                let candidate = field_value_to_string(v).to_lowercase();
                let target = self.value.to_lowercase();
                match self.op {
                    FilterOp::Eq => candidate == target,
                    FilterOp::Ne => candidate != target,
                    FilterOp::Contains => candidate.contains(&target),
                }
            }
        }
    }
}

// ─── Helper: stringify values ─────────────────────────────────────────────────

fn json_value_to_string(v: &serde_json::Value) -> String {
    match v {
        serde_json::Value::Null => String::new(),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Array(a) => format!("{a:?}"),
        serde_json::Value::Object(o) => format!("{o:?}"),
    }
}

fn field_value_to_string(v: &oxigdal_core::vector::FieldValue) -> String {
    use oxigdal_core::vector::FieldValue;
    match v {
        FieldValue::Null => String::new(),
        FieldValue::Bool(b) => b.to_string(),
        FieldValue::Integer(i) => i.to_string(),
        FieldValue::UInteger(u) => u.to_string(),
        FieldValue::Float(f) => f.to_string(),
        FieldValue::String(s) => s.clone(),
        FieldValue::Array(a) => format!("{a:?}"),
        FieldValue::Object(o) => format!("{o:?}"),
        FieldValue::Date(d) => d.to_string(),
        FieldValue::Blob(b) => format!("{b:?}"),
    }
}

// ─── GeoJSON Geometry ↔ Core Geometry converters ─────────────────────────────

/// Convert a GeoJSON geometry (`oxigdal_geojson::Geometry`) to a core geometry
/// (`oxigdal_core::vector::Geometry`).  Returns an error if coordinates are malformed.
pub fn geojson_geom_to_core(
    geom: &oxigdal_geojson::Geometry,
) -> Result<oxigdal_core::vector::Geometry> {
    use oxigdal_core::vector::{
        Geometry as CoreGeom, GeometryCollection as CoreGC, LineString as CoreLS,
        MultiLineString as CoreMLS, MultiPoint as CoreMP, MultiPolygon as CoreMPoly,
        Point as CorePoint, Polygon as CorePoly,
    };
    use oxigdal_geojson::Geometry as GjGeom;

    match geom {
        GjGeom::Point(p) => {
            let coord = pos_to_coord(&p.coordinates)?;
            Ok(CoreGeom::Point(CorePoint::from_coord(coord)))
        }
        GjGeom::LineString(ls) => {
            let coords = positions_to_coords(&ls.coordinates)?;
            let core_ls =
                CoreLS::new(coords).map_err(|e| anyhow!("LineString conversion error: {e}"))?;
            Ok(CoreGeom::LineString(core_ls))
        }
        GjGeom::Polygon(p) => {
            let rings = p
                .coordinates
                .iter()
                .map(|ring| positions_to_coords(ring))
                .collect::<Result<Vec<_>>>()?;
            let (exterior, interiors) = rings_to_exterior_interiors(rings)?;
            let core_poly = CorePoly::new(exterior, interiors)
                .map_err(|e| anyhow!("Polygon conversion error: {e}"))?;
            Ok(CoreGeom::Polygon(core_poly))
        }
        GjGeom::MultiPoint(mp) => {
            let points = mp
                .coordinates
                .iter()
                .map(|pos| {
                    let coord = pos_to_coord(pos)?;
                    Ok(CorePoint::from_coord(coord))
                })
                .collect::<Result<Vec<_>>>()?;
            Ok(CoreGeom::MultiPoint(CoreMP::new(points)))
        }
        GjGeom::MultiLineString(mls) => {
            let lines = mls
                .coordinates
                .iter()
                .map(|ring| {
                    let coords = positions_to_coords(ring)?;
                    CoreLS::new(coords).map_err(|e| anyhow!("MultiLineString line error: {e}"))
                })
                .collect::<Result<Vec<_>>>()?;
            Ok(CoreGeom::MultiLineString(CoreMLS {
                line_strings: lines,
            }))
        }
        GjGeom::MultiPolygon(mpoly) => {
            let polygons = mpoly
                .coordinates
                .iter()
                .map(|rings| {
                    let coord_rings = rings
                        .iter()
                        .map(|ring| positions_to_coords(ring))
                        .collect::<Result<Vec<_>>>()?;
                    let (exterior, interiors) = rings_to_exterior_interiors(coord_rings)?;
                    CorePoly::new(exterior, interiors)
                        .map_err(|e| anyhow!("MultiPolygon polygon error: {e}"))
                })
                .collect::<Result<Vec<_>>>()?;
            Ok(CoreGeom::MultiPolygon(CoreMPoly { polygons }))
        }
        GjGeom::GeometryCollection(gc) => {
            let geoms = gc
                .geometries
                .iter()
                .map(geojson_geom_to_core)
                .collect::<Result<Vec<_>>>()?;
            Ok(CoreGeom::GeometryCollection(CoreGC { geometries: geoms }))
        }
    }
}

/// Convert a core geometry to a GeoJSON geometry.
pub fn core_geom_to_geojson(
    geom: &oxigdal_core::vector::Geometry,
) -> Result<oxigdal_geojson::Geometry> {
    use oxigdal_core::vector::Geometry as CoreGeom;
    use oxigdal_geojson::types::{
        Geometry as GjGeom, GeometryCollection as GjGC, LineString as GjLS,
        MultiLineString as GjMLS, MultiPoint as GjMP, MultiPolygon as GjMPoly, Point as GjPoint,
        Polygon as GjPoly,
    };

    match geom {
        CoreGeom::Point(p) => {
            let pos = coord_to_pos(&p.coord);
            let gj_point = GjPoint::new(pos).map_err(|e| anyhow!("Point conversion error: {e}"))?;
            Ok(GjGeom::Point(gj_point))
        }
        CoreGeom::LineString(ls) => {
            let coords = ls.coords.iter().map(coord_to_pos).collect();
            let gj_ls =
                GjLS::new(coords).map_err(|e| anyhow!("LineString conversion error: {e}"))?;
            Ok(GjGeom::LineString(gj_ls))
        }
        CoreGeom::Polygon(p) => {
            let exterior: Vec<Vec<f64>> = p.exterior.coords.iter().map(coord_to_pos).collect();
            let mut rings = vec![exterior];
            for interior in &p.interiors {
                rings.push(interior.coords.iter().map(coord_to_pos).collect());
            }
            let gj_poly =
                GjPoly::new(rings).map_err(|e| anyhow!("Polygon conversion error: {e}"))?;
            Ok(GjGeom::Polygon(gj_poly))
        }
        CoreGeom::MultiPoint(mp) => {
            let positions = mp.points.iter().map(|p| coord_to_pos(&p.coord)).collect();
            let gj_mp = GjMP {
                coordinates: positions,
                bbox: None,
            };
            Ok(GjGeom::MultiPoint(gj_mp))
        }
        CoreGeom::MultiLineString(mls) => {
            let lines = mls
                .line_strings
                .iter()
                .map(|ls| ls.coords.iter().map(coord_to_pos).collect::<Vec<_>>())
                .collect();
            let gj_mls = GjMLS {
                coordinates: lines,
                bbox: None,
            };
            Ok(GjGeom::MultiLineString(gj_mls))
        }
        CoreGeom::MultiPolygon(mpoly) => {
            let polys = mpoly
                .polygons
                .iter()
                .map(|p| {
                    let ext: Vec<Vec<f64>> = p.exterior.coords.iter().map(coord_to_pos).collect();
                    let mut rings = vec![ext];
                    for interior in &p.interiors {
                        rings.push(interior.coords.iter().map(coord_to_pos).collect());
                    }
                    rings
                })
                .collect();
            let gj_mpoly = GjMPoly {
                coordinates: polys,
                bbox: None,
            };
            Ok(GjGeom::MultiPolygon(gj_mpoly))
        }
        CoreGeom::GeometryCollection(gc) => {
            let geoms = gc
                .geometries
                .iter()
                .map(core_geom_to_geojson)
                .collect::<Result<Vec<_>>>()?;
            let gj_gc = GjGC {
                geometries: geoms,
                bbox: None,
            };
            Ok(GjGeom::GeometryCollection(gj_gc))
        }
    }
}

// ─── Small coordinate helpers ─────────────────────────────────────────────────

fn pos_to_coord(pos: &[f64]) -> Result<oxigdal_core::vector::Coordinate> {
    if pos.len() < 2 {
        return Err(anyhow!(
            "position needs at least 2 elements, got {}",
            pos.len()
        ));
    }
    Ok(oxigdal_core::vector::Coordinate {
        x: pos[0],
        y: pos[1],
        z: pos.get(2).copied(),
        m: None,
    })
}

fn positions_to_coords(positions: &[Vec<f64>]) -> Result<Vec<oxigdal_core::vector::Coordinate>> {
    positions.iter().map(|p| pos_to_coord(p)).collect()
}

fn coord_to_pos(c: &oxigdal_core::vector::Coordinate) -> Vec<f64> {
    match c.z {
        Some(z) => vec![c.x, c.y, z],
        None => vec![c.x, c.y],
    }
}

/// Split a vec of rings into (exterior, interiors).
/// The exterior ring is the first ring; the rest are interior holes.
fn rings_to_exterior_interiors(
    mut rings: Vec<Vec<oxigdal_core::vector::Coordinate>>,
) -> Result<(
    oxigdal_core::vector::LineString,
    Vec<oxigdal_core::vector::LineString>,
)> {
    use oxigdal_core::vector::LineString as CoreLS;

    if rings.is_empty() {
        return Err(anyhow!("polygon has no rings"));
    }

    let exterior_coords = rings.remove(0);
    let exterior = CoreLS::new(exterior_coords).map_err(|e| anyhow!("exterior ring error: {e}"))?;

    let interiors = rings
        .into_iter()
        .map(|ring| CoreLS::new(ring).map_err(|e| anyhow!("interior ring error: {e}")))
        .collect::<Result<Vec<_>>>()?;

    Ok((exterior, interiors))
}

// ─── Shapefile schema inference ───────────────────────────────────────────────

/// Infer the `ShapeType` and `FieldDescriptor`s from a slice of Shapefile features.
/// Used when the input is GeoJSON and output is Shapefile.
pub fn infer_shapefile_schema_from_geojson(
    features: &[oxigdal_geojson::Feature],
) -> Result<(
    oxigdal_shapefile::shp::shapes::ShapeType,
    Vec<oxigdal_shapefile::dbf::FieldDescriptor>,
)> {
    use oxigdal_geojson::Geometry as GjGeom;
    use oxigdal_shapefile::{
        dbf::{FieldDescriptor, FieldType},
        shp::shapes::ShapeType,
    };

    // Determine shape type from first feature with geometry
    let shape_type = features
        .iter()
        .find_map(|f| f.geometry.as_ref())
        .map(|g| match g {
            GjGeom::Point(_) => ShapeType::Point,
            GjGeom::LineString(_) | GjGeom::MultiLineString(_) => ShapeType::PolyLine,
            GjGeom::Polygon(_) | GjGeom::MultiPolygon(_) => ShapeType::Polygon,
            GjGeom::MultiPoint(_) => ShapeType::MultiPoint,
            GjGeom::GeometryCollection(_) => ShapeType::Point, // fallback
        })
        .unwrap_or(ShapeType::Point);

    // Scan all features for property names and their max string width
    let mut field_widths: std::collections::HashMap<String, u8> = std::collections::HashMap::new();

    for feature in features {
        if let Some(props) = &feature.properties {
            for (key, value) in props {
                let key_short = truncate_field_name(key);
                let width = json_value_str_width(value);
                let entry = field_widths.entry(key_short).or_insert(0);
                if width > *entry {
                    *entry = width;
                }
            }
        }
    }

    let mut descriptors = Vec::new();
    for (name, width) in &field_widths {
        let length = width.clamp(&1, &254);
        let desc = FieldDescriptor::new(name.clone(), FieldType::Character, *length, 0)
            .with_context(|| format!("invalid field descriptor for '{name}'"))?;
        descriptors.push(desc);
    }

    // Sort deterministically
    descriptors.sort_by(|a, b| a.name.cmp(&b.name));

    Ok((shape_type, descriptors))
}

/// Infer the `ShapeType` and `FieldDescriptor`s from core vector features
/// (used for Shapefile-to-Shapefile passthrough is not needed here; used for
/// Shapefile→FGB schema inference via core).
pub fn infer_shapefile_schema_from_shapefiles(
    features: &[oxigdal_shapefile::reader::ShapefileFeature],
) -> Result<(
    oxigdal_shapefile::shp::shapes::ShapeType,
    Vec<oxigdal_shapefile::dbf::FieldDescriptor>,
)> {
    use oxigdal_core::vector::Geometry as CoreGeom;
    use oxigdal_shapefile::{
        dbf::{FieldDescriptor, FieldType},
        shp::shapes::ShapeType,
    };

    let shape_type = features
        .iter()
        .find_map(|f| f.geometry.as_ref())
        .map(|g| match g {
            CoreGeom::Point(_) => ShapeType::Point,
            CoreGeom::LineString(_) | CoreGeom::MultiLineString(_) => ShapeType::PolyLine,
            CoreGeom::Polygon(_) | CoreGeom::MultiPolygon(_) => ShapeType::Polygon,
            CoreGeom::MultiPoint(_) => ShapeType::MultiPoint,
            CoreGeom::GeometryCollection(_) => ShapeType::Point,
        })
        .unwrap_or(ShapeType::Point);

    let mut field_widths: std::collections::HashMap<String, u8> = std::collections::HashMap::new();

    for feature in features {
        for (key, value) in &feature.attributes {
            let key_short = truncate_field_name(key);
            let width = field_value_str_width(value);
            let entry = field_widths.entry(key_short).or_insert(0);
            if width > *entry {
                *entry = width;
            }
        }
    }

    let mut descriptors = Vec::new();
    for (name, width) in &field_widths {
        let length = width.clamp(&1, &254);
        let desc = FieldDescriptor::new(name.clone(), FieldType::Character, *length, 0)
            .with_context(|| format!("invalid field descriptor for '{name}'"))?;
        descriptors.push(desc);
    }

    descriptors.sort_by(|a, b| a.name.cmp(&b.name));

    Ok((shape_type, descriptors))
}

/// Truncate a field name to the 10-character DBF limit.
fn truncate_field_name(name: &str) -> String {
    name.chars().take(10).collect()
}

fn json_value_str_width(v: &serde_json::Value) -> u8 {
    let s = json_value_to_string(v);
    s.len().min(254) as u8
}

fn field_value_str_width(v: &oxigdal_core::vector::FieldValue) -> u8 {
    let s = field_value_to_string(v);
    s.len().min(254) as u8
}

// ─── GeoJSON features → Shapefile features ───────────────────────────────────

fn geojson_feature_to_shapefile(
    feature: &oxigdal_geojson::Feature,
    record_number: i32,
    field_names: &[String],
) -> Result<oxigdal_shapefile::reader::ShapefileFeature> {
    use oxigdal_core::vector::FieldValue;
    use oxigdal_shapefile::reader::ShapefileFeature;

    let geometry = match &feature.geometry {
        Some(gj_geom) => Some(geojson_geom_to_core(gj_geom)?),
        None => None,
    };

    let mut attributes = std::collections::HashMap::new();

    if let Some(props) = &feature.properties {
        for name in field_names {
            // find original key (may have been truncated to 10 chars)
            let original_key = props
                .keys()
                .find(|k| truncate_field_name(k) == *name)
                .cloned();

            if let Some(key) = original_key {
                let json_val = props.get(&key).cloned().unwrap_or(serde_json::Value::Null);
                let fv = json_to_field_value(&json_val);
                attributes.insert(name.clone(), fv);
            } else {
                attributes.insert(name.clone(), FieldValue::Null);
            }
        }
    } else {
        for name in field_names {
            attributes.insert(name.clone(), FieldValue::Null);
        }
    }

    Ok(ShapefileFeature::new(record_number, geometry, attributes))
}

fn json_to_field_value(v: &serde_json::Value) -> oxigdal_core::vector::FieldValue {
    use oxigdal_core::vector::FieldValue;
    match v {
        serde_json::Value::Null => FieldValue::Null,
        serde_json::Value::Bool(b) => FieldValue::Bool(*b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                FieldValue::Integer(i)
            } else if let Some(u) = n.as_u64() {
                FieldValue::UInteger(u)
            } else {
                FieldValue::Float(n.as_f64().unwrap_or(0.0))
            }
        }
        serde_json::Value::String(s) => FieldValue::String(s.clone()),
        other => FieldValue::String(other.to_string()),
    }
}

// ─── Shapefile features → GeoJSON FeatureCollection ──────────────────────────

fn shapefile_feature_to_geojson(
    sf: &oxigdal_shapefile::reader::ShapefileFeature,
) -> Result<oxigdal_geojson::Feature> {
    use oxigdal_geojson::Feature as GjFeature;

    let geometry = match &sf.geometry {
        Some(core_geom) => Some(core_geom_to_geojson(core_geom)?),
        None => None,
    };

    let mut props = serde_json::Map::new();
    for (key, value) in &sf.attributes {
        props.insert(key.clone(), value.to_json_value());
    }

    Ok(GjFeature::new(geometry, Some(props)))
}

// ─── Main conversion entry point ─────────────────────────────────────────────

/// Convert a vector dataset between supported formats.
///
/// Returns the number of features written.
pub fn convert_vector(
    input: &Path,
    output: &Path,
    filter: Option<&AttributeFilter>,
) -> Result<usize> {
    let input_fmt = VectorFormat::from_path(input)
        .ok_or_else(|| anyhow!("Unknown input vector format: {}", input.display()))?;
    let output_fmt = VectorFormat::from_path(output)
        .ok_or_else(|| anyhow!("Cannot determine output format from: {}", output.display()))?;

    match (input_fmt, output_fmt) {
        (VectorFormat::GeoJson, VectorFormat::GeoJson) => {
            convert_geojson_to_geojson(input, output, filter)
        }
        (VectorFormat::GeoJson, VectorFormat::Shapefile) => {
            convert_geojson_to_shapefile(input, output, filter)
        }
        (VectorFormat::Shapefile, VectorFormat::GeoJson) => {
            convert_shapefile_to_geojson(input, output, filter)
        }
        (VectorFormat::Shapefile, VectorFormat::Shapefile) => {
            convert_shapefile_to_shapefile(input, output, filter)
        }
        (VectorFormat::GeoJson, VectorFormat::FlatGeobuf)
        | (VectorFormat::Shapefile, VectorFormat::FlatGeobuf)
        | (VectorFormat::FlatGeobuf, _) => {
            anyhow::bail!(
                "FlatGeobuf vector conversion is not yet implemented (input: {}, output: {})",
                input.display(),
                output.display()
            )
        }
    }
}

// ─── GeoJSON → GeoJSON ────────────────────────────────────────────────────────

fn convert_geojson_to_geojson(
    input: &Path,
    output: &Path,
    filter: Option<&AttributeFilter>,
) -> Result<usize> {
    use oxigdal_geojson::{FeatureCollection, GeoJsonReader, GeoJsonWriter};

    let file =
        File::open(input).with_context(|| format!("Failed to open input: {}", input.display()))?;
    let buf_reader = BufReader::new(file);
    let mut reader = GeoJsonReader::new(buf_reader);

    let fc = reader
        .read_feature_collection()
        .context("Failed to read GeoJSON feature collection")?;

    let features: Vec<_> = fc
        .features
        .into_iter()
        .filter(|f| match filter {
            None => true,
            Some(filt) => {
                let props = f
                    .properties
                    .as_ref()
                    .map_or(serde_json::Map::new(), |p| p.clone());
                filt.matches_json(&props)
            }
        })
        .collect();

    let count = features.len();

    let out_fc = FeatureCollection::new(features);

    let out_file = File::create(output)
        .with_context(|| format!("Failed to create output: {}", output.display()))?;
    let buf_writer = BufWriter::new(out_file);
    let mut writer = GeoJsonWriter::pretty(buf_writer);

    writer
        .write_feature_collection(&out_fc)
        .context("Failed to write GeoJSON")?;

    Ok(count)
}

// ─── GeoJSON → Shapefile ──────────────────────────────────────────────────────

fn convert_geojson_to_shapefile(
    input: &Path,
    output: &Path,
    filter: Option<&AttributeFilter>,
) -> Result<usize> {
    use oxigdal_geojson::GeoJsonReader;
    use oxigdal_shapefile::ShapefileWriter;

    let file =
        File::open(input).with_context(|| format!("Failed to open input: {}", input.display()))?;
    let buf_reader = BufReader::new(file);
    let mut reader = GeoJsonReader::new(buf_reader);

    let fc = reader
        .read_feature_collection()
        .context("Failed to read GeoJSON feature collection")?;

    let features: Vec<_> = fc
        .features
        .into_iter()
        .filter(|f| match filter {
            None => true,
            Some(filt) => {
                let props = f
                    .properties
                    .as_ref()
                    .map_or(serde_json::Map::new(), |p| p.clone());
                filt.matches_json(&props)
            }
        })
        .collect();

    if features.is_empty() {
        anyhow::bail!("No features remain after filtering; cannot write empty Shapefile");
    }

    let count = features.len();

    // Infer schema from filtered features
    let (shape_type, field_descriptors) = infer_shapefile_schema_from_geojson(&features)?;

    let field_names: Vec<String> = field_descriptors.iter().map(|d| d.name.clone()).collect();

    // Output base path (strip .shp extension)
    let base_path = output.with_extension("");

    let mut writer = ShapefileWriter::new(&base_path, shape_type, field_descriptors)
        .context("Failed to create Shapefile writer")?;

    // Convert features to ShapefileFeature
    let sf_features: Vec<_> = features
        .iter()
        .enumerate()
        .map(|(i, f)| geojson_feature_to_shapefile(f, (i + 1) as i32, &field_names))
        .collect::<Result<Vec<_>>>()?;

    writer
        .write_features(&sf_features)
        .context("Failed to write Shapefile")?;

    Ok(count)
}

// ─── Shapefile → GeoJSON ──────────────────────────────────────────────────────

fn convert_shapefile_to_geojson(
    input: &Path,
    output: &Path,
    filter: Option<&AttributeFilter>,
) -> Result<usize> {
    use oxigdal_geojson::{FeatureCollection, GeoJsonWriter};
    use oxigdal_shapefile::ShapefileReader;

    // Strip .shp extension for base path
    let base_path = input.with_extension("");

    let reader = ShapefileReader::open(&base_path)
        .with_context(|| format!("Failed to open Shapefile: {}", input.display()))?;

    let sf_features = reader
        .read_features()
        .context("Failed to read Shapefile features")?;

    let filtered: Vec<_> = sf_features
        .into_iter()
        .filter(|f| match filter {
            None => true,
            Some(filt) => filt.matches_field_map(&f.attributes),
        })
        .collect();

    let count = filtered.len();

    // Convert to GeoJSON features
    let gj_features = filtered
        .iter()
        .map(shapefile_feature_to_geojson)
        .collect::<Result<Vec<_>>>()?;

    let out_fc = FeatureCollection::new(gj_features);

    let out_file = File::create(output)
        .with_context(|| format!("Failed to create output: {}", output.display()))?;
    let buf_writer = BufWriter::new(out_file);
    let mut writer = GeoJsonWriter::pretty(buf_writer);

    writer
        .write_feature_collection(&out_fc)
        .context("Failed to write GeoJSON")?;

    Ok(count)
}

// ─── Shapefile → Shapefile ────────────────────────────────────────────────────

fn convert_shapefile_to_shapefile(
    input: &Path,
    output: &Path,
    filter: Option<&AttributeFilter>,
) -> Result<usize> {
    use oxigdal_shapefile::{ShapefileReader, ShapefileWriter};

    let base_in = input.with_extension("");
    let reader = ShapefileReader::open(&base_in)
        .with_context(|| format!("Failed to open Shapefile: {}", input.display()))?;

    let sf_features = reader
        .read_features()
        .context("Failed to read Shapefile features")?;

    let filtered: Vec<_> = sf_features
        .into_iter()
        .filter(|f| match filter {
            None => true,
            Some(filt) => filt.matches_field_map(&f.attributes),
        })
        .collect();

    if filtered.is_empty() {
        anyhow::bail!("No features remain after filtering; cannot write empty Shapefile");
    }

    let count = filtered.len();

    let (shape_type, field_descriptors) = infer_shapefile_schema_from_shapefiles(&filtered)?;

    let base_out = output.with_extension("");
    let mut writer = ShapefileWriter::new(&base_out, shape_type, field_descriptors)
        .context("Failed to create Shapefile writer")?;

    writer
        .write_features(&filtered)
        .context("Failed to write Shapefile")?;

    Ok(count)
}