rmpca 0.2.0

Enterprise-grade unified CLI for rmp.ca operations - Rust port
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
//! Validate command: Validate GeoJSON file structure and geometry
//!
//! This command validates that a GeoJSON file has the correct
//! structure and valid geometries.

use crate::config::Config;
use anyhow::{Context, Result};
use clap::Args as ClapArgs;
use geojson::{GeoJson, Value};
use std::path::PathBuf;

/// Validate GeoJSON via remote API
///
/// Sends the GeoJSON to the backend validation endpoint for server-side
/// validation that may include topology checks, CRS verification,
/// and OSM conformance checks.
async fn validate_remote(geojson_str: &str, config: &Config) -> Result<String> {
    let client = reqwest::Client::new();
    let url = format!("{}/api/v1/validate", config.backend_url());

    tracing::info!("Sending GeoJSON to remote validation: {}", url);

    let response = client
        .post(&url)
        .header("Content-Type", "application/json")
        .timeout(std::time::Duration::from_secs(config.timeout_secs))
        .body(geojson_str.to_string())
        .send()
        .await
        .context("Failed to connect to remote validation server")?;

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await.unwrap_or_default();
        anyhow::bail!(
            "Remote validation server returned {}: {}",
            status,
            body.chars().take(200).collect::<String>()
        );
    }

    let result: serde_json::Value = response
        .json()
        .await
        .context("Failed to parse remote validation response")?;

    // Format the response
    let valid = result.get("valid").and_then(|v| v.as_bool()).unwrap_or(false);
    let errors = result.get("errors")
        .and_then(|e| e.as_array())
        .map(|arr| arr.len())
        .unwrap_or(0);
    let warnings = result.get("warnings")
        .and_then(|w| w.as_array())
        .map(|arr| arr.len())
        .unwrap_or(0);

    if valid {
        Ok(format!("VALID (remote: 0 errors, {} warnings)", warnings))
    } else {
        Ok(format!("INVALID (remote: {} errors, {} warnings)", errors, warnings))
    }
}

#[derive(Debug, ClapArgs)]
pub struct Args {
    /// Input GeoJSON file
    pub input: PathBuf,

    /// Validate via remote API
    #[arg(long)]
    pub remote: bool,

    /// Verbose output
    #[arg(short, long)]
    pub verbose: bool,
}

#[derive(Default)]
struct ValidationStats {
    total_features: usize,
    valid_features: usize,
    errors: Vec<String>,
    warnings: Vec<String>,
}

impl ValidationStats {
    fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }
}

/// Validate a coordinate: lat in [-90, 90], lon in [-180, 180]
fn validate_coordinate(coord: &[f64]) -> Vec<String> {
    let mut errors = Vec::new();
    if coord.len() < 2 {
        errors.push("Coordinate has fewer than 2 dimensions".to_string());
        return errors;
    }
    let lon = coord[0];
    let lat = coord[1];
    if !(-180.0..=180.0).contains(&lon) {
        errors.push(format!("Longitude {} out of range [-180, 180]", lon));
    }
    if !(-90.0..=90.0).contains(&lat) {
        errors.push(format!("Latitude {} out of range [-90, 90]", lat));
    }
    errors
}

/// Validate a LineString geometry
fn validate_linestring(coords: &[Vec<f64>]) -> Vec<String> {
    let mut errors = Vec::new();
    if coords.len() < 2 {
        errors.push("LineString must have at least 2 coordinates".to_string());
        return errors;
    }
    for (i, coord) in coords.iter().enumerate() {
        for err in validate_coordinate(coord) {
            errors.push(format!("Coordinate {}: {}", i, err));
        }
    }
    // Check for consecutive duplicate coordinates
    for i in 0..coords.len().saturating_sub(1) {
        if coords[i].len() >= 2 && coords[i + 1].len() >= 2 {
            let dlat = (coords[i][1] - coords[i + 1][1]).abs();
            let dlon = (coords[i][0] - coords[i + 1][0]).abs();
            if dlat < 1e-12 && dlon < 1e-12 {
                errors.push(format!(
                    "Consecutive duplicate coordinates at index {}",
                    i
                ));
            }
        }
    }
    errors
}

/// Validate a Polygon geometry
fn validate_polygon(rings: &[Vec<Vec<f64>>]) -> Vec<String> {
    let mut errors = Vec::new();
    if rings.is_empty() {
        errors.push("Polygon must have at least one ring".to_string());
        return errors;
    }
    for (ri, ring) in rings.iter().enumerate() {
        if ring.len() < 4 {
            errors.push(format!(
                "Ring {} must have at least 4 coordinates (closed ring)",
                ri
            ));
        }
        // Check ring is closed
        if ring.len() >= 2 {
            let first = &ring[0];
            let last = &ring[ring.len() - 1];
            if first.len() >= 2 && last.len() >= 2 {
                let dlat = (first[1] - last[1]).abs();
                let dlon = (first[0] - last[0]).abs();
                if dlat > 1e-9 || dlon > 1e-9 {
                    errors.push(format!("Ring {} is not closed", ri));
                }
            }
        }
        for (i, coord) in ring.iter().enumerate() {
            for err in validate_coordinate(coord) {
                errors.push(format!("Ring {} coord {}: {}", ri, i, err));
            }
        }
    }
    errors
}

/// Validate GeoJSON structure and geometry
pub async fn run(args: Args) -> Result<()> {
    let config = Config::load().unwrap_or_default();
    config.init_logging();

    tracing::info!("Validating GeoJSON: {}", args.input.display());

    let geojson_str = std::fs::read_to_string(&args.input)
        .with_context(|| format!("Failed to read {}", args.input.display()))?;

    // Parse JSON first
    let json_value: serde_json::Value = serde_json::from_str(&geojson_str)
        .context("File is not valid JSON")?;

    // Try to parse as GeoJSON
    let geojson: GeoJson = geojson_str.parse()
        .context("File is not valid GeoJSON")?;

    let mut stats = ValidationStats::default();

    match &geojson {
        GeoJson::FeatureCollection(fc) => {
            stats.total_features = fc.features.len();
            if args.verbose {
                println!("FeatureCollection with {} features", fc.features.len());
            }

            for (i, feature) in fc.features.iter().enumerate() {
                let mut feature_valid = true;

                // Check feature has geometry
                let geom = match feature.geometry.as_ref() {
                    Some(g) => g,
                    None => {
                        stats.warnings.push(format!("Feature {}: No geometry", i));
                        continue;
                    }
                };

                // Validate geometry
                let geom_errors = match &geom.value {
                    Value::Point(coord) => validate_coordinate(coord),
                    Value::MultiPoint(coords) => {
                        let mut errs = Vec::new();
                        for (j, c) in coords.iter().enumerate() {
                            for err in validate_coordinate(c) {
                                errs.push(format!("Point {}: {}", j, err));
                            }
                        }
                        errs
                    }
                    Value::LineString(coords) => validate_linestring(coords),
                    Value::MultiLineString(lines) => {
                        let mut errs = Vec::new();
                        for (j, line) in lines.iter().enumerate() {
                            for err in validate_linestring(line) {
                                errs.push(format!("Line {}: {}", j, err));
                            }
                        }
                        errs
                    }
                    Value::Polygon(rings) => validate_polygon(rings),
                    Value::MultiPolygon(polygons) => {
                        let mut errs = Vec::new();
                        for (j, poly) in polygons.iter().enumerate() {
                            for err in validate_polygon(poly) {
                                errs.push(format!("Polygon {}: {}", j, err));
                            }
                        }
                        errs
                    }
                    Value::GeometryCollection(geoms) => {
                        stats.warnings.push(format!(
                            "Feature {}: GeometryCollection with {} geometries",
                            i,
                            geoms.len()
                        ));
                        Vec::new()
                    }
                };

                if !geom_errors.is_empty() {
                    feature_valid = false;
                    for err in &geom_errors {
                        stats.errors.push(format!("Feature {}: {}", i, err));
                    }
                }

                // Check properties
                if feature.properties.is_none() && args.verbose {
                    stats.warnings.push(format!("Feature {}: No properties", i));
                }

                if feature_valid {
                    stats.valid_features += 1;
                }
            }
        }
        GeoJson::Feature(f) => {
            stats.total_features = 1;
            if f.geometry.is_some() {
                stats.valid_features = 1;
            } else {
                stats.errors.push("Feature has no geometry".to_string());
            }
        }
        GeoJson::Geometry(_) => {
            stats.warnings.push("Top-level Geometry (not a FeatureCollection)".to_string());
            stats.total_features = 1;
            stats.valid_features = 1;
        }
    }

    // Output results
    if args.verbose {
        println!("\nValidation Results:");
        println!("  Total features:  {}", stats.total_features);
        println!("  Valid features:  {}", stats.valid_features);
        println!("  Errors:          {}", stats.errors.len());
        println!("  Warnings:        {}", stats.warnings.len());

        if !stats.errors.is_empty() {
            println!("\nErrors:");
            for err in &stats.errors {
                println!("  - {}", err);
            }
        }

        if !stats.warnings.is_empty() {
            println!("\nWarnings:");
            for warn in &stats.warnings {
                println!("  - {}", warn);
            }
        }
    }

    if stats.is_valid() {
        tracing::info!(
            "Validation passed: {}/{} features valid",
            stats.valid_features,
            stats.total_features
        );
        println!("VALID: {}/{} features valid", stats.valid_features, stats.total_features);
    } else {
        tracing::warn!(
            "Validation failed: {} errors found",
            stats.errors.len()
        );
        println!(
            "INVALID: {} errors, {}/{} features valid",
            stats.errors.len(),
            stats.valid_features,
            stats.total_features
        );
        if args.verbose {
            for err in &stats.errors {
                println!("  ERROR: {}", err);
            }
        }
    }

    if args.remote {
        match validate_remote(&geojson_str, &config).await {
            Ok(remote_result) => {
                println!("Remote validation: {}", remote_result);
            }
            Err(e) => {
                tracing::warn!("Remote validation failed: {}", e);
                println!("Note: Remote validation failed ({}). Local validation was still performed.", e);
            }
        }
    }

    if stats.is_valid() {
        Ok(())
    } else {
        Err(anyhow::anyhow!(
            "Validation failed with {} errors",
            stats.errors.len()
        ))
    }
}

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

    #[test]
    fn test_validate_args() {
        let args = Args {
            input: PathBuf::from("test.geojson"),
            remote: false,
            verbose: true,
        };
        assert_eq!(args.input, PathBuf::from("test.geojson"));
        assert!(!args.remote);
        assert!(args.verbose);
    }

    #[test]
    fn test_validate_coordinate() {
        assert!(validate_coordinate(&vec![0.0, 0.0]).is_empty());
        assert!(validate_coordinate(&vec![-73.6, 45.5]).is_empty());
        assert!(validate_coordinate(&vec![181.0, 45.5]).len() > 0); // lon out of range
        assert!(validate_coordinate(&vec![-73.6, 91.0]).len() > 0); // lat out of range
    }

    #[test]
    fn test_validate_linestring() {
        let valid = vec![vec![-73.6, 45.5], vec![-73.61, 45.51]];
        assert!(validate_linestring(&valid).is_empty());

        let too_short = vec![vec![-73.6, 45.5]];
        assert!(validate_linestring(&too_short).len() > 0);

        let duplicate = vec![vec![-73.6, 45.5], vec![-73.6, 45.5]];
        assert!(validate_linestring(&duplicate).len() > 0);
    }

    #[test]
    fn test_validate_polygon() {
        // Valid closed ring
        let valid = vec![vec![0.0, 0.0], vec![1.0, 0.0], vec![1.0, 1.0], vec![0.0, 0.0]];
        assert!(validate_polygon(&[valid.clone()]).is_empty());

        // Unclosed ring
        let unclosed = vec![vec![0.0, 0.0], vec![1.0, 0.0], vec![1.0, 1.0]];
        let errors = validate_polygon(&[unclosed]);
        assert!(errors.iter().any(|e| e.contains("not closed")));
    }
}