v2rmp 0.4.2

rmpca — Route Optimization TUI & Agent Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use serde::{Deserialize, Serialize};

use crate::core::clean::{clean_geojson, CleanOptions};
use crate::core::compile::CompileRequest;
use crate::core::extract::{BBoxRequest, ExtractRequest, ExtractSource, RoadClass};
use crate::core::optimize::{OnewayMode, OptimizeRequest, SolverMode, TurnPenalties};

/// rmpca - Route optimization and data extraction
#[derive(Parser)]
#[command(name = "rmpca", version = "0.4.2")]
#[command(about = "Route optimization and data extraction")]
struct Cli {
    /// Output results as JSON (for machine / agent consumption)
    #[arg(long, global = true)]
    json: bool,

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

#[derive(Subcommand)]
enum Commands {
    /// Extract road network data from Overture Maps
    Extract(ExtractArgs),
    /// Compile GeoJSON into binary .rmp format
    Compile(CompileArgs),
    /// Clean a GeoJSON road network
    Clean(CleanArgs),
    /// Optimize a route (Chinese Postman Problem)
    Optimize(OptimizeArgs),
    /// Solve Vehicle Routing Problem (VRP) for multiple agents
    Vrp(VrpArgs),
    /// Run the full pipeline: extract -> clean -> compile -> optimize
    Pipeline(PipelineArgs),
    /// List available resources (maps, routes)
    List(ListArgs),
    /// Execute a JSON-encoded task plan
    Agent(AgentArgs),
}

#[derive(clap::Args)]
struct ListArgs {
    /// Resource type to list
    #[arg(value_enum, default_value = "maps")]
    resource: ResourceType,
}

#[derive(clap::ValueEnum, Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
enum ResourceType {
    Maps,
    Routes,
}

#[derive(clap::Args)]
struct AgentArgs {
    /// Path to JSON task file (or '-' for stdin)
    #[arg(short, long, default_value = "-")]
    task: String,
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum AgentTask {
    Extract(ExtractArgs),
    Compile(CompileArgs),
    Clean(CleanArgs),
    Optimize(OptimizeArgs),
    Vrp(VrpArgs),
    Pipeline(PipelineArgs),
}

// ── VRP ───────────────────────────────────────────────────────────────

// ── Custom Serde Deserializers for Agent Payloads ──────────────────────

fn deserialize_depot_opt<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum DepotInput {
        String(String),
        Array([f64; 2]),
    }

    let opt = Option::<DepotInput>::deserialize(deserializer)?;
    Ok(opt.map(|input| match input {
        DepotInput::String(s) => s,
        DepotInput::Array([lat, lon]) => format!("{},{}", lat, lon),
    }))
}

fn deserialize_depots_vec<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum DepotInput {
        String(String),
        Array([f64; 2]),
    }

    let inputs = Vec::<DepotInput>::deserialize(deserializer).unwrap_or_default();
    Ok(inputs
        .into_iter()
        .map(|input| match input {
            DepotInput::String(s) => s,
            DepotInput::Array([lat, lon]) => format!("{},{}", lat, lon),
        })
        .collect())
}

fn deserialize_bbox<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum BboxInput {
        String(String),
        Array([f64; 4]),
    }

    let input = BboxInput::deserialize(deserializer)?;
    Ok(match input {
        BboxInput::String(s) => s,
        BboxInput::Array([min_lon, min_lat, max_lon, max_lat]) => {
            format!("{},{},{},{}", min_lon, min_lat, max_lon, max_lat)
        }
    })
}

fn default_output_dir() -> String {
    "routes/".to_string()
}

fn default_vehicles() -> usize {
    1
}

fn default_vrp_algo() -> VrpAlgorithm {
    VrpAlgorithm::Greedy
}

fn default_source() -> String {
    "overture".to_string()
}

fn default_extract_output() -> String {
    "extract-output.geojson".to_string()
}

#[derive(clap::ValueEnum, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum VrpAlgorithm {
    /// Simple greedy nearest-neighbor approach
    Greedy,
    /// Savings algorithm (Clarke-Wright)
    Savings,
    /// Metaheuristic: Local search / Tabu search
    LocalSearch,
    /// Metaheuristic: Simulated Annealing
    SimulatedAnnealing,
}

#[derive(clap::Args, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
struct VrpArgs {
    /// Input .rmp cache file
    #[arg(short, long)]
    input: String,

    /// Output directory for agent GPX routes
    #[arg(short, long, default_value = "routes/")]
    #[serde(default = "default_output_dir")]
    output_dir: String,

    /// Number of vehicles/agents
    #[arg(short, long, default_value_t = 1)]
    #[serde(default = "default_vehicles", alias = "num_vehicles")]
    vehicles: usize,

    /// Algorithm to use for VRP
    #[arg(short, long, value_enum, default_value_t = VrpAlgorithm::Greedy)]
    #[serde(default = "default_vrp_algo")]
    algo: VrpAlgorithm,

    /// Vehicle capacity (if applicable)
    #[arg(long)]
    #[serde(default)]
    capacity: Option<f64>,

    /// Depot coordinates: LAT,LON (can be specified multiple times)
    #[arg(long, action = clap::ArgAction::Append)]
    #[serde(default, deserialize_with = "deserialize_depots_vec")]
    depot: Vec<String>,

    /// Path to a JSON/CSV file containing specific waypoints to visit
    #[arg(long)]
    #[serde(default)]
    waypoints: Option<String>,
}

// ── Extract ───────────────────────────────────────────────────────────

#[derive(clap::Args, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
struct ExtractArgs {
    /// Bounding box: MIN_LON,MIN_LAT,MAX_LON,MAX_LAT
    #[arg(long, allow_hyphen_values = true)]
    #[serde(deserialize_with = "deserialize_bbox")]
    bbox: String,

    /// Data source: overture (default)
    #[arg(long, default_value = "overture")]
    #[serde(default = "default_source")]
    source: String,

    /// Road classes to include (comma-separated, default: all vehicle)
    #[arg(long, value_delimiter = ',')]
    #[serde(default)]
    road_classes: Vec<String>,

    /// Output GeoJSON file path
    #[arg(short, long, default_value = "extract-output.geojson")]
    #[serde(default = "default_extract_output")]
    output: String,

    /// Path to local OSM PBF file (required for source=osm)
    #[arg(long)]
    #[serde(default)]
    pbf: Option<String>,
}

// ── Compile ───────────────────────────────────────────────────────────

#[derive(clap::Args, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
struct CompileArgs {
    /// Input GeoJSON file
    #[arg(short, long)]
    input: String,

    /// Output .rmp file
    #[arg(short, long)]
    output: String,

    /// Run cleaning before compilation (with default clean options)
    #[arg(long)]
    #[serde(default)]
    clean: bool,
}

// ── Clean ─────────────────────────────────────────────────────────────

#[derive(clap::Args, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
struct CleanArgs {
    /// Input GeoJSON file
    #[arg(short, long)]
    input: String,

    /// Output cleaned GeoJSON file
    #[arg(short, long)]
    output: String,

    /// Minimum edge length in meters (default: 0.1)
    #[arg(long)]
    #[serde(default)]
    min_length_m: Option<f64>,

    /// Node snapping distance in meters (default: 1.0)
    #[arg(long)]
    #[serde(default)]
    node_snap_m: Option<f64>,

    /// Keep only the N largest connected components (default: 1)
    #[arg(long)]
    #[serde(default)]
    max_components: Option<usize>,

    /// Geometry simplification tolerance in meters (default: 0.0)
    #[arg(long)]
    #[serde(default)]
    simplify_tolerance_m: Option<f64>,

    /// Skip edge deduplication
    #[arg(long)]
    #[serde(default)]
    no_dedupe: bool,

    /// Skip isolated node removal
    #[arg(long)]
    #[serde(default)]
    no_remove_isolates: bool,
}

// ── Optimize ──────────────────────────────────────────────────────────

fn default_oneway() -> String {
    "respect".to_string()
}

fn default_mode() -> String {
    "cpp".to_string()
}

fn default_left_penalty() -> f64 {
    1.0
}

fn default_right_penalty() -> f64 {
    0.0
}

fn default_uturn_penalty() -> f64 {
    5.0
}

fn default_solver() -> String {
    "default".to_string()
}

fn default_pipeline_output_dir() -> String {
    ".".to_string()
}

#[derive(clap::Args, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
struct OptimizeArgs {
    /// Input .rmp cache file
    #[arg(short, long)]
    input: String,

    /// Output route GPX file
    #[arg(short, long)]
    #[serde(default)]
    output: Option<String>,

    /// Depot coordinates: LAT,LON
    #[arg(long)]
    #[serde(default, deserialize_with = "deserialize_depot_opt")]
    depot: Option<String>,

    /// Oneway mode: respect, ignore, reverse (default: respect)
    #[arg(long, default_value = "respect")]
    #[serde(default = "default_oneway")]
    oneway: String,

    /// Solver mode: cpp (edge coverage) or vrp (stop visits) (default: cpp)
    #[arg(short, long, default_value = "cpp")]
    #[serde(default = "default_mode")]
    mode: String,

    /// Left turn penalty (default: 1.0)
    #[arg(long, default_value_t = 1.0)]
    #[serde(default = "default_left_penalty")]
    left_penalty: f64,

    /// Right turn penalty (default: 0.0)
    #[arg(long, default_value_t = 0.0)]
    #[serde(default = "default_right_penalty")]
    right_penalty: f64,

    /// U-turn penalty (default: 5.0)
    #[arg(long, default_value_t = 5.0)]
    #[serde(default = "default_uturn_penalty")]
    uturn_penalty: f64,

    /// Number of vehicles (for VRP mode only)
    #[arg(long, default_value_t = 1)]
    vehicles: usize,

    /// Solver algorithm for VRP mode (clarke_wright, sweep, two_opt, or_opt, default)
    #[arg(long, default_value = "default")]
    #[serde(default = "default_solver", alias = "solver_id")]
    solver: String,
}

// ── Pipeline ──────────────────────────────────────────────────────────

#[derive(clap::Args, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
struct PipelineArgs {
    /// Bounding box: MIN_LON,MIN_LAT,MAX_LON,MAX_LAT
    #[arg(long, allow_hyphen_values = true)]
    #[serde(deserialize_with = "deserialize_bbox")]
    bbox: String,

    /// Data source: overture (default)
    #[arg(long, default_value = "overture")]
    #[serde(default = "default_source")]
    source: String,

    /// Output directory for all intermediate and final files
    #[arg(short, long, default_value = ".")]
    #[serde(default = "default_pipeline_output_dir")]
    output_dir: String,

    /// Depot coordinates: LAT,LON
    #[arg(long)]
    #[serde(default, deserialize_with = "deserialize_depot_opt")]
    depot: Option<String>,
}

#[derive(Serialize)]
struct PipelineResult {
    extract: crate::core::extract::ExtractResult,
    clean: crate::core::clean::CleanStats,
    compile: crate::core::compile::CompileResult,
    optimize: crate::core::optimize::OptimizeResult,
}

// ── Parsing helpers ───────────────────────────────────────────────────

fn parse_bbox(s: &str) -> Result<(f64, f64, f64, f64)> {
    let parts: Vec<f64> = s
        .split(',')
        .map(|v| v.parse::<f64>().context(format!("Invalid bbox value: {v}")))
        .collect::<Result<Vec<f64>>>()?;
    if parts.len() != 4 {
        anyhow::bail!("Bounding box must have exactly 4 values: MIN_LON,MIN_LAT,MAX_LON,MAX_LAT");
    }
    Ok((parts[0], parts[1], parts[2], parts[3]))
}

fn parse_road_classes(classes: &[String]) -> Result<Vec<RoadClass>> {
    if classes.is_empty() {
        return Ok(RoadClass::all_vehicle());
    }
    classes
        .iter()
        .map(|s| match s.as_str() {
            "residential" => Ok(RoadClass::Residential),
            "tertiary" => Ok(RoadClass::Tertiary),
            "secondary" => Ok(RoadClass::Secondary),
            "primary" => Ok(RoadClass::Primary),
            "trunk" => Ok(RoadClass::Trunk),
            "motorway" => Ok(RoadClass::Motorway),
            "unclassified" => Ok(RoadClass::Unclassified),
            "living_street" => Ok(RoadClass::LivingStreet),
            "service" => Ok(RoadClass::Service),
            "secondary_link" => Ok(RoadClass::SecondaryLink),
            "primary_link" => Ok(RoadClass::PrimaryLink),
            "trunk_link" => Ok(RoadClass::TrunkLink),
            "motorway_link" => Ok(RoadClass::MotorwayLink),
            other => anyhow::bail!("Unknown road class: {other}"),
        })
        .collect()
}

fn parse_source(s: &str) -> Result<ExtractSource> {
    match s {
        "osm" => Ok(ExtractSource::Osm),
        "overture" => Ok(ExtractSource::Overture),
        other => anyhow::bail!("Unknown source: {other}"),
    }
}

fn parse_depot(s: &str) -> Result<(f64, f64)> {
    let parts: Vec<f64> = s
        .split(',')
        .map(|v| {
            v.parse::<f64>()
                .context(format!("Invalid depot value: {v}"))
        })
        .collect::<Result<Vec<f64>>>()?;
    if parts.len() != 2 {
        anyhow::bail!("Depot must be LAT,LON (2 values)");
    }
    Ok((parts[0], parts[1]))
}

fn parse_oneway(s: &str) -> Result<OnewayMode> {
    match s {
        "respect" => Ok(OnewayMode::Respect),
        "ignore" => Ok(OnewayMode::Ignore),
        "reverse" => Ok(OnewayMode::Reverse),
        other => anyhow::bail!("Unknown oneway mode: {other} (respect|ignore|reverse)"),
    }
}

// ── Output helpers ────────────────────────────────────────────────────

fn output_json<T: Serialize>(value: &T) -> Result<()> {
    let json = serde_json::to_string_pretty(value)?;
    println!("{json}");
    Ok(())
}

fn init_tracing() {
    let _ = tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .with_target(false)
        .try_init();
}

// ── Command handlers ──────────────────────────────────────────────────

async fn run_extract_cmd(args: ExtractArgs, json: bool) -> Result<()> {
    let (min_lon, min_lat, max_lon, max_lat) = parse_bbox(&args.bbox)?;
    let road_classes = parse_road_classes(&args.road_classes)?;
    let source = parse_source(&args.source)?;

    if !json {
        tracing::info!("Starting extraction...");
        tracing::info!("Source: {:?}", source);
        tracing::info!("Bounding box: [{min_lon:.4}, {min_lat:.4}, {max_lon:.4}, {max_lat:.4}]");
    }

    let req = ExtractRequest {
        source,
        bbox: BBoxRequest {
            min_lon,
            min_lat,
            max_lon,
            max_lat,
        },
        road_classes,
        output_path: args.output.clone(),
    };

    if let Some(pbf) = args.pbf {
        // If PBF path is provided, we can pass it via env or update ExtractRequest
        // For now, let's set the env var that run_osm_extract uses
        std::env::set_var("OSM_PBF_PATH", pbf);
    }

    let result = crate::core::extract::run_extract(&req).await?;

    if json {
        output_json(&result)?;
    } else {
        tracing::info!("Extraction complete!");
        tracing::info!("Nodes: {}", result.nodes);
        tracing::info!("Edges: {}", result.edges);
        tracing::info!("Total road length: {:.2} km", result.total_km);
        tracing::info!("Output: {}", result.output_path);
    }

    Ok(())
}

fn run_compile_cmd(args: CompileArgs, json: bool) -> Result<()> {
    let clean_options = if args.clean {
        Some(CleanOptions::default())
    } else {
        None
    };

    if !json {
        tracing::info!("Compiling {} -> {}", args.input, args.output);
    }

    let req = CompileRequest {
        input_geojson: args.input,
        output_rmp: args.output,
        compress: false,
        road_classes: vec![],
        clean_options,
    };

    let result = crate::core::compile::run_compile(&req)?;

    if json {
        output_json(&result)?;
    } else {
        tracing::info!("Compilation complete!");
        tracing::info!("Nodes: {}", result.node_count);
        tracing::info!("Edges: {}", result.edge_count);
        tracing::info!(
            "Size: {} -> {} bytes ({:.1}% ratio)",
            result.input_size_bytes,
            result.output_size_bytes,
            if result.input_size_bytes > 0 {
                (result.output_size_bytes as f64 / result.input_size_bytes as f64) * 100.0
            } else {
                0.0
            }
        );
        tracing::info!("Elapsed: {} ms", result.elapsed_ms);
    }

    Ok(())
}

fn run_clean_cmd(args: CleanArgs, json: bool) -> Result<()> {
    let mut opts = CleanOptions::default();
    if let Some(v) = args.min_length_m {
        opts.min_length_m = v;
    }
    if let Some(v) = args.node_snap_m {
        opts.node_snap_m = v;
    }
    if let Some(v) = args.max_components {
        opts.max_components = v;
    }
    if let Some(v) = args.simplify_tolerance_m {
        opts.simplify_tolerance_m = v;
    }
    if args.no_dedupe {
        opts.dedupe_edges = false;
    }
    if args.no_remove_isolates {
        opts.remove_isolates = false;
    }

    if !json {
        tracing::info!("Cleaning {} -> {}", args.input, args.output);
    }

    let input_data = std::fs::read_to_string(&args.input)
        .with_context(|| format!("Failed to read input file: {}", args.input))?;
    let geojson: geojson::FeatureCollection = serde_json::from_str(&input_data)
        .with_context(|| "Failed to parse GeoJSON FeatureCollection")?;

    let (cleaned, stats, warnings) = clean_geojson(&geojson, &opts)?;

    let output_str = serde_json::to_string_pretty(&cleaned)?;
    std::fs::write(&args.output, &output_str)
        .with_context(|| format!("Failed to write output file: {}", args.output))?;

    if json {
        #[derive(Serialize)]
        struct CleanOutput {
            stats: crate::core::clean::CleanStats,
            warnings: Vec<String>,
            output_file: String,
        }
        output_json(&CleanOutput {
            stats,
            warnings,
            output_file: args.output,
        })?;
    } else {
        tracing::info!("Cleaning complete!");
        tracing::info!(
            "Features: {} -> {}",
            stats.input_features,
            stats.output_features
        );
        for w in &warnings {
            tracing::warn!("Warning: {w}");
        }
    }

    Ok(())
}

async fn run_optimize_cmd(args: OptimizeArgs, json: bool) -> Result<()> {
    let depot = args.depot.as_deref().map(parse_depot).transpose()?;
    let oneway_mode = parse_oneway(&args.oneway)?;
    let mode = match args.mode.to_lowercase().as_str() {
        "vrp" => SolverMode::Vrp,
        _ => SolverMode::Cpp,
    };

    if !json {
        tracing::info!(
            "Optimizing route from {} (mode: {})",
            args.input,
            if mode == SolverMode::Vrp {
                "VRP"
            } else {
                "CPP"
            }
        );
    }

    let req = OptimizeRequest {
        cache_file: args.input.clone(),
        route_file: args.output.clone(),
        turn_penalties: TurnPenalties {
            left: args.left_penalty,
            right: args.right_penalty,
            u_turn: args.uturn_penalty,
        },
        depot,
        oneway_mode,
        mode,
        num_vehicles: args.vehicles,
        solver_id: args.solver,
    };

    let result = crate::core::optimize::run_optimize(&req).await?;

    if json {
        output_json(&result)?;
    } else {
        tracing::info!("Optimization complete!");
        tracing::info!("Total distance: {:.2} km", result.total_distance_km);
        tracing::info!("Stops/Segments: {}", result.total_segments);
        tracing::info!("Vehicles used: {}", result.num_routes);
        tracing::info!(
            "Turns: {} left, {} right, {} u-turn, {} straight",
            result.turns.left,
            result.turns.right,
            result.turns.u_turn,
            result.turns.straight
        );
        tracing::info!("Elapsed: {} ms", result.elapsed_ms);
        if let Some(ref path) = args.output {
            tracing::info!("Route written to: {path}");
        }
    }

    Ok(())
}

fn run_vrp_cmd(args: VrpArgs, _json: bool) -> Result<()> {
    tracing::info!("VRP solving requested for {}", args.input);
    tracing::info!("Algorithm: {:?}", args.algo);
    tracing::info!(
        "Vehicles: {}, Depots: {}, Waypoints: {:?}",
        args.vehicles,
        args.depot.len(),
        args.waypoints
    );

    // Parse all depots
    let _depots: Vec<(f64, f64)> = args
        .depot
        .iter()
        .map(|s| parse_depot(s))
        .collect::<Result<Vec<_>>>()?;

    // Placeholder for actual VRP logic
    tracing::warn!(
        "VRP implementation ({:?}) is currently a wireframe.",
        args.algo
    );

    Ok(())
}

async fn run_pipeline_cmd(args: PipelineArgs, json: bool) -> Result<()> {
    let (min_lon, min_lat, max_lon, max_lat) = parse_bbox(&args.bbox)?;
    let source = parse_source(&args.source)?;
    let depot = args.depot.as_deref().map(parse_depot).transpose()?;

    // Ensure output directory exists
    std::fs::create_dir_all(&args.output_dir)?;

    let extract_path = format!("{}/extract.geojson", args.output_dir);
    let cleaned_path = format!("{}/cleaned.geojson", args.output_dir);
    let rmp_path = format!("{}/network.rmp", args.output_dir);
    let route_path = format!("{}/route.gpx", args.output_dir);

    // Stage 1: Extract
    if !json {
        tracing::info!("=== Pipeline Stage 1: Extract ===");
    }
    let extract_req = ExtractRequest {
        source,
        bbox: BBoxRequest {
            min_lon,
            min_lat,
            max_lon,
            max_lat,
        },
        road_classes: RoadClass::all_vehicle(),
        output_path: extract_path.clone(),
    };
    let extract_result = crate::core::extract::run_extract(&extract_req)
        .await
        .context("Pipeline failed at stage 'extract'")?;

    // Stage 2: Clean
    if !json {
        tracing::info!("=== Pipeline Stage 2: Clean ===");
    }
    let input_data = std::fs::read_to_string(&extract_path)
        .context("Pipeline failed reading extracted GeoJSON")?;
    let geojson: geojson::FeatureCollection =
        serde_json::from_str(&input_data).context("Pipeline failed parsing extracted GeoJSON")?;
    let (cleaned, clean_stats, _warnings) = clean_geojson(&geojson, &CleanOptions::default())
        .context("Pipeline failed at stage 'clean'")?;
    let cleaned_str = serde_json::to_string_pretty(&cleaned)?;
    std::fs::write(&cleaned_path, &cleaned_str)
        .context("Pipeline failed writing cleaned GeoJSON")?;

    // Stage 3: Compile
    if !json {
        tracing::info!("=== Pipeline Stage 3: Compile ===");
    }
    let compile_req = CompileRequest {
        input_geojson: cleaned_path.clone(),
        output_rmp: rmp_path.clone(),
        compress: false,
        road_classes: vec![],
        clean_options: None,
    };
    let compile_result = crate::core::compile::run_compile(&compile_req)
        .context("Pipeline failed at stage 'compile'")?;

    // Stage 4: Optimize
    if !json {
        tracing::info!("=== Pipeline Stage 4: Optimize ===");
    }
    let optimize_req = OptimizeRequest {
        cache_file: rmp_path.clone(),
        route_file: Some(route_path.clone()),
        turn_penalties: TurnPenalties::default(),
        depot,
        oneway_mode: OnewayMode::default(),
        mode: SolverMode::Cpp,
        num_vehicles: 1,
        solver_id: "clarke_wright".to_string(),
    };
    let optimize_result = crate::core::optimize::run_optimize(&optimize_req)
        .await
        .context("Pipeline failed at stage 'optimize'")?;

    // Output
    let pipeline_result = PipelineResult {
        extract: extract_result,
        clean: clean_stats,
        compile: compile_result,
        optimize: optimize_result,
    };

    if json {
        output_json(&pipeline_result)?;
    } else {
        tracing::info!("=== Pipeline Complete ===");
        tracing::info!(
            "Extract: {} nodes, {} edges, {:.2} km",
            pipeline_result.extract.nodes,
            pipeline_result.extract.edges,
            pipeline_result.extract.total_km
        );
        tracing::info!(
            "Clean: {} -> {} features",
            pipeline_result.clean.input_features,
            pipeline_result.clean.output_features
        );
        tracing::info!(
            "Compile: {} nodes, {} edges, {} bytes",
            pipeline_result.compile.node_count,
            pipeline_result.compile.edge_count,
            pipeline_result.compile.output_size_bytes
        );
        tracing::info!(
            "Optimize: {:.2} km total, {} vehicles",
            pipeline_result.optimize.total_distance_km,
            pipeline_result.optimize.num_routes
        );
        tracing::info!("Files in: {}/", args.output_dir);
    }

    Ok(())
}

async fn run_agent_cmd(args: AgentArgs, json: bool) -> Result<()> {
    let input: Box<dyn std::io::Read> = if args.task == "-" {
        Box::new(std::io::stdin())
    } else {
        Box::new(std::fs::File::open(&args.task)?)
    };

    let task: AgentTask =
        serde_json::from_reader(input).context("Failed to parse agent task JSON")?;

    match task {
        AgentTask::Extract(a) => run_extract_cmd(a, json).await,
        AgentTask::Compile(a) => run_compile_cmd(a, json),
        AgentTask::Clean(a) => run_clean_cmd(a, json),
        AgentTask::Optimize(a) => run_optimize_cmd(a, json).await,
        AgentTask::Vrp(a) => run_vrp_cmd(a, json),
        AgentTask::Pipeline(a) => run_pipeline_cmd(a, json).await,
    }
}

fn run_list_cmd(args: ListArgs, json: bool) -> Result<()> {
    let mut files = Vec::new();
    if let Ok(entries) = std::fs::read_dir(".") {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
                match args.resource {
                    ResourceType::Maps => {
                        if ext == "rmp" {
                            files.push(path.display().to_string());
                        }
                    }
                    ResourceType::Routes => {
                        if ext == "gpx" || ext == "geojson" {
                            files.push(path.display().to_string());
                        }
                    }
                }
            }
        }
    }

    if json {
        output_json(&files)?;
    } else {
        println!("Available {:?}:", args.resource);
        for f in files {
            println!("  - {f}");
        }
    }
    Ok(())
}

// ── Entry point ───────────────────────────────────────────────────────

pub async fn run() -> Result<()> {
    let cli = Cli::parse();
    init_tracing();

    let result = match cli.command {
        Commands::Extract(args) => run_extract_cmd(args, cli.json).await,
        Commands::Compile(args) => run_compile_cmd(args, cli.json),
        Commands::Clean(args) => run_clean_cmd(args, cli.json),
        Commands::Optimize(args) => run_optimize_cmd(args, cli.json).await,
        Commands::Vrp(args) => run_vrp_cmd(args, cli.json),
        Commands::Pipeline(args) => run_pipeline_cmd(args, cli.json).await,
        Commands::List(args) => run_list_cmd(args, cli.json),
        Commands::Agent(args) => run_agent_cmd(args, cli.json).await,
    };

    if let Err(e) = result {
        eprintln!("Error: {e:#}");
        std::process::exit(1);
    }

    Ok(())
}