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
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
//! Rasterize command - Convert vector geometries to raster
//!
//! Converts vector features (points, lines, polygons) into raster format.
//! Supports attribute burning, fixed value burning, and various burn modes.
//!
//! Examples:
//! ```bash
//! # Burn vector to raster with fixed value
//! oxigdal rasterize input.geojson output.tif -ts 1024 1024 -burn 255
//!
//! # Burn using attribute value
//! oxigdal rasterize input.geojson output.tif -ts 1024 1024 -a population
//!
//! # All-touched mode
//! oxigdal rasterize input.shp output.tif -ts 512 512 -burn 1 --all-touched
//! ```

use crate::OutputFormat;
use crate::util::progress;
use anyhow::{Context, Result};
use clap::Args;
use console::style;
use oxigdal_core::buffer::RasterBuffer;
use oxigdal_core::types::{GeoTransform, RasterDataType};
use oxigdal_core::vector::geometry::{
    Coordinate, Geometry, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon,
};
use oxigdal_geojson::GeoJsonReader;
use serde::Serialize;
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;

/// Convert vector geometries to raster
#[derive(Args, Debug)]
pub struct RasterizeArgs {
    /// Input vector file
    #[arg(value_name = "INPUT")]
    input: PathBuf,

    /// Output raster file
    #[arg(value_name = "OUTPUT")]
    output: PathBuf,

    /// Output size in pixels (width height)
    #[arg(long = "ts", num_args = 2, value_names = ["WIDTH", "HEIGHT"])]
    target_size: Option<Vec<usize>>,

    /// Output resolution (xres yres)
    #[arg(long = "tr", num_args = 2, value_names = ["XRES", "YRES"])]
    target_resolution: Option<Vec<f64>>,

    /// Output extent (minx miny maxx maxy)
    #[arg(long = "te", num_args = 4, value_names = ["MINX", "MINY", "MAXX", "MAXY"])]
    target_extent: Option<Vec<f64>>,

    /// Fixed value to burn
    #[arg(long)]
    burn: Option<f64>,

    /// Attribute field to use for burn values
    #[arg(short, long)]
    attribute: Option<String>,

    /// Initialization value for raster
    #[arg(long, default_value = "0.0")]
    init: f64,

    /// NoData value
    #[arg(long)]
    no_data: Option<f64>,

    /// Enable all-touched mode (burn all pixels touched by geometry)
    #[arg(long)]
    all_touched: bool,

    /// Add burn value to existing raster values
    #[arg(long)]
    add: bool,

    /// Invert rasterization (burn pixels outside geometries)
    #[arg(long)]
    invert: bool,

    /// Output data type
    #[arg(long, default_value = "uint8")]
    data_type: DataTypeArg,

    /// Overwrite existing output file
    #[arg(long)]
    overwrite: bool,
}

#[derive(Debug, Clone, Copy)]
enum DataTypeArg {
    UInt8,
    UInt16,
    UInt32,
    Int16,
    Int32,
    Float32,
    Float64,
}

impl std::str::FromStr for DataTypeArg {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "uint8" | "byte" => Ok(DataTypeArg::UInt8),
            "uint16" => Ok(DataTypeArg::UInt16),
            "uint32" => Ok(DataTypeArg::UInt32),
            "int16" => Ok(DataTypeArg::Int16),
            "int32" => Ok(DataTypeArg::Int32),
            "float32" => Ok(DataTypeArg::Float32),
            "float64" => Ok(DataTypeArg::Float64),
            _ => Err(format!("Invalid data type: {}", s)),
        }
    }
}

impl From<DataTypeArg> for RasterDataType {
    fn from(arg: DataTypeArg) -> Self {
        match arg {
            DataTypeArg::UInt8 => RasterDataType::UInt8,
            DataTypeArg::UInt16 => RasterDataType::UInt16,
            DataTypeArg::UInt32 => RasterDataType::UInt32,
            DataTypeArg::Int16 => RasterDataType::Int16,
            DataTypeArg::Int32 => RasterDataType::Int32,
            DataTypeArg::Float32 => RasterDataType::Float32,
            DataTypeArg::Float64 => RasterDataType::Float64,
        }
    }
}

#[derive(Serialize)]
struct RasterizeResult {
    input_file: String,
    output_file: String,
    width: usize,
    height: usize,
    features_burned: usize,
    processing_time_ms: u128,
}

pub fn execute(args: RasterizeArgs, format: OutputFormat) -> Result<()> {
    let start = std::time::Instant::now();

    // Validate inputs
    if !args.input.exists() {
        anyhow::bail!("Input file not found: {}", args.input.display());
    }

    if args.output.exists() && !args.overwrite {
        anyhow::bail!(
            "Output file already exists: {}. Use --overwrite to replace.",
            args.output.display()
        );
    }

    if args.burn.is_none() && args.attribute.is_none() {
        anyhow::bail!("Must specify either --burn or --attribute");
    }

    if args.target_size.is_none() && args.target_resolution.is_none() {
        anyhow::bail!("Must specify either --ts (target size) or --tr (target resolution)");
    }

    // Read vector data
    let pb = progress::create_spinner("Reading vector data");
    let file = File::open(&args.input)
        .with_context(|| format!("Failed to open file: {}", args.input.display()))?;
    let buf_reader = BufReader::new(file);
    let mut reader = GeoJsonReader::new(buf_reader);

    let feature_collection = reader
        .read_feature_collection()
        .context("Failed to read vector data")?;

    let feature_count = feature_collection.features.len();
    pb.finish_with_message(format!("Read {} features", feature_count));

    // Determine output extent
    let extent = if let Some(ref te) = args.target_extent {
        if te.len() != 4 {
            anyhow::bail!("Target extent must have 4 values: minx miny maxx maxy");
        }
        (te[0], te[1], te[2], te[3])
    } else {
        // Calculate from feature collection bounds
        let bbox = feature_collection
            .bbox
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Vector file has no bounds and --te not specified"))?;

        if bbox.len() < 4 {
            anyhow::bail!("Invalid bounding box in vector file");
        }

        (bbox[0], bbox[1], bbox[2], bbox[3])
    };

    // Determine output dimensions
    let (width, height) = if let Some(ref ts) = args.target_size {
        if ts.len() != 2 {
            anyhow::bail!("Target size must have 2 values: width height");
        }
        (ts[0], ts[1])
    } else if let Some(ref tr) = args.target_resolution {
        if tr.len() != 2 {
            anyhow::bail!("Target resolution must have 2 values: xres yres");
        }

        let width = ((extent.2 - extent.0) / tr[0]).ceil() as usize;
        let height = ((extent.3 - extent.1) / tr[1]).ceil() as usize;
        (width, height)
    } else {
        unreachable!();
    };

    // Create geotransform
    let pixel_width = (extent.2 - extent.0) / width as f64;
    let pixel_height = -(extent.3 - extent.1) / height as f64; // Negative for north-up

    let geo_transform = GeoTransform {
        origin_x: extent.0,
        pixel_width,
        row_rotation: 0.0,
        origin_y: extent.3,
        col_rotation: 0.0,
        pixel_height,
    };

    // Initialize raster
    let mut raster_data: Vec<f64> = vec![args.init; width * height];

    // Rasterize features
    let pb = progress::create_progress_bar(feature_count as u64, "Rasterizing features");

    let mut features_burned = 0;

    for feature in &feature_collection.features {
        if let Some(ref geom) = feature.geometry {
            // Determine burn value
            let burn_value = if let Some(burn) = args.burn {
                burn
            } else if let Some(ref attr_name) = args.attribute {
                // Get attribute value from properties map
                if let Some(ref props) = feature.properties {
                    if let Some(attr_value) = props.get(attr_name) {
                        // Try to parse as f64
                        match attr_value {
                            serde_json::Value::Number(n) => n.as_f64().ok_or_else(|| {
                                anyhow::anyhow!("Could not convert attribute to number")
                            })?,
                            _ => {
                                anyhow::bail!("Attribute '{}' is not a number", attr_name);
                            }
                        }
                    } else {
                        pb.inc(1);
                        continue; // Skip features without the attribute
                    }
                } else {
                    pb.inc(1);
                    continue; // Skip features with no properties
                }
            } else {
                unreachable!();
            };

            // Convert and rasterize geometry
            let core_geom = convert_geojson_geometry(geom)?;
            let mut params = RasterizeParams {
                raster_data: &mut raster_data,
                width,
                height,
                geo_transform: &geo_transform,
                burn_value,
                all_touched: args.all_touched,
                add: args.add,
            };
            rasterize_geometry(&core_geom, &mut params)?;

            features_burned += 1;
        }

        pb.inc(1);
    }

    pb.finish_with_message(format!("Rasterized {} features", features_burned));

    // Apply invert if requested
    if args.invert {
        let pb = progress::create_spinner("Inverting raster");
        for pixel in &mut raster_data {
            if *pixel == args.init {
                *pixel = args
                    .burn
                    .ok_or_else(|| anyhow::anyhow!("--invert requires --burn to be specified"))?;
            } else {
                *pixel = args.init;
            }
        }
        pb.finish_and_clear();
    }

    // Convert f64 raster data to bytes for the target data type
    let data_type: RasterDataType = args.data_type.into();
    let pixel_count = width * height;
    let mut byte_data: Vec<u8> = Vec::with_capacity(pixel_count * data_type.size_bytes());

    for &value in &raster_data {
        match data_type {
            RasterDataType::UInt8 => byte_data.push(value as u8),
            RasterDataType::Int8 => byte_data.push((value as i8) as u8),
            RasterDataType::UInt16 => {
                byte_data.extend_from_slice(&(value as u16).to_ne_bytes());
            }
            RasterDataType::Int16 => {
                byte_data.extend_from_slice(&(value as i16).to_ne_bytes());
            }
            RasterDataType::UInt32 => {
                byte_data.extend_from_slice(&(value as u32).to_ne_bytes());
            }
            RasterDataType::Int32 => {
                byte_data.extend_from_slice(&(value as i32).to_ne_bytes());
            }
            RasterDataType::Float32 => {
                byte_data.extend_from_slice(&(value as f32).to_ne_bytes());
            }
            RasterDataType::Float64 => {
                byte_data.extend_from_slice(&value.to_ne_bytes());
            }
            _ => {
                anyhow::bail!("Unsupported data type for rasterization: {:?}", data_type);
            }
        }
    }

    // Create RasterBuffer
    let nodata_val = if let Some(nd) = args.no_data {
        match data_type {
            RasterDataType::UInt8
            | RasterDataType::UInt16
            | RasterDataType::UInt32
            | RasterDataType::Int8
            | RasterDataType::Int16
            | RasterDataType::Int32 => oxigdal_core::types::NoDataValue::Integer(nd as i64),
            _ => oxigdal_core::types::NoDataValue::Float(nd),
        }
    } else {
        oxigdal_core::types::NoDataValue::None
    };

    let raster_buffer = RasterBuffer::new(
        byte_data,
        width as u64,
        height as u64,
        data_type,
        nodata_val,
    )
    .context("Failed to create raster buffer")?;

    // Extract CRS from vector file
    let epsg_code = feature_collection
        .crs
        .as_ref()
        .and_then(|crs| crs.epsg_code());

    // Write output
    let pb = progress::create_spinner("Writing output");
    crate::util::raster::write_single_band(
        &args.output,
        &raster_buffer,
        Some(geo_transform),
        epsg_code,
        args.no_data,
    )
    .context("Failed to write output raster")?;
    pb.finish_with_message("Output written successfully");

    // Output results
    let result = RasterizeResult {
        input_file: args.input.display().to_string(),
        output_file: args.output.display().to_string(),
        width,
        height,
        features_burned,
        processing_time_ms: start.elapsed().as_millis(),
    };

    match format {
        OutputFormat::Json => {
            let json =
                serde_json::to_string_pretty(&result).context("Failed to serialize to JSON")?;
            println!("{}", json);
        }
        OutputFormat::Text => {
            println!("{}", style("Rasterization complete").green().bold());
            println!("  Input:    {}", result.input_file);
            println!("  Output:   {}", result.output_file);
            println!("  Size:     {} x {}", result.width, result.height);
            println!("  Features: {}", result.features_burned);
            println!("  Time:     {} ms", result.processing_time_ms);
        }
    }

    Ok(())
}

/// Convert GeoJSON geometry to OxiGDAL core geometry
fn convert_geojson_geometry(geom: &oxigdal_geojson::Geometry) -> Result<Geometry> {
    match geom {
        oxigdal_geojson::Geometry::Point(point) => {
            let coord = convert_position(&point.coordinates)?;
            Ok(Geometry::Point(Point::from_coord(coord)))
        }
        oxigdal_geojson::Geometry::LineString(line) => {
            let coords: Result<Vec<_>> = line
                .coordinates
                .iter()
                .map(|pos| convert_position(pos.as_slice()))
                .collect();
            let line_string = LineString::new(coords?)
                .map_err(|e| anyhow::anyhow!("Failed to create LineString: {}", e))?;
            Ok(Geometry::LineString(line_string))
        }
        oxigdal_geojson::Geometry::Polygon(poly) => {
            if poly.coordinates.is_empty() {
                anyhow::bail!("Polygon has no coordinates");
            }

            let exterior_coords: Result<Vec<_>> = poly.coordinates[0]
                .iter()
                .map(|pos| convert_position(pos.as_slice()))
                .collect();
            let exterior = LineString::new(exterior_coords?)
                .map_err(|e| anyhow::anyhow!("Failed to create exterior ring: {}", e))?;

            let mut interiors = Vec::new();
            for interior_ring in &poly.coordinates[1..] {
                let interior_coords: Result<Vec<_>> = interior_ring
                    .iter()
                    .map(|pos| convert_position(pos.as_slice()))
                    .collect();
                let interior = LineString::new(interior_coords?)
                    .map_err(|e| anyhow::anyhow!("Failed to create interior ring: {}", e))?;
                interiors.push(interior);
            }

            let polygon = Polygon::new(exterior, interiors)
                .map_err(|e| anyhow::anyhow!("Failed to create Polygon: {}", e))?;
            Ok(Geometry::Polygon(polygon))
        }
        oxigdal_geojson::Geometry::MultiPoint(mp) => {
            let points: Result<Vec<_>> = mp
                .coordinates
                .iter()
                .map(|pos| {
                    let coord = convert_position(pos.as_slice())?;
                    Ok(Point::from_coord(coord))
                })
                .collect();
            Ok(Geometry::MultiPoint(MultiPoint::new(points?)))
        }
        oxigdal_geojson::Geometry::MultiLineString(mls) => {
            let line_strings: Result<Vec<_>> = mls
                .coordinates
                .iter()
                .map(|line_coords| {
                    let coords: Result<Vec<_>> = line_coords
                        .iter()
                        .map(|pos| convert_position(pos.as_slice()))
                        .collect();
                    LineString::new(coords?)
                        .map_err(|e| anyhow::anyhow!("Failed to create LineString: {}", e))
                })
                .collect();
            Ok(Geometry::MultiLineString(MultiLineString::new(
                line_strings?,
            )))
        }
        oxigdal_geojson::Geometry::MultiPolygon(mp) => {
            let polygons: Result<Vec<_>> = mp
                .coordinates
                .iter()
                .map(|poly_coords| {
                    if poly_coords.is_empty() {
                        anyhow::bail!("Polygon in MultiPolygon has no coordinates");
                    }

                    let exterior_coords: Result<Vec<_>> = poly_coords[0]
                        .iter()
                        .map(|pos| convert_position(pos.as_slice()))
                        .collect();
                    let exterior = LineString::new(exterior_coords?)
                        .map_err(|e| anyhow::anyhow!("Failed to create exterior ring: {}", e))?;

                    let mut interiors = Vec::new();
                    for interior_ring in &poly_coords[1..] {
                        let interior_coords: Result<Vec<_>> = interior_ring
                            .iter()
                            .map(|pos| convert_position(pos.as_slice()))
                            .collect();
                        let interior = LineString::new(interior_coords?).map_err(|e| {
                            anyhow::anyhow!("Failed to create interior ring: {}", e)
                        })?;
                        interiors.push(interior);
                    }

                    Polygon::new(exterior, interiors)
                        .map_err(|e| anyhow::anyhow!("Failed to create Polygon: {}", e))
                })
                .collect();
            Ok(Geometry::MultiPolygon(MultiPolygon::new(polygons?)))
        }
        oxigdal_geojson::Geometry::GeometryCollection(gc) => {
            let geometries: Result<Vec<_>> =
                gc.geometries.iter().map(convert_geojson_geometry).collect();
            Ok(Geometry::GeometryCollection(
                oxigdal_core::vector::geometry::GeometryCollection::new(geometries?),
            ))
        }
    }
}

/// Convert GeoJSON position to OxiGDAL coordinate
fn convert_position(pos: &[f64]) -> Result<Coordinate> {
    if pos.len() < 2 {
        anyhow::bail!("Position must have at least 2 coordinates");
    }

    let coord = if pos.len() >= 3 {
        Coordinate::new_3d(pos[0], pos[1], pos[2])
    } else {
        Coordinate::new_2d(pos[0], pos[1])
    };

    Ok(coord)
}

/// Parameters for rasterization operations
struct RasterizeParams<'a> {
    raster_data: &'a mut [f64],
    width: usize,
    height: usize,
    geo_transform: &'a GeoTransform,
    burn_value: f64,
    all_touched: bool,
    add: bool,
}

/// Rasterize a single geometry into the raster data
fn rasterize_geometry(geometry: &Geometry, params: &mut RasterizeParams) -> Result<()> {
    match geometry {
        Geometry::Point(point) => {
            let (px, py) = geo_to_pixel(
                point.coord.x,
                point.coord.y,
                params.geo_transform,
                params.width,
                params.height,
            )?;
            if px < params.width && py < params.height {
                let idx = py * params.width + px;
                if params.add {
                    params.raster_data[idx] += params.burn_value;
                } else {
                    params.raster_data[idx] = params.burn_value;
                }
            }
        }
        Geometry::LineString(line) => {
            rasterize_line_string(
                &line.coords,
                params.raster_data,
                params.width,
                params.height,
                params.geo_transform,
                params.burn_value,
                params.add,
            )?;
        }
        Geometry::Polygon(poly) => {
            let mut poly_params = PolygonRasterParams {
                raster_data: params.raster_data,
                width: params.width,
                height: params.height,
                geo_transform: params.geo_transform,
                burn_value: params.burn_value,
                _all_touched: params.all_touched,
                add: params.add,
            };
            rasterize_polygon(&poly.exterior.coords, &poly.interiors, &mut poly_params)?;
        }
        Geometry::MultiPoint(mp) => {
            for point in &mp.points {
                let (px, py) = geo_to_pixel(
                    point.coord.x,
                    point.coord.y,
                    params.geo_transform,
                    params.width,
                    params.height,
                )?;
                if px < params.width && py < params.height {
                    let idx = py * params.width + px;
                    if params.add {
                        params.raster_data[idx] += params.burn_value;
                    } else {
                        params.raster_data[idx] = params.burn_value;
                    }
                }
            }
        }
        Geometry::MultiLineString(mls) => {
            for line in &mls.line_strings {
                rasterize_line_string(
                    &line.coords,
                    params.raster_data,
                    params.width,
                    params.height,
                    params.geo_transform,
                    params.burn_value,
                    params.add,
                )?;
            }
        }
        Geometry::MultiPolygon(mp) => {
            for poly in &mp.polygons {
                let mut poly_params = PolygonRasterParams {
                    raster_data: params.raster_data,
                    width: params.width,
                    height: params.height,
                    geo_transform: params.geo_transform,
                    burn_value: params.burn_value,
                    _all_touched: params.all_touched,
                    add: params.add,
                };
                rasterize_polygon(&poly.exterior.coords, &poly.interiors, &mut poly_params)?;
            }
        }
        Geometry::GeometryCollection(gc) => {
            for geom in &gc.geometries {
                rasterize_geometry(geom, params)?;
            }
        }
    }

    Ok(())
}

/// Convert geographic coordinates to pixel coordinates
fn geo_to_pixel(
    x: f64,
    y: f64,
    gt: &GeoTransform,
    width: usize,
    height: usize,
) -> Result<(usize, usize)> {
    let px = ((x - gt.origin_x) / gt.pixel_width) as isize;
    let py = ((y - gt.origin_y) / gt.pixel_height) as isize;

    if px >= 0 && py >= 0 && (px as usize) < width && (py as usize) < height {
        Ok((px as usize, py as usize))
    } else {
        Ok((usize::MAX, usize::MAX)) // Out of bounds
    }
}

/// Rasterize a line string using Bresenham's algorithm
fn rasterize_line_string(
    coords: &[oxigdal_core::vector::geometry::Coordinate],
    raster_data: &mut [f64],
    width: usize,
    height: usize,
    geo_transform: &GeoTransform,
    burn_value: f64,
    add: bool,
) -> Result<()> {
    for window in coords.windows(2) {
        let (x0, y0) = geo_to_pixel(window[0].x, window[0].y, geo_transform, width, height)?;
        let (x1, y1) = geo_to_pixel(window[1].x, window[1].y, geo_transform, width, height)?;

        if x0 == usize::MAX || x1 == usize::MAX {
            continue; // Skip out of bounds
        }

        // Bresenham's line algorithm
        let mut params = LineRasterParams {
            raster_data,
            width,
            height,
            burn_value,
            add,
        };
        bresenham_line(x0, y0, x1, y1, &mut params);
    }

    Ok(())
}

/// Parameters for line rasterization
struct LineRasterParams<'a> {
    raster_data: &'a mut [f64],
    width: usize,
    height: usize,
    burn_value: f64,
    add: bool,
}

/// Bresenham's line drawing algorithm
fn bresenham_line(x0: usize, y0: usize, x1: usize, y1: usize, params: &mut LineRasterParams) {
    let dx = (x1 as isize - x0 as isize).abs();
    let dy = -(y1 as isize - y0 as isize).abs();
    let sx = if x0 < x1 { 1 } else { -1 };
    let sy = if y0 < y1 { 1 } else { -1 };
    let mut err = dx + dy;

    let mut x = x0 as isize;
    let mut y = y0 as isize;

    loop {
        if x >= 0 && y >= 0 && (x as usize) < params.width && (y as usize) < params.height {
            let idx = (y as usize) * params.width + (x as usize);
            if params.add {
                params.raster_data[idx] += params.burn_value;
            } else {
                params.raster_data[idx] = params.burn_value;
            }
        }

        if x == x1 as isize && y == y1 as isize {
            break;
        }

        let e2 = 2 * err;

        if e2 >= dy {
            err += dy;
            x += sx;
        }

        if e2 <= dx {
            err += dx;
            y += sy;
        }
    }
}

/// Parameters for polygon rasterization
struct PolygonRasterParams<'a> {
    raster_data: &'a mut [f64],
    width: usize,
    height: usize,
    geo_transform: &'a GeoTransform,
    burn_value: f64,
    _all_touched: bool,
    add: bool,
}

/// Edge structure for scanline algorithm
#[derive(Debug, Clone)]
struct Edge {
    /// Y coordinate of the lower vertex (in pixel space)
    y_min: f64,
    /// Y coordinate of the upper vertex (in pixel space)
    y_max: f64,
    /// X coordinate at y_min
    x_at_y_min: f64,
    /// Inverse slope (dx/dy)
    inv_slope: f64,
}

impl Edge {
    /// Creates a new edge from two coordinates in pixel space
    fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Option<Self> {
        // Skip horizontal edges
        if (y1 - y0).abs() < f64::EPSILON {
            return None;
        }

        let (y_min, y_max, x_at_y_min) = if y0 < y1 { (y0, y1, x0) } else { (y1, y0, x1) };

        let inv_slope = (x1 - x0) / (y1 - y0);

        Some(Self {
            y_min,
            y_max,
            x_at_y_min,
            inv_slope,
        })
    }

    /// Get x coordinate at a given y
    fn x_at(&self, y: f64) -> f64 {
        self.x_at_y_min + (y - self.y_min) * self.inv_slope
    }
}

/// Collect edges from a ring of coordinates
fn collect_edges_from_ring(
    coords: &[oxigdal_core::vector::geometry::Coordinate],
    geo_transform: &GeoTransform,
    _width: usize,
    height: usize,
) -> Vec<Edge> {
    let mut edges = Vec::new();

    if coords.len() < 3 {
        return edges;
    }

    for i in 0..coords.len() {
        let j = (i + 1) % coords.len();

        // Convert to pixel coordinates
        let (px0, py0) = geo_to_pixel_f64(coords[i].x, coords[i].y, geo_transform);
        let (px1, py1) = geo_to_pixel_f64(coords[j].x, coords[j].y, geo_transform);

        // Clip edges to raster bounds (with some margin)
        let y_min = py0.min(py1);
        let y_max = py0.max(py1);

        // Skip if completely outside vertical bounds
        if y_max < 0.0 || y_min >= height as f64 {
            continue;
        }

        if let Some(edge) = Edge::new(px0, py0, px1, py1) {
            edges.push(edge);
        }
    }

    edges
}

/// Convert geographic coordinates to pixel coordinates (floating point)
fn geo_to_pixel_f64(x: f64, y: f64, gt: &GeoTransform) -> (f64, f64) {
    let px = (x - gt.origin_x) / gt.pixel_width;
    let py = (y - gt.origin_y) / gt.pixel_height;
    (px, py)
}

/// Rasterize a polygon using scanline algorithm with even-odd fill rule
///
/// This implementation uses the scanline algorithm with an Active Edge Table (AET)
/// to efficiently rasterize polygons. The even-odd fill rule is used to correctly
/// handle holes in polygons.
fn rasterize_polygon(
    exterior: &[oxigdal_core::vector::geometry::Coordinate],
    interiors: &[LineString],
    params: &mut PolygonRasterParams,
) -> Result<()> {
    // Collect all edges from exterior and interior rings
    let mut all_edges: Vec<Edge> = Vec::new();

    // Add edges from exterior ring
    all_edges.extend(collect_edges_from_ring(
        exterior,
        params.geo_transform,
        params.width,
        params.height,
    ));

    // Add edges from interior rings (holes)
    // The even-odd rule will automatically handle the holes
    for interior in interiors {
        all_edges.extend(collect_edges_from_ring(
            &interior.coords,
            params.geo_transform,
            params.width,
            params.height,
        ));
    }

    if all_edges.is_empty() {
        return Ok(());
    }

    // Find the scanline range
    let y_min = all_edges
        .iter()
        .map(|e| e.y_min.floor() as isize)
        .min()
        .unwrap_or(0);
    let y_max = all_edges
        .iter()
        .map(|e| e.y_max.ceil() as isize)
        .max()
        .unwrap_or(0);

    let scanline_start = y_min.max(0) as usize;
    let scanline_end = (y_max as usize).min(params.height);

    // Process each scanline
    for scanline in scanline_start..scanline_end {
        let y = scanline as f64 + 0.5; // Sample at pixel center

        // Find all edges that intersect this scanline
        let mut intersections: Vec<f64> = all_edges
            .iter()
            .filter(|edge| edge.y_min <= y && edge.y_max > y)
            .map(|edge| edge.x_at(y))
            .collect();

        // Sort intersections by x coordinate
        intersections.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        // Apply even-odd fill rule: fill between pairs of intersections
        for chunk in intersections.chunks_exact(2) {
            let x_start = chunk[0].floor() as isize;
            let x_end = chunk[1].ceil() as isize;

            // Fill pixels between this pair of intersections
            let pixel_start = x_start.max(0) as usize;
            let pixel_end = (x_end as usize).min(params.width);

            for x in pixel_start..pixel_end {
                let idx = scanline * params.width + x;
                if idx < params.raster_data.len() {
                    if params.add {
                        params.raster_data[idx] += params.burn_value;
                    } else {
                        params.raster_data[idx] = params.burn_value;
                    }
                }
            }
        }

        // Handle all-touched mode: also burn edge pixels
        if params._all_touched {
            for edge in &all_edges {
                if edge.y_min <= y && edge.y_max > y {
                    let x = edge.x_at(y);
                    let x_floor = x.floor() as isize;
                    let x_ceil = x.ceil() as isize;

                    for px in [x_floor, x_ceil] {
                        if px >= 0 && (px as usize) < params.width {
                            let idx = scanline * params.width + px as usize;
                            if idx < params.raster_data.len() {
                                if params.add {
                                    params.raster_data[idx] += params.burn_value;
                                } else {
                                    params.raster_data[idx] = params.burn_value;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

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

    #[test]
    fn test_data_type_parsing() {
        use std::str::FromStr;

        assert!(matches!(
            DataTypeArg::from_str("uint8"),
            Ok(DataTypeArg::UInt8)
        ));
        assert!(matches!(
            DataTypeArg::from_str("byte"),
            Ok(DataTypeArg::UInt8)
        ));
        assert!(matches!(
            DataTypeArg::from_str("float32"),
            Ok(DataTypeArg::Float32)
        ));
        assert!(DataTypeArg::from_str("invalid").is_err());
    }

    #[test]
    fn test_edge_creation() {
        // Vertical edge
        let edge = Edge::new(5.0, 0.0, 5.0, 10.0);
        assert!(edge.is_some());
        let e = edge.expect("should create edge");
        assert_eq!(e.y_min, 0.0);
        assert_eq!(e.y_max, 10.0);
        assert_eq!(e.x_at_y_min, 5.0);
        assert_eq!(e.inv_slope, 0.0);

        // Diagonal edge
        let edge2 = Edge::new(0.0, 0.0, 10.0, 10.0);
        assert!(edge2.is_some());
        let e2 = edge2.expect("should create edge");
        assert_eq!(e2.x_at(5.0), 5.0);

        // Horizontal edge should be None
        let horizontal = Edge::new(0.0, 5.0, 10.0, 5.0);
        assert!(horizontal.is_none());
    }

    #[test]
    fn test_edge_x_interpolation() {
        // 45-degree line from (0,0) to (10,10)
        let edge = Edge::new(0.0, 0.0, 10.0, 10.0).expect("valid edge");

        assert_eq!(edge.x_at(0.0), 0.0);
        assert_eq!(edge.x_at(5.0), 5.0);
        assert_eq!(edge.x_at(10.0), 10.0);

        // Steeper slope: from (0,0) to (5,10)
        let steep = Edge::new(0.0, 0.0, 5.0, 10.0).expect("valid edge");
        assert_eq!(steep.x_at(0.0), 0.0);
        assert_eq!(steep.x_at(10.0), 5.0);
        assert_eq!(steep.x_at(5.0), 2.5);
    }

    #[test]
    fn test_geo_to_pixel_f64() {
        let gt = GeoTransform {
            origin_x: 0.0,
            origin_y: 100.0,
            pixel_width: 1.0,
            pixel_height: -1.0,
            row_rotation: 0.0,
            col_rotation: 0.0,
        };

        let (px, py) = geo_to_pixel_f64(50.0, 50.0, &gt);
        assert_eq!(px, 50.0);
        assert_eq!(py, 50.0);

        let (px2, py2) = geo_to_pixel_f64(0.0, 100.0, &gt);
        assert_eq!(px2, 0.0);
        assert_eq!(py2, 0.0);
    }

    #[test]
    fn test_simple_polygon_rasterization() {
        // Create a simple square polygon: (10,10) to (90,90) in a 100x100 raster
        let exterior = vec![
            Coordinate::new_2d(10.0, 90.0),
            Coordinate::new_2d(90.0, 90.0),
            Coordinate::new_2d(90.0, 10.0),
            Coordinate::new_2d(10.0, 10.0),
            Coordinate::new_2d(10.0, 90.0), // Close the ring
        ];

        let mut raster_data = vec![0.0; 100 * 100];
        let geo_transform = GeoTransform {
            origin_x: 0.0,
            origin_y: 100.0,
            pixel_width: 1.0,
            pixel_height: -1.0,
            row_rotation: 0.0,
            col_rotation: 0.0,
        };

        let mut params = PolygonRasterParams {
            raster_data: &mut raster_data,
            width: 100,
            height: 100,
            geo_transform: &geo_transform,
            burn_value: 1.0,
            _all_touched: false,
            add: false,
        };

        let result = rasterize_polygon(&exterior, &[], &mut params);
        assert!(result.is_ok());

        // Check that pixels inside the polygon are burned
        let center_idx = 50 * 100 + 50;
        assert_eq!(raster_data[center_idx], 1.0);

        // Check that pixels outside the polygon are not burned
        let outside_idx = 5 * 100 + 5;
        assert_eq!(raster_data[outside_idx], 0.0);
    }

    #[test]
    fn test_polygon_with_hole_rasterization() {
        // Create a square polygon with a hole
        // Outer square: (10,10) to (90,90)
        let exterior = vec![
            Coordinate::new_2d(10.0, 90.0),
            Coordinate::new_2d(90.0, 90.0),
            Coordinate::new_2d(90.0, 10.0),
            Coordinate::new_2d(10.0, 10.0),
            Coordinate::new_2d(10.0, 90.0),
        ];

        // Inner hole: (40,40) to (60,60)
        let hole_coords = vec![
            Coordinate::new_2d(40.0, 60.0),
            Coordinate::new_2d(60.0, 60.0),
            Coordinate::new_2d(60.0, 40.0),
            Coordinate::new_2d(40.0, 40.0),
            Coordinate::new_2d(40.0, 60.0),
        ];
        let hole = LineString::new(hole_coords).expect("valid hole ring");

        let mut raster_data = vec![0.0; 100 * 100];
        let geo_transform = GeoTransform {
            origin_x: 0.0,
            origin_y: 100.0,
            pixel_width: 1.0,
            pixel_height: -1.0,
            row_rotation: 0.0,
            col_rotation: 0.0,
        };

        let mut params = PolygonRasterParams {
            raster_data: &mut raster_data,
            width: 100,
            height: 100,
            geo_transform: &geo_transform,
            burn_value: 1.0,
            _all_touched: false,
            add: false,
        };

        let result = rasterize_polygon(&exterior, &[hole], &mut params);
        assert!(result.is_ok());

        // Check that pixels inside the polygon (but outside the hole) are burned
        let inside_idx = 20 * 100 + 20;
        assert_eq!(raster_data[inside_idx], 1.0);

        // Check that pixels inside the hole are NOT burned (even-odd rule)
        let hole_center_idx = 50 * 100 + 50;
        assert_eq!(raster_data[hole_center_idx], 0.0);

        // Check that pixels outside the polygon are not burned
        let outside_idx = 5 * 100 + 5;
        assert_eq!(raster_data[outside_idx], 0.0);
    }

    #[test]
    fn test_polygon_add_mode() {
        // Test that add mode accumulates values
        let exterior = vec![
            Coordinate::new_2d(10.0, 90.0),
            Coordinate::new_2d(90.0, 90.0),
            Coordinate::new_2d(90.0, 10.0),
            Coordinate::new_2d(10.0, 10.0),
            Coordinate::new_2d(10.0, 90.0),
        ];

        let mut raster_data = vec![5.0; 100 * 100]; // Pre-fill with 5.0
        let geo_transform = GeoTransform {
            origin_x: 0.0,
            origin_y: 100.0,
            pixel_width: 1.0,
            pixel_height: -1.0,
            row_rotation: 0.0,
            col_rotation: 0.0,
        };

        let mut params = PolygonRasterParams {
            raster_data: &mut raster_data,
            width: 100,
            height: 100,
            geo_transform: &geo_transform,
            burn_value: 3.0,
            _all_touched: false,
            add: true, // Add mode
        };

        let result = rasterize_polygon(&exterior, &[], &mut params);
        assert!(result.is_ok());

        // Check that pixels inside have accumulated value (5 + 3 = 8)
        let center_idx = 50 * 100 + 50;
        assert_eq!(raster_data[center_idx], 8.0);

        // Check that pixels outside still have original value
        let outside_idx = 5 * 100 + 5;
        assert_eq!(raster_data[outside_idx], 5.0);
    }

    #[test]
    fn test_collect_edges_from_ring() {
        let coords = vec![
            Coordinate::new_2d(0.0, 100.0),
            Coordinate::new_2d(100.0, 100.0),
            Coordinate::new_2d(100.0, 0.0),
            Coordinate::new_2d(0.0, 0.0),
            Coordinate::new_2d(0.0, 100.0),
        ];

        let geo_transform = GeoTransform {
            origin_x: 0.0,
            origin_y: 100.0,
            pixel_width: 1.0,
            pixel_height: -1.0,
            row_rotation: 0.0,
            col_rotation: 0.0,
        };

        let edges = collect_edges_from_ring(&coords, &geo_transform, 100, 100);

        // Should have 4 edges (square has 4 sides, but 2 are horizontal and skipped)
        // Actually, with pixel_height = -1.0, we get vertical edges on left and right
        assert!(!edges.is_empty());
    }

    #[test]
    fn test_triangle_polygon_rasterization() {
        // Create a triangle to test non-rectangular shapes
        let exterior = vec![
            Coordinate::new_2d(50.0, 90.0), // Top vertex
            Coordinate::new_2d(90.0, 10.0), // Bottom right
            Coordinate::new_2d(10.0, 10.0), // Bottom left
            Coordinate::new_2d(50.0, 90.0), // Close the ring
        ];

        let mut raster_data = vec![0.0; 100 * 100];
        let geo_transform = GeoTransform {
            origin_x: 0.0,
            origin_y: 100.0,
            pixel_width: 1.0,
            pixel_height: -1.0,
            row_rotation: 0.0,
            col_rotation: 0.0,
        };

        let mut params = PolygonRasterParams {
            raster_data: &mut raster_data,
            width: 100,
            height: 100,
            geo_transform: &geo_transform,
            burn_value: 1.0,
            _all_touched: false,
            add: false,
        };

        let result = rasterize_polygon(&exterior, &[], &mut params);
        assert!(result.is_ok());

        // Check that centroid area is burned
        let center_idx = 50 * 100 + 50;
        assert_eq!(raster_data[center_idx], 1.0);

        // Check that top-left corner (outside triangle) is not burned
        let outside_idx = 15 * 100 + 15;
        assert_eq!(raster_data[outside_idx], 0.0);
    }

    #[test]
    fn test_empty_polygon() {
        // Test that empty polygon doesn't cause issues
        let exterior: Vec<Coordinate> = vec![];

        let mut raster_data = vec![0.0; 100 * 100];
        let geo_transform = GeoTransform {
            origin_x: 0.0,
            origin_y: 100.0,
            pixel_width: 1.0,
            pixel_height: -1.0,
            row_rotation: 0.0,
            col_rotation: 0.0,
        };

        let mut params = PolygonRasterParams {
            raster_data: &mut raster_data,
            width: 100,
            height: 100,
            geo_transform: &geo_transform,
            burn_value: 1.0,
            _all_touched: false,
            add: false,
        };

        let result = rasterize_polygon(&exterior, &[], &mut params);
        assert!(result.is_ok());

        // All pixels should remain 0
        assert!(raster_data.iter().all(|&v| v == 0.0));
    }

    #[test]
    fn test_polygon_outside_raster_bounds() {
        // Create a polygon completely outside the raster bounds
        let exterior = vec![
            Coordinate::new_2d(200.0, 300.0),
            Coordinate::new_2d(300.0, 300.0),
            Coordinate::new_2d(300.0, 200.0),
            Coordinate::new_2d(200.0, 200.0),
            Coordinate::new_2d(200.0, 300.0),
        ];

        let mut raster_data = vec![0.0; 100 * 100];
        let geo_transform = GeoTransform {
            origin_x: 0.0,
            origin_y: 100.0,
            pixel_width: 1.0,
            pixel_height: -1.0,
            row_rotation: 0.0,
            col_rotation: 0.0,
        };

        let mut params = PolygonRasterParams {
            raster_data: &mut raster_data,
            width: 100,
            height: 100,
            geo_transform: &geo_transform,
            burn_value: 1.0,
            _all_touched: false,
            add: false,
        };

        let result = rasterize_polygon(&exterior, &[], &mut params);
        assert!(result.is_ok());

        // All pixels should remain 0
        assert!(raster_data.iter().all(|&v| v == 0.0));
    }

    #[test]
    fn test_all_touched_mode() {
        // Create a small polygon that tests all-touched mode
        let exterior = vec![
            Coordinate::new_2d(45.5, 55.5),
            Coordinate::new_2d(55.5, 55.5),
            Coordinate::new_2d(55.5, 45.5),
            Coordinate::new_2d(45.5, 45.5),
            Coordinate::new_2d(45.5, 55.5),
        ];

        let mut raster_data = vec![0.0; 100 * 100];
        let geo_transform = GeoTransform {
            origin_x: 0.0,
            origin_y: 100.0,
            pixel_width: 1.0,
            pixel_height: -1.0,
            row_rotation: 0.0,
            col_rotation: 0.0,
        };

        let mut params = PolygonRasterParams {
            raster_data: &mut raster_data,
            width: 100,
            height: 100,
            geo_transform: &geo_transform,
            burn_value: 1.0,
            _all_touched: true, // All-touched mode
            add: false,
        };

        let result = rasterize_polygon(&exterior, &[], &mut params);
        assert!(result.is_ok());

        // Check that center is burned
        let center_idx = 50 * 100 + 50;
        assert_eq!(raster_data[center_idx], 1.0);

        // In all-touched mode, edge pixels should also be burned
        let edge_idx = 45 * 100 + 45;
        assert_eq!(raster_data[edge_idx], 1.0);
    }
}