everymap-cli 0.4.3

Unified CLI for geospatial APIs — geocoding, search, routing, matrix, traffic, tiles and more across every EveryMap provider
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
mod config;
mod output;
mod provider;

use clap::{Parser, Subcommand};
use everymap_core::domains::attributes::AttributeOptions;
use everymap_core::domains::imaging::ImageOptions;
use everymap_core::domains::isoline::{IsolineOptions, RangeType as CoreRangeType};
use everymap_core::domains::matching::MatchingOptions;
use everymap_core::domains::positioning::PositioningOptions;
use everymap_core::domains::routing::AvoidType as CoreAvoidType;
use everymap_core::domains::routing::DepartureTime;
use everymap_core::domains::routing::{RouteOptions, TransportMode as CoreTransportMode};
use everymap_core::domains::search::{GeocodeOptions, ReverseGeocodeOptions};
use everymap_core::domains::tiling::{RasterImageFormat, RasterTileRequest, RasterTileResolution};
use everymap_core::domains::tour::TourOptions;
use everymap_core::domains::traffic::TrafficOptions;
use everymap_core::types::Coordinate;
use provider::ProviderRegistry;

/// The providers this binary can construct.
const SUPPORTED_PROVIDERS: [&str; 8] = [
    "here", "google", "tomtom", "mapbox", "radar", "mapquest", "osrm", "valhalla",
];

#[derive(Parser)]
#[command(
    name = "everymap",
    version,
    about = "Geospatial API CLI - unified interface for map providers"
)]
struct Cli {
    /// Provider to use (here, google, tomtom, mapbox, radar, mapquest, osrm, valhalla)
    #[arg(long, default_value = "here")]
    provider: String,

    /// API key for authentication
    #[arg(long, env = "EVERYMAP_API_KEY")]
    api_key: Option<String>,

    /// API key parameter name (default: key for Google, apiKey for HERE)
    #[arg(long)]
    api_key_param: Option<String>,

    /// Output format
    #[arg(long, default_value = "json")]
    output: String,

    /// Enable verbose output (show request URLs and response bodies on stderr)
    #[arg(long, short)]
    verbose: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Geocode an address to coordinates
    Geocode {
        /// Address to geocode
        query: String,
        /// Maximum number of results
        #[arg(long)]
        limit: Option<u32>,
        /// Language for results (e.g., en, fr, de)
        #[arg(long)]
        language: Option<String>,
        /// Country codes to restrict search (repeatable, e.g., --country DE --country FR)
        #[arg(long = "country", num_args = 1..)]
        country_codes: Option<Vec<String>>,
        /// Bounding box as "south,west;north,east"
        #[arg(long)]
        bbox: Option<String>,
    },
    /// Reverse geocode coordinates to an address
    ReverseGeocode {
        /// Latitude
        #[arg(long)]
        lat: f64,
        /// Longitude
        #[arg(long)]
        lng: f64,
        /// Maximum number of results
        #[arg(long)]
        limit: Option<u32>,
        /// Language for results (e.g., en, fr, de)
        #[arg(long)]
        language: Option<String>,
        /// Search radius in meters
        #[arg(long)]
        radius: Option<f64>,
    },
    /// Calculate a route between two points
    Route {
        /// Origin coordinates (lat,lng)
        #[arg(long)]
        origin: String,
        /// Destination coordinates (lat,lng)
        #[arg(long)]
        destination: String,
        /// Transport mode (car, truck, pedestrian, bicycle, scooter, bus, taxi)
        #[arg(long, default_value = "car")]
        transport: String,
        /// Number of alternative routes
        #[arg(long)]
        alternatives: Option<u32>,
        /// Road types to avoid (repeatable: tolls, ferries, tunnels, highways, dirt-roads)
        #[arg(long = "avoid", num_args = 1..)]
        avoid: Option<Vec<String>>,
        /// Departure time (now, unix timestamp, or ISO 8601)
        #[arg(long)]
        departure_time: Option<String>,
        /// Arrival time (now, unix timestamp, or ISO 8601)
        #[arg(long)]
        arrival_time: Option<String>,
        /// Language for instructions (e.g., en, fr, de)
        #[arg(long)]
        language: Option<String>,
    },
    /// Get traffic flow data for a location
    Traffic {
        /// Latitude
        #[arg(long)]
        lat: f64,
        /// Longitude
        #[arg(long)]
        lng: f64,
        /// Search radius in meters
        #[arg(long)]
        radius: Option<f64>,
        /// Include incident data (true/false)
        #[arg(long)]
        include_incidents: Option<bool>,
        /// Language for results (e.g., en, fr, de)
        #[arg(long)]
        language: Option<String>,
    },
    /// Get position estimate from network data
    Position,
    /// Calculate an isoline (reachability polygon)
    Isoline {
        /// Center latitude
        #[arg(long)]
        lat: f64,
        /// Center longitude
        #[arg(long)]
        lng: f64,
        /// Range value (meters for distance, seconds for time)
        #[arg(long, default_value = "1000")]
        range: f64,
        /// Transport mode (car, truck, pedestrian, bicycle) — default: car
        #[arg(long, default_value = "car")]
        transport: String,
        /// Range type (distance, time) — default: distance
        #[arg(long, default_value = "distance")]
        range_type: String,
        /// Departure time (now, unix timestamp, or ISO 8601)
        #[arg(long)]
        departure_time: Option<String>,
        /// Road types to avoid (repeatable: tolls, ferries, tunnels, highways, dirt-roads)
        #[arg(long = "avoid", num_args = 1..)]
        avoid: Option<Vec<String>>,
    },
    /// Match a GPS trace to the road network
    MatchRoute {
        /// Trace points as semicolon-separated lat,lng pairs (e.g., "52.5,13.3;52.6,13.4")
        #[arg(long)]
        trace: String,
        /// Transport mode for matching (car, truck, pedestrian, bicycle) — default: car
        #[arg(long, default_value = "car")]
        transport: String,
        /// Heading in degrees (0–360)
        #[arg(long)]
        heading: Option<f64>,
        /// Departure time (now, unix timestamp, or ISO 8601)
        #[arg(long)]
        departure_time: Option<String>,
        /// Road types to avoid (repeatable: tolls, ferries, tunnels, highways, dirt-roads)
        #[arg(long = "avoid", num_args = 1..)]
        avoid: Option<Vec<String>>,
    },
    /// Optimize a tour visiting multiple stops
    Tour {
        /// Stop coordinates as space-separated lat,lng pairs
        #[arg(long, num_args = 1..)]
        stops: Vec<String>,
        /// Transport mode (car, truck, pedestrian, bicycle) — default: car
        #[arg(long, default_value = "car")]
        transport: String,
        /// Departure time (ISO 8601, e.g., "2026-04-21T08:00:00Z") — default: now
        #[arg(long)]
        departure: Option<String>,
    },
    /// Get a map tile
    Tile {
        /// Zoom level
        #[arg(long)]
        z: u32,
        /// X coordinate
        #[arg(long)]
        x: u32,
        /// Y coordinate
        #[arg(long)]
        y: u32,
        /// Tile contract to use: raster (encoded imagery) or vector (MVT);
        /// omitted, the first contract the provider serves is used
        #[arg(long)]
        variant: Option<String>,
        /// Raster image format (png, jpeg); vector tiles are always MVT
        #[arg(long)]
        format: Option<String>,
        /// Raster resolution (standard, retina)
        #[arg(long)]
        resolution: Option<String>,
        /// Output file path (default: tile.png for raster, tile.mvt for vector)
        #[arg(long)]
        output_file: Option<String>,
    },
    /// Query road attributes
    Attributes {
        /// Bounding box as "south,west;north,east" or "lat,lng;lat,lng"
        #[arg(long)]
        bbox: Option<String>,
        /// Attribute layer (roads, segments, adminAreas, buildings, landmarks)
        #[arg(long, default_value = "roads")]
        layer: String,
        /// Response format (json, geojson)
        #[arg(long, default_value = "json")]
        format: String,
        /// Specific feature IDs to retrieve
        #[arg(long, num_args = 0..)]
        ids: Option<Vec<String>>,
        /// Include specific attribute fields (comma-separated)
        #[arg(long)]
        include: Option<String>,
        /// Language for results (e.g., en, fr, de)
        #[arg(long)]
        language: Option<String>,
    },
    /// Get a static map image
    MapImage {
        /// Center latitude
        #[arg(long)]
        lat: f64,
        /// Center longitude
        #[arg(long)]
        lng: f64,
        /// Zoom level
        #[arg(long, default_value = "14")]
        zoom: u32,
        /// Image format (png, jpg)
        #[arg(long)]
        format: Option<String>,
        /// Language for labels (e.g., en, fr, de)
        #[arg(long)]
        language: Option<String>,
        /// Image width in pixels (default: 800)
        #[arg(long)]
        width: Option<u32>,
        /// Image height in pixels (default: 600)
        #[arg(long)]
        height: Option<u32>,
        /// Output file path (default: map.png)
        #[arg(long, default_value = "map.png")]
        output_file: String,
    },
}

fn parse_coordinate(input: &str) -> Result<Coordinate, String> {
    let parts: Vec<&str> = input.split(',').collect();
    if parts.len() != 2 {
        return Err("Expected format: lat,lng".to_string());
    }
    let lat: f64 = parts[0].trim().parse().map_err(|_| "Invalid latitude")?;
    let lng: f64 = parts[1].trim().parse().map_err(|_| "Invalid longitude")?;
    Coordinate::new(lat, lng).map_err(|e| e.to_string())
}

fn parse_transport_mode(transport: &str) -> CoreTransportMode {
    match transport {
        "car" => CoreTransportMode::Car,
        "truck" => CoreTransportMode::Truck,
        "pedestrian" => CoreTransportMode::Pedestrian,
        "bicycle" => CoreTransportMode::Bicycle,
        "scooter" => CoreTransportMode::Scooter,
        "bus" => CoreTransportMode::Bus,
        "taxi" => CoreTransportMode::Taxi,
        _ => CoreTransportMode::Car,
    }
}

fn parse_avoid_type(avoid: &str) -> CoreAvoidType {
    match avoid {
        "tolls" => CoreAvoidType::Tolls,
        "ferries" => CoreAvoidType::Ferries,
        "tunnels" => CoreAvoidType::Tunnels,
        "highways" => CoreAvoidType::Highways,
        "dirt-roads" | "dirt_roads" => CoreAvoidType::DirtRoads,
        _ => CoreAvoidType::Tolls,
    }
}

fn parse_departure_time(value: &str) -> DepartureTime {
    if value == "now" {
        DepartureTime::Now
    } else if let Ok(ts) = value.parse::<i64>() {
        DepartureTime::Timestamp(ts)
    } else {
        DepartureTime::Iso8601(value.to_string())
    }
}

fn parse_bbox(bbox: &str) -> Option<everymap_core::types::BoundingBox> {
    let parts: Vec<&str> = bbox.split(';').collect();
    if parts.len() != 2 {
        return None;
    }
    let sw = parse_coordinate(parts[0]).ok()?;
    let ne = parse_coordinate(parts[1]).ok()?;
    Some(everymap_core::types::BoundingBox::new(ne, sw))
}

fn print_output(value: &serde_json::Value, format: &output::OutputFormat) {
    use std::io::stdout;
    let mut out = stdout();
    if let Err(e) = output::write_output(&mut out, value, format) {
        eprintln!("Output error: {}", e);
    }
}

fn exit_with_coord_error(message: &str) -> ! {
    eprintln!("Invalid coordinates: {}", message);
    std::process::exit(1);
}

fn exit_with_error(message: &str) -> ! {
    eprintln!("Error: {}", message);
    std::process::exit(1);
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();

    if !SUPPORTED_PROVIDERS.contains(&cli.provider.as_str()) {
        eprintln!(
            "Error: Unsupported provider '{}'. Supported providers: {}",
            cli.provider,
            SUPPORTED_PROVIDERS.join(", ")
        );
        std::process::exit(1);
    }

    // OSRM and Valhalla are keyless engines: the credential slot carries their
    // deployment base URL, and leaving it empty reaches the crate's documented
    // local default.
    let provider_requires_credential = !matches!(cli.provider.as_str(), "osrm" | "valhalla");
    let config = config::Config::load();
    let api_key = cli
        .api_key
        .clone()
        .or_else(|| config.resolve_api_key(&None, &cli.provider, "EVERYMAP_API_KEY"))
        .unwrap_or_default();
    if provider_requires_credential && api_key.trim().is_empty() {
        eprintln!(
            "Error: API key required for {}. Use --api-key, set EVERYMAP_API_KEY env var, or configure ~/.everymap/config.toml",
            cli.provider
        );
        std::process::exit(1);
    }

    let key_param = cli
        .api_key_param
        .clone()
        .unwrap_or_else(|| match cli.provider.as_str() {
            "google" | "tomtom" => "key".to_string(),
            "mapbox" => "access_token".to_string(),
            _ => "apiKey".to_string(),
        });

    let output_format = output::OutputFormat::from_str(&cli.output);
    let registry = ProviderRegistry::new(&cli.provider, api_key, key_param, cli.verbose);
    run_commands(&cli, &registry, &output_format).await;
}

async fn run_commands(
    cli: &Cli,
    registry: &ProviderRegistry,
    output_format: &output::OutputFormat,
) {
    match &cli.command {
        Commands::Geocode {
            query,
            limit,
            language,
            country_codes,
            bbox,
        } => {
            let geocoder = registry.geocoder();
            let options = GeocodeOptions {
                limit: *limit,
                language: language.clone(),
                country_codes: country_codes.clone().unwrap_or_default(),
                bounding_box: bbox.as_ref().and_then(|b| parse_bbox(b)),
                ..Default::default()
            };
            match geocoder.geocode(query, &options).await {
                Ok(result) => {
                    let output: Vec<serde_json::Value> = result.items.iter().map(|item| {
                        serde_json::json!({
                            "id": item.id,
                            "title": item.title,
                            "coordinate": { "lat": item.coordinate.lat, "lng": item.coordinate.lng },
                            "address": item.address,
                            "result_type": format!("{:?}", item.result_type),
                            "distance": item.distance,
                        })
                    }).collect();
                    print_output(&serde_json::json!({ "results": output }), output_format);
                }
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Commands::ReverseGeocode {
            lat,
            lng,
            limit,
            language,
            radius,
        } => {
            let geocoder = registry.geocoder();
            let coordinate = Coordinate::new(*lat, *lng)
                .unwrap_or_else(|e| exit_with_coord_error(&e.to_string()));
            let options = ReverseGeocodeOptions {
                limit: *limit,
                language: language.clone(),
                radius: *radius,
                ..Default::default()
            };
            match geocoder.reverse_geocode(&coordinate, &options).await {
                Ok(result) => {
                    let output: Vec<serde_json::Value> = result.items.iter().map(|item| {
                        serde_json::json!({
                            "id": item.id,
                            "title": item.title,
                            "coordinate": { "lat": item.coordinate.lat, "lng": item.coordinate.lng },
                            "address": item.address,
                            "result_type": format!("{:?}", item.result_type),
                        })
                    }).collect();
                    print_output(&serde_json::json!({ "results": output }), output_format);
                }
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Commands::Route {
            origin,
            destination,
            transport,
            alternatives,
            avoid,
            departure_time,
            arrival_time,
            language,
        } => {
            let router = registry.router();
            let start = parse_coordinate(origin)
                .unwrap_or_else(|e| exit_with_error(&format!("Invalid origin: {}", e)));
            let end = parse_coordinate(destination)
                .unwrap_or_else(|e| exit_with_error(&format!("Invalid destination: {}", e)));
            let transport_mode = parse_transport_mode(transport);
            let options = RouteOptions {
                transport_mode: Some(transport_mode),
                alternatives: *alternatives,
                avoid: avoid
                    .as_ref()
                    .map(|v| v.iter().map(|a| parse_avoid_type(a)).collect())
                    .unwrap_or_default(),
                departure_time: departure_time.as_ref().map(|v| parse_departure_time(v)),
                arrival_time: arrival_time.as_ref().map(|v| parse_departure_time(v)),
                language: language.clone(),
                ..Default::default()
            };
            match router.calculate_route(&start, &end, &options).await {
                Ok(result) => {
                    let routes: Vec<serde_json::Value> = result
                        .routes
                        .iter()
                        .map(|r| {
                            serde_json::json!({
                                "distance_m": r.distance,
                                "duration_s": r.duration,
                                "points": r.geometry.points.len(),
                            })
                        })
                        .collect();
                    print_output(&serde_json::json!({ "routes": routes }), output_format);
                }
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Commands::Traffic {
            lat,
            lng,
            radius,
            include_incidents,
            language,
        } => {
            let traffic = registry.traffic();
            let coordinate = Coordinate::new(*lat, *lng)
                .unwrap_or_else(|e| exit_with_coord_error(&e.to_string()));
            let options = TrafficOptions {
                radius: *radius,
                include_incidents: *include_incidents,
                language: language.clone(),
                ..Default::default()
            };
            match traffic.get_traffic(&coordinate, &options).await {
                Ok(result) => {
                    let flows: Vec<serde_json::Value> = result
                        .flows
                        .iter()
                        .map(|f| {
                            serde_json::json!({
                                "jam_factor": f.jam_factor,
                                "speed": f.speed,
                                "free_flow_speed": f.free_flow_speed,
                                "road_name": f.road_name,
                            })
                        })
                        .collect();
                    print_output(
                        &serde_json::json!({ "flows": flows, "incidents": result.incidents.len() }),
                        output_format,
                    );
                }
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Commands::Position => {
            let positioner = registry.positioner();
            let options = PositioningOptions::default();
            match positioner.get_position(&options).await {
                Ok(result) => {
                    print_output(
                        &serde_json::json!({
                            "coordinate": { "lat": result.coordinate.lat, "lng": result.coordinate.lng },
                            "accuracy": result.accuracy,
                            "altitude": result.altitude,
                        }),
                        output_format,
                    );
                }
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Commands::Isoline {
            lat,
            lng,
            range,
            transport,
            range_type,
            departure_time,
            avoid,
        } => {
            let isoline = registry.isoline();
            let center = Coordinate::new(*lat, *lng)
                .unwrap_or_else(|e| exit_with_coord_error(&e.to_string()));
            let transport_mode = parse_transport_mode(transport);
            let core_range_type = match range_type.as_str() {
                "time" => CoreRangeType::Time,
                _ => CoreRangeType::Distance,
            };
            let options = IsolineOptions {
                range_type: Some(core_range_type),
                transport_mode: Some(transport_mode),
                departure_time: departure_time.as_ref().map(|v| parse_departure_time(v)),
                avoid: avoid
                    .as_ref()
                    .map(|v| v.iter().map(|a| parse_avoid_type(a)).collect())
                    .unwrap_or_default(),
                ..Default::default()
            };
            match isoline.get_isoline(&center, *range, &options).await {
                Ok(result) => {
                    let isolines: Vec<serde_json::Value> = result.isolines.iter().map(|iso| {
                        serde_json::json!({ "range": iso.range, "points": iso.polygon.len() })
                    }).collect();
                    print_output(&serde_json::json!({ "isolines": isolines }), output_format);
                }
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Commands::MatchRoute {
            trace,
            transport,
            heading,
            departure_time,
            avoid,
        } => {
            let matcher = registry.route_matcher();
            let points: Vec<Coordinate> = trace
                .split(';')
                .filter_map(|p| parse_coordinate(p.trim()).ok())
                .collect();
            if points.is_empty() {
                exit_with_error("No valid coordinates in trace. Use format: 'lat,lng;lat,lng'");
            }
            let transport_mode = parse_transport_mode(transport);
            let options = MatchingOptions {
                transport_mode: Some(transport_mode),
                heading: *heading,
                departure_time: departure_time.as_ref().map(|v| parse_departure_time(v)),
                avoid: avoid
                    .as_ref()
                    .map(|v| v.iter().map(|a| parse_avoid_type(a)).collect())
                    .unwrap_or_default(),
                provider_extra: Some(serde_json::json!({
                    "transport_mode": transport
                })),
            };
            match matcher.match_route(&points, &options).await {
                Ok(result) => {
                    print_output(
                        &serde_json::json!({
                            "matched_points": result.matched_points.len(),
                            "distance_m": result.distance,
                            "duration_s": result.duration,
                        }),
                        output_format,
                    );
                }
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Commands::Tour {
            stops,
            transport,
            departure,
        } => {
            let planner = registry.tour_planner();
            let coordinates: Vec<Coordinate> = stops
                .iter()
                .filter_map(|s| parse_coordinate(s).ok())
                .collect();
            if coordinates.len() < 2 {
                exit_with_error("At least 2 stops required for tour optimization");
            }
            let transport_mode = parse_transport_mode(transport);
            let mut provider_extra = serde_json::json!({});
            if let Some(departure_time) = departure {
                provider_extra["departure_time"] = serde_json::json!(departure_time);
            }
            let options = TourOptions {
                transport_mode: Some(transport_mode),
                provider_extra: Some(provider_extra),
            };
            match planner.optimize_tour(&coordinates, &options).await {
                Ok(result) => {
                    let stop_list: Vec<serde_json::Value> = result
                        .stops
                        .iter()
                        .map(|s| {
                            serde_json::json!({
                                "coordinate": { "lat": s.coordinate.lat, "lng": s.coordinate.lng },
                                "arrival_time": s.arrival_time,
                                "departure_time": s.departure_time,
                            })
                        })
                        .collect();
                    print_output(
                        &serde_json::json!({
                            "stops": stop_list,
                            "total_distance": result.total_distance,
                            "total_duration": result.total_duration,
                            "unassigned_count": result.unassigned_count,
                        }),
                        output_format,
                    );
                }
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Commands::Tile {
            z,
            x,
            y,
            variant,
            format,
            resolution,
            output_file,
        } => {
            let zoom_level = u8::try_from(*z)
                .unwrap_or_else(|_| exit_with_error("Tile zoom must fit in a byte"));
            let variant = match variant.as_deref() {
                Some(chosen_variant) => chosen_variant.to_string(),
                None if registry.raster_tile_provider().is_some() => "raster".to_string(),
                None if registry.vector_tile_provider().is_some() => "vector".to_string(),
                None => exit_with_error(&format!("{} does not support tiling", cli.provider)),
            };
            match variant.as_str() {
                "raster" => {
                    let Some(raster_provider) = registry.raster_tile_provider() else {
                        exit_with_error(&format!("{} does not support raster tiles", cli.provider));
                    };
                    let image_format = match format.as_deref() {
                        None | Some("png") => RasterImageFormat::Png,
                        Some("jpeg") | Some("jpg") => RasterImageFormat::Jpeg,
                        Some(other) => exit_with_error(&format!(
                            "Unknown raster format '{other}'; use png or jpeg"
                        )),
                    };
                    let tile_resolution = match resolution.as_deref() {
                        None | Some("standard") => RasterTileResolution::Standard,
                        Some("retina") => RasterTileResolution::Retina,
                        Some(other) => exit_with_error(&format!(
                            "Unknown raster resolution '{other}'; use standard or retina"
                        )),
                    };
                    let request =
                        RasterTileRequest::new(*x, *y, zoom_level, image_format, tile_resolution);
                    match raster_provider.fetch_raster_tile(&request).await {
                        Ok(tile) => {
                            let path = output_file
                                .clone()
                                .unwrap_or_else(|| "tile.png".to_string());
                            match std::fs::write(&path, &tile.image_bytes) {
                                Ok(()) => println!(
                                    "Saved tile to {} ({}, {} bytes)",
                                    path,
                                    image_format.file_extension(),
                                    tile.image_bytes.len()
                                ),
                                Err(e) => eprintln!("Error writing file {}: {}", path, e),
                            }
                        }
                        Err(e) => eprintln!("Error: {}", e),
                    }
                }
                "vector" => {
                    let Some(vector_provider) = registry.vector_tile_provider() else {
                        exit_with_error(&format!("{} does not support vector tiles", cli.provider));
                    };
                    match vector_provider.fetch_vector_tile(*x, *y, zoom_level).await {
                        Ok(tile) => {
                            let path = output_file
                                .clone()
                                .unwrap_or_else(|| "tile.mvt".to_string());
                            match std::fs::write(&path, &tile.tile_bytes) {
                                Ok(()) => println!(
                                    "Saved tile to {} (vector, {} bytes, {:?})",
                                    path,
                                    tile.tile_bytes.len(),
                                    tile.tile_encoding
                                ),
                                Err(e) => eprintln!("Error writing file {}: {}", path, e),
                            }
                        }
                        Err(e) => eprintln!("Error: {}", e),
                    }
                }
                other => exit_with_error(&format!(
                    "Unknown tile variant '{other}'; use raster or vector"
                )),
            }
        }
        Commands::Attributes {
            bbox,
            layer,
            format,
            ids,
            include,
            language,
        } => {
            let attr_provider = registry.attribute_provider();
            let mut provider_extra = serde_json::json!({
                "layers": layer,
                "format": format,
            });
            if let Some(ids) = ids {
                provider_extra["ids"] = serde_json::json!(ids);
            }
            if let Some(include) = include {
                provider_extra["include"] =
                    serde_json::json!(include.split(',').collect::<Vec<_>>());
            }
            let options = AttributeOptions {
                bbox: bbox.clone(),
                language: language.clone(),
                provider_extra: Some(provider_extra),
            };
            match attr_provider.get_attributes(&options).await {
                Ok(result) => {
                    print_output(&result.data, output_format);
                }
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        Commands::MapImage {
            lat,
            lng,
            zoom,
            format,
            language,
            width,
            height,
            output_file,
        } => {
            let image_provider = registry.image_provider();
            let center = Coordinate::new(*lat, *lng)
                .unwrap_or_else(|e| exit_with_coord_error(&e.to_string()));
            let options = ImageOptions {
                format: format.clone(),
                language: language.clone(),
                width: *width,
                height: *height,
                ..Default::default()
            };
            match image_provider
                .get_image(&center, *zoom, (800, 600), &options)
                .await
            {
                Ok(result) => match std::fs::write(output_file, &result.data) {
                    Ok(()) => println!(
                        "Saved map image to {} ({} bytes, {})",
                        output_file,
                        result.data.len(),
                        result.content_type.as_deref().unwrap_or("unknown")
                    ),
                    Err(e) => eprintln!("Error writing file {}: {}", output_file, e),
                },
                Err(e) => eprintln!("Error: {}", e),
            }
        }
    }
}