odk-cli 0.1.2

ODK CLI - Unified schema compilation from TypeScript, WASM, or JSON to multiple targets
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
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
//! ODK CLI - Unified Schema Compilation Tool
//!
//! Compile schemas from various sources to TypeSpec targets:
//! - Input: TypeScript (.ts), WASM plugins (.wasm), YAML (.yaml), JSON (.json)
//! - Output: Any TypeSpec emitter

use anyhow::{Context, Result, bail};
use camino::Utf8PathBuf;
use clap::{Parser, Subcommand};
use odk_schema::CompiledSchema;
use std::fs;
use std::path::PathBuf;
use std::process::Command;

mod builder;
use odk_cli::config;
mod error_mapper;
mod extism_host;
mod source_map;
mod templates;
mod ts_executor;
mod typespec_bridge;

use odk_cli::loaders;

#[derive(Parser, Debug)]
#[command(name = "odk", version, about = "ODK - Omni Development Kit CLI")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Compile a schema and emit to targets
    Compile {
        /// Input source: .ts, .yaml, .json, or .wasm file (optional if in config)
        input: Option<Utf8PathBuf>,

        /// Config file path (default: auto-detect odk.config.*)
        #[arg(short, long)]
        config: Option<Utf8PathBuf>,

        /// Output directory for generated files
        #[arg(short, long)]
        out: Option<Utf8PathBuf>,

        /// TypeSpec emitters to use (comma-separated or multiple -e flags)
        /// Examples: @typespec/json-schema, @typespec/openapi3, @typespec/protobuf
        /// Default: @typespec/json-schema, @typespec/openapi3
        #[arg(short, long, value_delimiter = ',')]
        emit: Option<Vec<String>>,

        /// Namespace for generated TypeSpec (overrides schema name)
        #[arg(short, long)]
        namespace: Option<String>,

        /// Keep temporary TypeSpec files (for debugging)
        #[arg(long)]
        keep_temp: bool,

        /// GraphQL operation documents glob pattern (e.g. "src/**/*.graphql")
        #[arg(long)]
        operations: Option<String>,

        /// Introspect a GraphQL endpoint to get the schema
        #[arg(long)]
        introspect: Option<String>,
    },

    /// Initialize a new ODK project
    Init {
        /// Language/format: rust, python, yaml (prompts if not specified)
        #[arg(short, long)]
        lang: Option<String>,

        /// Project name (default: current directory name)
        #[arg(short, long)]
        name: Option<String>,
    },

    /// Build a schema plugin to WASM
    Build {
        /// Input: directory with Cargo.toml (default: current dir)
        #[arg(default_value = ".")]
        input: Utf8PathBuf,

        /// Output .wasm file (default: ./target/odk/<name>.wasm)
        #[arg(short, long)]
        out: Option<Utf8PathBuf>,

        /// Build in release mode
        #[arg(long, default_value = "true")]
        release: bool,
    },

    /// Check/validate a schema without emitting
    Check {
        /// Input source: .ts, .yaml, .json, .wasm, or .graphql file
        input: Utf8PathBuf,

        /// GraphQL operation documents glob pattern
        #[arg(long)]
        operations: Option<String>,
    },

    /// Generate client artifacts (hooks, mocks, SDK) from a schema
    Generate {
        /// Input source: .ts, .yaml, .json, .wasm, or .graphql file
        input: Option<Utf8PathBuf>,

        /// Config file path (default: auto-detect odk.config.*)
        #[arg(short, long)]
        config: Option<Utf8PathBuf>,

        /// Output directory for generated files
        #[arg(short, long, default_value = "./generated")]
        out: Utf8PathBuf,

        /// Generation targets (comma-separated)
        /// Available: sdk, react-query, msw, mcp, python, typescript, rust
        /// Default: sdk,react-query,msw
        #[arg(short, long, default_value = "sdk,react-query,msw")]
        targets: String,

        /// GraphQL operation documents glob pattern (e.g. "src/**/*.graphql")
        #[arg(long)]
        operations: Option<String>,

        /// Introspect a GraphQL endpoint to get the schema
        #[arg(long)]
        introspect: Option<String>,

        /// Base name for the model output file(s), replacing the default
        /// "models" stem (e.g. --out-file opgraph -> opgraph.rs, opgraph.ts).
        /// Multi-file targets (sdk, react-query, msw, mcp) are unaffected
        #[arg(long)]
        out_file: Option<String>,
    },

    /// Generate TypeSpec source from a schema (without emitting)
    Typespec {
        /// Input source: .ts, .yaml, .json, or .wasm file
        input: Utf8PathBuf,

        /// Output .tsp file (stdout if not specified)
        #[arg(short, long)]
        out: Option<Utf8PathBuf>,

        /// Namespace for generated TypeSpec
        #[arg(short, long)]
        namespace: Option<String>,
    },

    /// Publish a schema to an OCI registry as an artifact
    Publish {
        /// Input source: .ts, .yaml, .json, .wasm, or .graphql file
        input: Utf8PathBuf,

        /// Registry base URL (e.g. https://manifold.omni.dev)
        #[arg(short, long)]
        registry: String,

        /// Repository path (e.g. myteam/blog-api)
        #[arg(long)]
        repository: String,

        /// Tag for the published artifact
        #[arg(short, long, default_value = "latest")]
        tag: String,

        /// Bearer token (falls back to the ODK_REGISTRY_TOKEN env var)
        #[arg(long)]
        token: Option<String>,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Compile {
            input,
            config,
            out,
            emit,
            namespace,
            keep_temp,
            operations,
            introspect,
        } => cmd_compile(
            input, config, out, emit, namespace, keep_temp, operations, introspect,
        ),

        Commands::Init { lang, name } => cmd_init(lang, name),

        Commands::Build {
            input,
            out,
            release,
        } => builder::cmd_build(input, out, release),

        Commands::Check { input, operations } => cmd_check(input, operations),

        Commands::Generate {
            input,
            config,
            out,
            targets,
            operations,
            introspect,
            out_file,
        } => cmd_generate(
            input, config, out, targets, operations, introspect, out_file,
        ),

        Commands::Typespec {
            input,
            out,
            namespace,
        } => cmd_typespec(input, out, namespace),

        Commands::Publish {
            input,
            registry,
            repository,
            tag,
            token,
        } => cmd_publish(input, registry, repository, tag, token),
    }
}

/// Load a schema from the given input source (auto-detected by extension).
fn load_schema(input: &Utf8PathBuf) -> Result<CompiledSchema> {
    let ext = input.extension().unwrap_or("");

    match ext {
        "ts" => {
            // TypeScript schema via bun + odk-ts
            eprintln!("  Compiling TypeScript schema via bun...");
            ts_executor::compile_ts_schema(input)
        }
        "wasm" => {
            // WASM plugin via Extism
            extism_host::load_schema_from_plugin(input)
        }
        "json" => {
            let path = std::path::Path::new(input.as_str());

            // A standard JSON Schema document (schemars output, for example) is
            // a different thing from ODK's own JSON format, so it is detected
            // before the ODK parsers get a chance to half-read it
            let content =
                fs::read_to_string(input).with_context(|| format!("Failed to read {}", input))?;
            if loaders::is_json_schema(&content) {
                return loaders::load_json_schema(path)
                    .map_err(|e| anyhow::anyhow!("Failed to load JSON Schema: {}", e));
            }

            // ODK JSON: try the YAML-format parser first, then raw CompiledSchema
            match loaders::load_yaml_schema(path) {
                Ok(schema) => Ok(schema),
                Err(_) => {
                    // Fall back to raw CompiledSchema JSON
                    let content = fs::read_to_string(input)
                        .with_context(|| format!("Failed to read {}", input))?;
                    CompiledSchema::from_json(&content)
                        .with_context(|| format!("Failed to parse JSON schema from {}", input))
                }
            }
        }
        "yaml" | "yml" => {
            // YAML schema file (ODK format)
            let path = std::path::Path::new(input.as_str());
            loaders::load_yaml_schema(path)
                .map_err(|e| anyhow::anyhow!("Failed to load YAML schema: {}", e))
        }
        "graphql" | "gql" => {
            // GraphQL SDL schema file
            let path = std::path::Path::new(input.as_str());
            loaders::load_graphql_schema(path)
                .map_err(|e| anyhow::anyhow!("Failed to load GraphQL schema: {}", e))
        }
        _ => bail!(
            "Unsupported input format: .{}. Use .ts, .wasm, .json, .yaml, or .graphql",
            ext
        ),
    }
}

/// Compile command: load schema and emit to targets.
fn cmd_compile(
    input: Option<Utf8PathBuf>,
    config_path: Option<Utf8PathBuf>,
    out: Option<Utf8PathBuf>,
    emit: Option<Vec<String>>,
    namespace: Option<String>,
    keep_temp: bool,
    operations: Option<String>,
    introspect_url: Option<String>,
) -> Result<()> {
    // Load config file if present
    let cfg = if let Some(ref path) = config_path {
        eprintln!("Loading config from {}...", path);
        Some(config::load_config(path)?)
    } else if let Some(found) = config::find_config_file() {
        eprintln!("Using config file: {}", found);
        Some(config::load_config(&found)?)
    } else {
        None
    };

    // Merge config with CLI args (CLI takes precedence)
    let (schema_path, output_dir, emitters, ns) = if let Some(cfg) = cfg {
        let merged = config::merge_with_cli(cfg, input.as_ref(), out.as_ref(), &emit, &namespace);
        (merged.schema, merged.output, merged.emit, merged.namespace)
    } else {
        (
            input,
            out.unwrap_or_else(|| Utf8PathBuf::from("./generated")),
            emit.unwrap_or_default(),
            namespace,
        )
    };

    // Ensure we have a schema path
    let schema_path = schema_path.ok_or_else(|| {
        anyhow::anyhow!(
            "No schema file specified. Use: odk compile <schema> or set 'schema' in config file."
        )
    })?;

    // If --introspect is set, fetch schema from endpoint
    let mut schema = if let Some(url) = &introspect_url {
        eprintln!("Introspecting {}...", url);
        loaders::introspect_schema(url)
            .map_err(|e| anyhow::anyhow!("Introspection failed: {}", e))?
    } else {
        eprintln!("Loading schema from {}...", schema_path);
        load_schema(&schema_path)?
    };

    // If --operations is set, load operation documents
    if let Some(pattern) = &operations {
        eprintln!("Loading operations from {}...", pattern);
        let (ops, frags) = loaders::load_graphql_operations(pattern)
            .map_err(|e| anyhow::anyhow!("Failed to load operations: {}", e))?;
        for op in ops {
            schema.add_operation(op);
        }
        for frag in frags {
            schema.add_fragment(frag);
        }
        eprintln!(
            "  Loaded {} operations, {} fragments",
            schema.operations.len(),
            schema.fragments.len()
        );
    }

    eprintln!(
        "  Loaded: {} ({} models, {} unions, {} operations)",
        schema.name,
        schema.models.len(),
        schema.unions.len(),
        schema.operations.len()
    );

    compile_with_typespec(&schema, &emitters, &output_dir, ns, keep_temp)
}

/// Compile using TypeSpec emitters.
fn compile_with_typespec(
    schema: &CompiledSchema,
    emit: &[String],
    out: &Utf8PathBuf,
    namespace: Option<String>,
    keep_temp: bool,
) -> Result<()> {
    // Check that tsp is available
    if which::which("tsp").is_err() {
        bail!(
            "TypeSpec compiler (tsp) not found. Install it with:\n\
             npm install -g @typespec/compiler"
        );
    }

    // Default emitters if none specified
    let emitters: Vec<String> = if emit.is_empty() {
        vec![
            "@typespec/json-schema".to_string(),
            "@typespec/openapi3".to_string(),
        ]
    } else {
        emit.to_vec()
    };

    eprintln!("Using TypeSpec emitters: {}", emitters.join(", "));

    // Generate TypeSpec source. When protobuf is a requested emitter, the
    // bridge injects the protobuf decorators (@package/@message/@field) the
    // emitter requires, so a `.proto` is produced without hand-written
    // protobuf decorators in the schema
    let ns = namespace.as_deref().unwrap_or(&schema.name);
    let emit_options = typespec_bridge::emit_options_for(&emitters, ns);
    let tsp_source = typespec_bridge::compiled_to_typespec_with_options(schema, ns, &emit_options);

    // Create temp directory for TypeSpec project
    let temp_dir = tempfile::tempdir()?;
    let temp_path = Utf8PathBuf::try_from(temp_dir.path().to_path_buf())?;
    let tsp_file = temp_path.join("main.tsp");

    // Write TypeSpec source
    fs::write(&tsp_file, &tsp_source)?;

    // Create package.json with all requested emitters
    let mut deps = serde_json::Map::new();
    deps.insert("@typespec/compiler".into(), serde_json::json!("*"));
    for emitter in &emitters {
        deps.insert(emitter.clone(), serde_json::json!("*"));
    }
    // The generated TypeSpec imports whatever the schema declares (e.g.
    // "@typespec/http"), so those libraries must be installed too, not just the
    // emitters. An emitter that does not pull them in transitively (the Drizzle
    // emitter, unlike openapi3 which depends on @typespec/http) would otherwise
    // fail to resolve the import. Relative imports are files, not packages
    for import in &schema.imports {
        if import.starts_with('.') || import.starts_with('/') {
            continue;
        }
        deps.insert(import.clone(), serde_json::json!("*"));
    }
    let package_json = serde_json::json!({
        "name": "odk-temp-project",
        "type": "module",
        "dependencies": deps
    });
    fs::write(temp_path.join("package.json"), package_json.to_string())?;

    // Reuse an existing node_modules only when it already satisfies every
    // required package (the emitters plus the schema's declared imports).
    // Otherwise a schema that declares an import the host project has not
    // installed (e.g. @omnidotdev/typespec-drizzle) would resolve against an
    // incomplete node_modules and fail to compile, so fall back to a clean
    // install from the package.json written above
    let required: Vec<String> = deps.keys().cloned().collect();
    let search_start = Utf8PathBuf::try_from(std::env::current_dir()?)?;
    let reusable =
        find_node_modules(&search_start).filter(|nm| node_modules_has_packages(nm, &required));
    if let Some(node_modules) = reusable {
        let temp_node_modules = temp_path.join("node_modules");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&node_modules, &temp_node_modules)
            .with_context(|| "Failed to symlink node_modules".to_string())?;
        #[cfg(windows)]
        std::os::windows::fs::symlink_dir(&node_modules, &temp_node_modules)
            .with_context(|| "Failed to symlink node_modules".to_string())?;
        eprintln!("  Using node_modules from {}", node_modules.display());
    } else {
        eprintln!("  Installing TypeSpec dependencies...");
        let npm_output = Command::new("npm")
            .args(["install", "--silent"])
            .current_dir(&temp_path)
            .output()
            .context("Failed to run npm install")?;
        if !npm_output.status.success() {
            bail!(
                "npm install failed: {}",
                String::from_utf8_lossy(&npm_output.stderr)
            );
        }
    }

    // Create tspconfig.yaml
    let absolute_out = if out.is_absolute() {
        out.clone()
    } else {
        Utf8PathBuf::try_from(std::env::current_dir()?)?.join(out)
    };

    let tsp_config = format!(
        "output-dir: \"{}\"\nemit:\n{}\noptions:\n{}",
        absolute_out,
        emitters
            .iter()
            .map(|e| format!("  - \"{}\"", e))
            .collect::<Vec<_>>()
            .join("\n"),
        emitters
            .iter()
            .map(|e| emitter_options(e))
            .collect::<Vec<_>>()
            .join("\n")
    );
    fs::write(temp_path.join("tspconfig.yaml"), &tsp_config)?;

    // Ensure output directory exists
    fs::create_dir_all(&absolute_out)?;

    // Run TypeSpec compiler
    eprintln!("Running TypeSpec compiler...");
    let output = Command::new("tsp")
        .args(["compile", tsp_file.as_str()])
        .current_dir(&temp_path)
        .output()
        .context("Failed to run tsp compiler")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        eprintln!("TypeSpec stdout:\n{}", stdout);
        eprintln!("TypeSpec stderr:\n{}", stderr);
        bail!("TypeSpec compilation failed");
    }

    eprintln!("Generated output to {}", absolute_out);

    // Keep temp files if requested
    if keep_temp {
        let kept_path = temp_dir.keep();
        eprintln!("Kept temp files at: {}", kept_path.display());
    }

    Ok(())
}

/// Generate emitter-specific options for tspconfig.yaml.
fn emitter_options(emitter: &str) -> String {
    match emitter {
        // emitAllModels: false pairs with the `@jsonSchema` decorator the
        // bridge puts on the user namespace, so only the user's types emit and
        // an imported library's models (e.g. Drizzle options) do not leak
        "@typespec/json-schema" => format!(
            "  \"{}\":\n    emitter-output-dir: \"{{output-dir}}\"\n    emitAllModels: false\n    emitAllRefs: true",
            emitter
        ),
        "@typespec/openapi3" => format!(
            "  \"{}\":\n    emitter-output-dir: \"{{output-dir}}\"",
            emitter
        ),
        _ => format!(
            "  \"{}\":\n    emitter-output-dir: \"{{output-dir}}\"",
            emitter
        ),
    }
}

/// Find node_modules directory by searching upward.
fn find_node_modules(start: &Utf8PathBuf) -> Option<PathBuf> {
    let mut current = start.as_std_path().to_path_buf();
    loop {
        let node_modules = current.join("node_modules");
        if node_modules.is_dir() && node_modules.join("@typespec").is_dir() {
            return Some(node_modules);
        }
        if !current.pop() {
            return None;
        }
    }
}

/// Whether an existing node_modules already contains every required package, so
/// it can be reused instead of running a fresh install. A scoped package name
/// (`@scope/name`) maps to a nested directory, which `Path::join` handles
fn node_modules_has_packages(node_modules: &std::path::Path, packages: &[String]) -> bool {
    packages.iter().all(|pkg| node_modules.join(pkg).is_dir())
}

/// Init command: create a new ODK project.
fn cmd_init(lang: Option<String>, name: Option<String>) -> Result<()> {
    use templates::ProjectLang;

    // Determine project name
    let project_name = match name {
        Some(n) => n,
        None => {
            // Use current directory name
            std::env::current_dir()?
                .file_name()
                .and_then(|n| n.to_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| "my-schema".to_string())
        }
    };

    // Determine language (interactive if not specified)
    let project_lang = match lang {
        Some(l) => ProjectLang::from_str(&l).ok_or_else(|| {
            anyhow::anyhow!("Unknown language: '{}'. Use: rust, python, or yaml", l)
        })?,
        None => prompt_for_language()?,
    };

    eprintln!(
        "Initializing {} project '{}'...",
        project_lang.display_name(),
        project_name
    );

    // Create project based on language
    let is_directory = match project_lang {
        ProjectLang::Rust => {
            // Create directory structure
            let dir = std::path::Path::new(&project_name);
            fs::create_dir_all(dir.join("src"))?;

            // Write Cargo.toml
            let cargo_toml = templates::render(templates::RUST_CARGO_TOML, &project_name);
            fs::write(dir.join("Cargo.toml"), cargo_toml)?;

            // Write src/lib.rs
            let lib_rs = templates::render(templates::RUST_LIB_RS, &project_name);
            fs::write(dir.join("src/lib.rs"), lib_rs)?;

            true
        }
        ProjectLang::Python => {
            // Write schema.py in current directory
            let schema_py = templates::render(templates::PYTHON_SCHEMA, &project_name);
            fs::write("schema.py", schema_py)?;

            false
        }
        ProjectLang::Yaml => {
            // Write schema.yaml in current directory
            let schema_yaml = templates::render(templates::YAML_SCHEMA, &project_name);
            fs::write("schema.yaml", schema_yaml)?;

            false
        }
    };

    // Print success message with next steps
    eprintln!(
        "{}",
        templates::post_init_message(project_lang, &project_name, is_directory)
    );

    Ok(())
}

/// Prompt user to select a language interactively
fn prompt_for_language() -> Result<templates::ProjectLang> {
    use std::io::{self, Write};

    eprintln!("Select a project type:");
    for (i, lang) in templates::ProjectLang::all().iter().enumerate() {
        eprintln!("  {}. {}", i + 1, lang.display_name());
    }
    eprint!("Enter choice [1-3]: ");
    io::stderr().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    let choice: usize = input
        .trim()
        .parse()
        .map_err(|_| anyhow::anyhow!("Invalid choice. Please enter 1, 2, or 3."))?;

    templates::ProjectLang::all()
        .get(choice.saturating_sub(1))
        .copied()
        .ok_or_else(|| anyhow::anyhow!("Invalid choice. Please enter 1, 2, or 3."))
}

/// Check command: validate a schema without emitting.
fn cmd_check(input: Utf8PathBuf, operations: Option<String>) -> Result<()> {
    eprintln!("Checking {}...", input);

    let mut schema = load_schema(&input)?;

    if let Some(pattern) = &operations {
        let (ops, frags) = loaders::load_graphql_operations(pattern)
            .map_err(|e| anyhow::anyhow!("Failed to load operations: {}", e))?;
        for op in ops {
            schema.add_operation(op);
        }
        for frag in frags {
            schema.add_fragment(frag);
        }
    }

    println!("Schema: {}", schema.name);
    println!("Models: {}", schema.models.len());
    for model in &schema.models {
        println!("  - {} ({} fields)", model.name, model.fields.len());
    }
    println!("Unions: {}", schema.unions.len());
    for union in &schema.unions {
        println!("  - {} ({} variants)", union.name, union.variants.len());
    }
    println!("Operations: {}", schema.operations.len());
    for op in &schema.operations {
        println!("  - {} ({:?})", op.name, op.kind);
    }
    println!("Fragments: {}", schema.fragments.len());
    for frag in &schema.fragments {
        println!("  - {} on {}", frag.name, frag.type_condition);
    }

    if let Some(warnings) = &schema.warnings {
        if !warnings.is_empty() {
            println!("\nWarnings:");
            for w in warnings {
                println!("  - {}", w);
            }
        }
    }

    println!("\nSchema is valid!");
    Ok(())
}

/// Generate command: produce client artifacts from schema + operations.
fn cmd_generate(
    input: Option<Utf8PathBuf>,
    config_path: Option<Utf8PathBuf>,
    out: Utf8PathBuf,
    targets_str: String,
    operations: Option<String>,
    introspect_url: Option<String>,
    out_file: Option<String>,
) -> Result<()> {
    use odk_cli::generate::{self, Target};

    // Load config file if present
    let cfg = if let Some(ref path) = config_path {
        Some(config::load_config(path)?)
    } else if let Some(found) = config::find_config_file() {
        eprintln!("Using config file: {}", found);
        Some(config::load_config(&found)?)
    } else {
        None
    };
    let gen_cfg = cfg.as_ref().and_then(|c| c.generate.as_ref());

    // Merge: CLI flags take precedence over config
    let schema_input = input.or_else(|| cfg.as_ref().and_then(|c| c.schema.clone()));
    let final_targets_str = if targets_str == "sdk,react-query,msw" {
        // Only use config targets if CLI is still at default
        gen_cfg
            .filter(|g| !g.targets.is_empty())
            .map(|g| g.targets.join(","))
            .unwrap_or(targets_str)
    } else {
        targets_str
    };
    let final_operations = operations.or_else(|| gen_cfg.and_then(|g| g.operations.clone()));
    let final_out = if out == Utf8PathBuf::from("./generated") {
        gen_cfg.and_then(|g| g.output.clone()).unwrap_or(out)
    } else {
        out
    };

    // Parse targets
    let targets = Target::parse_list(&final_targets_str).map_err(|e| anyhow::anyhow!(e))?;

    if targets.is_empty() {
        bail!(
            "No targets specified. Available: sdk, react-query, msw, mcp, python, typescript, rust"
        );
    }

    // Load schema
    let mut schema = if let Some(url) = &introspect_url {
        eprintln!("Introspecting {}...", url);
        loaders::introspect_schema(url)
            .map_err(|e| anyhow::anyhow!("Introspection failed: {}", e))?
    } else if let Some(ref input_path) = schema_input {
        eprintln!("Loading schema from {}...", input_path);
        load_schema(input_path)?
    } else {
        bail!("No schema source. Provide an input file or --introspect URL.");
    };

    // Load operations
    if let Some(pattern) = &final_operations {
        eprintln!("Loading operations from {}...", pattern);
        let (ops, frags) = loaders::load_graphql_operations(pattern)
            .map_err(|e| anyhow::anyhow!("Failed to load operations: {}", e))?;
        for op in ops {
            schema.add_operation(op);
        }
        for frag in frags {
            schema.add_fragment(frag);
        }
    }

    // The client targets are built from operations; model generators are built
    // from types and are legitimately operation-free
    let needs_operations = targets
        .iter()
        .any(|t| *t != Target::Python && *t != Target::Typescript && *t != Target::Rust);

    if needs_operations && schema.operations.is_empty() {
        bail!(
            "No operations found. Provide operation documents via --operations \
             or include them in the schema file."
        );
    }

    if schema.operations.is_empty() {
        eprintln!(
            "  {} models, {} unions",
            schema.models.len(),
            schema.unions.len()
        );
    } else {
        eprintln!(
            "  {} operations, {} fragments",
            schema.operations.len(),
            schema.fragments.len()
        );
    }

    // Generate
    let target_names: Vec<String> = targets.iter().map(|t| t.to_string()).collect();
    eprintln!("Generating targets: {}", target_names.join(", "));

    // Extract MCP config if present
    let mcp_config = cfg
        .as_ref()
        .and_then(|c| c.generate.as_ref())
        .and_then(|g| g.mcp.as_ref());

    let mut output = generate::generate(&schema, &targets, mcp_config);

    // Rename the model output stem if requested (e.g. --out-file opgraph ->
    // opgraph.rs / opgraph.ts)
    if let Some(stem) = &out_file {
        output = rename_model_stem(output, stem);
    }

    // Write output files
    fs::create_dir_all(&final_out)
        .with_context(|| format!("Failed to create output directory: {}", final_out))?;

    for (filename, content) in &output {
        let path = final_out.join(filename);
        fs::write(&path, content).with_context(|| format!("Failed to write {}", path))?;
        eprintln!("  Wrote {}", path);
    }

    eprintln!("Done! {} files generated.", output.len());
    Ok(())
}

/// Rename the model output stem ("models.<ext>") to a caller-supplied base
/// name, e.g. "opgraph" -> opgraph.rs / opgraph.ts. Only the model emitters
/// produce "models.<ext>"; multi-file targets (sdk, react-query, msw, mcp)
/// keep their own semantic names.
fn rename_model_stem(
    output: std::collections::BTreeMap<String, String>,
    stem: &str,
) -> std::collections::BTreeMap<String, String> {
    output
        .into_iter()
        .map(|(name, content)| match name.strip_prefix("models.") {
            Some(ext) => (format!("{stem}.{ext}"), content),
            None => (name, content),
        })
        .collect()
}

/// Publish command: push a schema to an OCI registry as an artifact.
fn cmd_publish(
    input: Utf8PathBuf,
    registry: String,
    repository: String,
    tag: String,
    token: Option<String>,
) -> Result<()> {
    use odk_cli::publish::{self, PublishTarget};

    eprintln!("Loading schema from {input}...");
    let schema = load_schema(&input)?;

    // an explicit --token wins, else fall back to the environment
    let token = token.or_else(|| std::env::var("ODK_REGISTRY_TOKEN").ok());
    let target = PublishTarget {
        registry,
        repository,
        tag,
        token,
    };

    eprintln!(
        "Publishing to {}/v2/{}:{}...",
        target.registry.trim_end_matches('/'),
        target.repository,
        target.tag
    );
    let reference = publish::publish(&schema, &target)?;
    println!("Published {reference}");
    Ok(())
}

/// Typespec command: generate TypeSpec source only.
fn cmd_typespec(
    input: Utf8PathBuf,
    out: Option<Utf8PathBuf>,
    namespace: Option<String>,
) -> Result<()> {
    let schema = load_schema(&input)?;
    let ns = namespace.as_deref().unwrap_or(&schema.name);
    let tsp_source = typespec_bridge::compiled_to_typespec(&schema, ns);

    match out {
        Some(path) => {
            fs::write(&path, &tsp_source)?;
            eprintln!("Wrote TypeSpec to {}", path);
        }
        None => {
            println!("{}", tsp_source);
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{node_modules_has_packages, rename_model_stem};
    use std::collections::BTreeMap;

    #[test]
    fn node_modules_reused_only_when_all_required_packages_present() {
        let dir = tempfile::tempdir().unwrap();
        let nm = dir.path().join("node_modules");
        std::fs::create_dir_all(nm.join("@typespec/compiler")).unwrap();
        std::fs::create_dir_all(nm.join("@typespec/openapi3")).unwrap();

        let present = [
            "@typespec/compiler".to_string(),
            "@typespec/openapi3".to_string(),
        ];
        assert!(node_modules_has_packages(&nm, &present));

        // a declared import missing from the host node_modules must force a
        // clean install rather than reuse (the Drizzle compile-path bug)
        let missing = [
            "@typespec/compiler".to_string(),
            "@omnidotdev/typespec-drizzle".to_string(),
        ];
        assert!(!node_modules_has_packages(&nm, &missing));
    }

    #[test]
    fn out_file_renames_only_the_models_stem() {
        let mut out = BTreeMap::new();
        out.insert("models.rs".to_string(), "r".to_string());
        out.insert("models.ts".to_string(), "t".to_string());
        // a multi-file target's output keeps its own name
        out.insert("client.ts".to_string(), "c".to_string());

        let renamed = rename_model_stem(out, "opgraph");

        assert_eq!(renamed.get("opgraph.rs").map(String::as_str), Some("r"));
        assert_eq!(renamed.get("opgraph.ts").map(String::as_str), Some("t"));
        assert_eq!(renamed.get("client.ts").map(String::as_str), Some("c"));
        assert!(!renamed.contains_key("models.rs"));
    }
}