spikard-cli 0.15.6-rc.1

Command-line interface for building and validating Spikard applications
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
//! Spikard CLI – user-facing code generation + testing helpers

use crate::app;
use crate::codegen::{
    self, CodegenOutcome, CodegenRequest, CodegenTargetKind, DtoConfig, NodeDtoStyle, PythonDtoStyle, RubyDtoStyle,
    SchemaKind, TargetLanguage,
};
use crate::init::{InitRequest, InitResponse};
use anyhow::{Context, Result, bail};
use clap::{Args, Parser, Subcommand, ValueEnum};
use scythe_core::dialect::SqlDialect;
use spikard_codegen::sql::DecimalMode;
use std::ffi::OsString;
use std::path::PathBuf;

/// Spikard - High-performance HTTP framework with Rust core
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Initialize a new Spikard project
    Init(InitArgs),
    /// Start the Spikard MCP server
    #[cfg(feature = "mcp")]
    Mcp(McpArgs),
    /// User-facing code generation entrypoints
    Generate {
        #[command(subcommand)]
        target: GenerateCommand,
    },
    /// Test-fixture generation helpers (used by the internal e2e suite)
    Testing {
        #[command(subcommand)]
        target: TestingCommand,
    },
    /// Validate an `AsyncAPI` specification
    ValidateAsyncapi {
        /// Path to `AsyncAPI` schema file (JSON or YAML)
        schema: PathBuf,
    },
    /// Show information about Spikard
    Features,
}

#[derive(Args, Debug)]
struct InitArgs {
    /// Name of the project to create
    name: String,

    /// Target programming language
    #[arg(long, short = 'l', default_value = "python")]
    lang: InitLanguage,

    /// Directory where the project will be created (default: current directory)
    #[arg(long, short = 'd', default_value = ".")]
    dir: PathBuf,
}

#[cfg(feature = "mcp")]
#[derive(Args, Debug)]
struct McpArgs {
    /// Transport for the MCP server
    #[arg(long, default_value = "stdio")]
    transport: String,

    /// Host to bind when using HTTP transport
    #[arg(long, default_value = "127.0.0.1")]
    host: String,

    /// Port to bind when using HTTP transport
    #[arg(long, default_value_t = 3001)]
    port: u16,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum InitLanguage {
    #[value(name = "python")]
    Python,
    #[value(name = "typescript")]
    TypeScript,
    #[value(name = "rust")]
    Rust,
    #[value(name = "ruby")]
    Ruby,
    #[value(name = "php")]
    Php,
    #[value(name = "elixir")]
    Elixir,
}

impl From<InitLanguage> for TargetLanguage {
    fn from(lang: InitLanguage) -> Self {
        match lang {
            InitLanguage::Python => Self::Python,
            InitLanguage::TypeScript => Self::TypeScript,
            InitLanguage::Rust => Self::Rust,
            InitLanguage::Ruby => Self::Ruby,
            InitLanguage::Php => Self::Php,
            InitLanguage::Elixir => Self::Elixir,
        }
    }
}

#[derive(Subcommand, Debug)]
enum GenerateCommand {
    /// Generate REST handlers from `OpenAPI` schemas
    Openapi(OpenapiArgs),
    /// Generate `AsyncAPI` handler scaffolding (SSE/WebSocket)
    Asyncapi(AsyncapiHandlerArgs),
    /// Generate JSON-RPC 2.0 handlers from `OpenRPC` schemas
    Jsonrpc(JsonrpcArgs),
    /// Generate GraphQL types, resolvers, or schema
    Graphql(GraphqlArgs),
    /// Generate protobuf messages and gRPC services
    Protobuf(ProtobufArgs),
    /// Generate PHP DTO classes (Request/Response) for Spikard integration
    PhpDto(PhpDtoArgs),
    /// Generate routes + OpenAPI + sidecar from annotated SQL queries (via scythe)
    Sql(SqlArgs),
}

#[derive(Args, Debug)]
struct SqlArgs {
    /// Directory (or single file) holding `.sql` query files annotated with
    /// `-- @http <METHOD> <PATH>` etc.
    queries: PathBuf,

    /// Path(s) to schema DDL — accepts files or directories. Repeat for multiple.
    #[arg(long = "schema", required = true)]
    schema: Vec<PathBuf>,

    /// SQL dialect (postgresql, mysql, sqlite, mssql, oracle, redshift, snowflake)
    #[arg(long, default_value = "postgresql")]
    dialect: SqlDialectArg,

    /// Output directory (created if missing).
    #[arg(long, short = 'o', default_value = "generated")]
    output: PathBuf,

    /// Target languages for sidecar entries. Repeat for multiple.
    #[arg(long = "lang", num_args = 1..)]
    lang: Vec<GenerateLanguage>,

    /// How to render the `decimal` neutral type. `string-pattern` (default)
    /// is lossless; `number` is lossy but ergonomic.
    #[arg(long, default_value = "string-pattern")]
    decimal_mode: DecimalModeArg,

    /// Fail on unrecognised neutral types instead of falling back to any-JSON.
    #[arg(long, default_value_t = false)]
    strict: bool,

    /// Skip emitting the OpenAPI 3.1 spec alongside routes + sidecar.
    #[arg(long = "no-openapi", default_value_t = false)]
    no_openapi: bool,

    /// API title for the OpenAPI spec.
    #[arg(long, default_value = "Generated API")]
    api_title: String,

    /// API version for the OpenAPI spec.
    #[arg(long, default_value = "0.1.0")]
    api_version: String,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum SqlDialectArg {
    #[value(name = "postgresql", alias = "postgres", alias = "redshift", alias = "cockroachdb")]
    PostgreSQL,
    #[value(name = "mysql", alias = "mariadb")]
    MySQL,
    #[value(name = "sqlite")]
    SQLite,
    #[value(name = "mssql", alias = "sqlserver")]
    MsSql,
    #[value(name = "oracle")]
    Oracle,
    #[value(name = "snowflake")]
    Snowflake,
}

impl From<SqlDialectArg> for SqlDialect {
    fn from(d: SqlDialectArg) -> Self {
        match d {
            SqlDialectArg::PostgreSQL => SqlDialect::PostgreSQL,
            SqlDialectArg::MySQL => SqlDialect::MySQL,
            SqlDialectArg::SQLite => SqlDialect::SQLite,
            SqlDialectArg::MsSql => SqlDialect::MsSql,
            SqlDialectArg::Oracle => SqlDialect::Oracle,
            SqlDialectArg::Snowflake => SqlDialect::Snowflake,
        }
    }
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum DecimalModeArg {
    #[value(name = "string-pattern")]
    StringPattern,
    #[value(name = "number")]
    Number,
}

impl From<DecimalModeArg> for DecimalMode {
    fn from(m: DecimalModeArg) -> Self {
        match m {
            DecimalModeArg::StringPattern => DecimalMode::StringPattern,
            DecimalModeArg::Number => DecimalMode::Number,
        }
    }
}

#[derive(Args, Debug)]
struct OpenapiArgs {
    /// Path to `OpenAPI` schema file (JSON or YAML)
    schema: PathBuf,

    /// Target language for code generation
    #[arg(long, short = 'l', default_value = "python")]
    lang: GenerateLanguage,

    /// Output file path (prints to stdout if not specified)
    #[arg(long, short = 'o')]
    output: Option<PathBuf>,

    /// DTO implementation for the selected language (defaults per language)
    #[arg(long = "dto", value_enum)]
    dto: Option<DtoArg>,
}

#[derive(Args, Debug)]
struct AsyncapiHandlerArgs {
    /// Path to `AsyncAPI` schema file (JSON or YAML)
    schema: PathBuf,

    /// Target language for handler scaffolding
    #[arg(long, short = 'l')]
    lang: GenerateLanguage,

    /// Output file path
    #[arg(long, short = 'o')]
    output: PathBuf,

    /// DTO implementation for the selected language (defaults per language)
    #[arg(long = "dto", value_enum)]
    dto: Option<DtoArg>,
}

#[derive(Args, Debug)]
struct JsonrpcArgs {
    /// Path to `OpenRPC` schema file (JSON or YAML)
    schema: PathBuf,

    /// Target language for handler scaffolding
    #[arg(long, short = 'l', default_value = "python")]
    lang: GenerateLanguage,

    /// Output file path (prints to stdout if not specified)
    #[arg(long, short = 'o')]
    output: Option<PathBuf>,
}

#[derive(Args, Debug)]
struct GraphqlArgs {
    /// Path to GraphQL schema file (.graphql, .gql, or .json for introspection)
    schema: PathBuf,

    /// Target language (python, typescript, rust, ruby, php)
    #[arg(long, short = 'l', default_value = "python")]
    lang: GenerateLanguage,

    /// Output file path (prints to stdout if not specified)
    #[arg(long, short = 'o')]
    output: Option<PathBuf>,

    /// Target specific features (all, types, resolvers, schema)
    #[arg(long, default_value = "all")]
    target: String,
}

#[derive(Args, Debug)]
struct ProtobufArgs {
    /// Path to .proto schema file
    schema: PathBuf,

    /// Target language (python, typescript, ruby, php)
    #[arg(long, short = 'l', default_value = "python")]
    lang: GenerateLanguage,

    /// Output file path
    #[arg(long, short = 'o')]
    output: PathBuf,

    /// Target: all, messages, or services
    #[arg(long, default_value = "all")]
    target: String,

    /// Additional import directories used to resolve imported .proto files
    #[arg(long = "include")]
    include: Vec<PathBuf>,
}

#[derive(Subcommand, Debug)]
enum TestingCommand {
    /// AsyncAPI-specific fixture + harness generators
    Asyncapi {
        #[command(subcommand)]
        target: AsyncapiTestingTarget,
    },
}

#[derive(Subcommand, Debug)]
enum AsyncapiTestingTarget {
    /// Generate test fixtures from message schemas
    Fixtures(AsyncFixtureArgs),
    /// Generate test application for a specific language
    TestApp(AsyncTestAppArgs),
    /// Generate everything (fixtures + test apps for all languages)
    All(AsyncAllArgs),
}

#[derive(Args, Debug)]
struct AsyncFixtureArgs {
    /// Path to `AsyncAPI` schema file (JSON or YAML)
    schema: PathBuf,
    /// Output directory for fixtures (default: `testing_data`/)
    #[arg(long, short = 'o', default_value = "testing_data")]
    output: PathBuf,
}

#[derive(Args, Debug)]
struct AsyncTestAppArgs {
    /// Path to `AsyncAPI` schema file (JSON or YAML)
    schema: PathBuf,
    /// Target language
    #[arg(long, short = 'l')]
    lang: GenerateLanguage,
    /// Output file path
    #[arg(long, short = 'o')]
    output: PathBuf,
}

#[derive(Args, Debug)]
struct AsyncAllArgs {
    /// Path to `AsyncAPI` schema file (JSON or YAML)
    schema: PathBuf,
    /// Output directory (default: current directory)
    #[arg(long, short = 'o', default_value = ".")]
    output: PathBuf,
}

#[derive(Args, Debug)]
struct PhpDtoArgs {
    /// Output directory for generated DTO classes (default: src/Generated)
    #[arg(long, short = 'o', default_value = "src/Generated")]
    output: PathBuf,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum GenerateLanguage {
    #[value(name = "python")]
    Python,
    #[value(name = "typescript")]
    TypeScript,
    #[value(name = "rust")]
    Rust,
    #[value(name = "ruby")]
    Ruby,
    #[value(name = "php")]
    Php,
    #[value(name = "elixir")]
    Elixir,
}

impl From<GenerateLanguage> for codegen::TargetLanguage {
    fn from(lang: GenerateLanguage) -> Self {
        match lang {
            GenerateLanguage::Python => Self::Python,
            GenerateLanguage::TypeScript => Self::TypeScript,
            GenerateLanguage::Rust => Self::Rust,
            GenerateLanguage::Ruby => Self::Ruby,
            GenerateLanguage::Php => Self::Php,
            GenerateLanguage::Elixir => Self::Elixir,
        }
    }
}

fn apply_dto_selection(config: &mut DtoConfig, lang: GenerateLanguage, dto: DtoArg) -> Result<()> {
    match lang {
        GenerateLanguage::Python => match dto {
            DtoArg::Dataclass => config.python = PythonDtoStyle::Dataclass,
            DtoArg::Msgspec => config.python = PythonDtoStyle::Msgspec,
            _ => bail!("DTO '{dto:?}' is not supported for Python"),
        },
        GenerateLanguage::TypeScript => match dto {
            DtoArg::Zod => config.node = NodeDtoStyle::Zod,
            _ => bail!("DTO '{dto:?}' is not supported for TypeScript"),
        },
        GenerateLanguage::Ruby => match dto {
            DtoArg::DrySchema => config.ruby = RubyDtoStyle::DrySchema,
            _ => bail!("DTO '{dto:?}' is not supported for Ruby"),
        },
        GenerateLanguage::Rust => match dto {
            DtoArg::Serde => config.rust = codegen::RustDtoStyle::SerdeStruct,
            _ => bail!("DTO '{dto:?}' is not supported for Rust"),
        },
        GenerateLanguage::Php => match dto {
            DtoArg::ReadonlyClass => config.php = codegen::PhpDtoStyle::ReadonlyClass,
            _ => bail!("DTO '{dto:?}' is not supported for PHP"),
        },
        GenerateLanguage::Elixir => bail!("DTO '{dto:?}' is not supported for Elixir"),
    }
    Ok(())
}

fn default_jsonrpc_output(lang: GenerateLanguage) -> PathBuf {
    let ext = match lang {
        GenerateLanguage::Python => "py",
        GenerateLanguage::TypeScript => "ts",
        GenerateLanguage::Rust => "rs",
        GenerateLanguage::Ruby => "rb",
        GenerateLanguage::Php => "php",
        GenerateLanguage::Elixir => "ex",
    };

    PathBuf::from(format!("handlers.{ext}"))
}

fn default_graphql_output(lang: GenerateLanguage) -> PathBuf {
    let ext = match lang {
        GenerateLanguage::Python => "py",
        GenerateLanguage::TypeScript => "ts",
        GenerateLanguage::Rust => "rs",
        GenerateLanguage::Ruby => "rb",
        GenerateLanguage::Php => "php",
        GenerateLanguage::Elixir => "ex",
    };

    PathBuf::from(format!("generated.{ext}"))
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum DtoArg {
    Dataclass,
    Msgspec,
    Zod,
    DrySchema,
    Serde,
    ReadonlyClass,
}

pub fn run_from_env() -> Result<()> {
    run(Cli::parse())
}

pub fn run_from<I, T>(args: I) -> Result<()>
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
{
    run(Cli::try_parse_from(args)?)
}

fn run(cli: Cli) -> Result<()> {
    match cli.command {
        Commands::Init(args) => {
            println!("Creating new Spikard project...");
            println!("  Project name: {}", args.name);
            println!("  Language: {:?}", args.lang);
            println!("  Directory: {}", args.dir.display());
            println!();

            let request = InitRequest {
                project_name: args.name.clone(),
                language: args.lang.into(),
                project_dir: args.dir.join(&args.name),
                schema_path: None,
            };

            match app::init_project(request) {
                Ok(response) => {
                    print_init_response(response);
                }
                Err(e) => {
                    eprintln!("✗ Failed to create project: {e}");
                    return Err(e);
                }
            }
        }
        #[cfg(feature = "mcp")]
        Commands::Mcp(args) => {
            let runtime = tokio::runtime::Runtime::new().context("Failed to create Tokio runtime for MCP server")?;
            match args.transport.to_ascii_lowercase().as_str() {
                "stdio" => runtime
                    .block_on(crate::mcp::start_mcp_server())
                    .map_err(|error| anyhow::anyhow!(error.to_string()))
                    .context("Failed to start MCP server over stdio")?,
                "http" => {
                    #[cfg(not(feature = "mcp-http"))]
                    {
                        bail!("HTTP transport requires the 'mcp-http' feature");
                    }

                    #[cfg(feature = "mcp-http")]
                    runtime
                        .block_on(crate::mcp::start_mcp_server_http(&args.host, args.port))
                        .map_err(|error| anyhow::anyhow!(error.to_string()))
                        .with_context(|| {
                            format!("Failed to start MCP server over http://{}:{}", args.host, args.port)
                        })?;
                }
                other => bail!("Unknown MCP transport '{other}'. Use 'stdio' or 'http'"),
            }
        }
        Commands::Generate { target } => match target {
            GenerateCommand::PhpDto(args) => {
                println!("Generating PHP DTO classes for Spikard...");
                println!("  Output directory: {}", args.output.display());
                let assets = app::generate_php_dto(&args.output)?;
                print_codegen_outcome(CodegenOutcome::Files(assets));
            }
            GenerateCommand::Sql(args) => {
                if args.lang.is_empty() {
                    bail!("At least one --lang is required for `generate sql` (e.g. --lang python --lang typescript)");
                }
                println!("Generating handlers from annotated SQL...");
                println!("  Queries: {}", args.queries.display());
                println!("  Output:  {}", args.output.display());
                let languages: Vec<TargetLanguage> = args.lang.iter().map(|l| (*l).into()).collect();
                let request = CodegenRequest {
                    schema_path: args.queries.clone(),
                    schema_kind: SchemaKind::Sql,
                    target: CodegenTargetKind::SqlHandlers {
                        schema_paths: args.schema.clone(),
                        output: args.output,
                        dialect: args.dialect.into(),
                        languages,
                        decimal_mode: args.decimal_mode.into(),
                        strict: args.strict,
                        emit_openapi: !args.no_openapi,
                        api_title: args.api_title,
                        api_version: args.api_version,
                    },
                    dto: None,
                };
                let outcome = app::execute_codegen(request).context("Failed to generate handlers from SQL")?;
                print_codegen_outcome(outcome);
            }
            GenerateCommand::Openapi(args) => {
                let mut dto_config = DtoConfig::default();
                if let Some(arg) = args.dto {
                    apply_dto_selection(&mut dto_config, args.lang, arg)?;
                }
                let request = CodegenRequest {
                    schema_path: args.schema.clone(),
                    schema_kind: SchemaKind::OpenApi,
                    target: CodegenTargetKind::Server {
                        language: args.lang.into(),
                        output: args.output,
                    },
                    dto: Some(dto_config),
                };

                let outcome = app::execute_codegen(request).context("Failed to generate code from OpenAPI schema")?;
                print_codegen_outcome(outcome);
            }
            GenerateCommand::Asyncapi(args) => {
                println!("Generating handler scaffolding from AsyncAPI schema...");
                println!("  Input: {}", args.schema.display());
                println!("  Language: {:?}", args.lang);
                println!("  Output: {}", args.output.display());
                let mut dto_config = DtoConfig::default();
                if let Some(arg) = args.dto {
                    apply_dto_selection(&mut dto_config, args.lang, arg)?;
                }
                let request = CodegenRequest {
                    schema_path: args.schema.clone(),
                    schema_kind: SchemaKind::AsyncApi,
                    target: CodegenTargetKind::AsyncHandlers {
                        language: args.lang.into(),
                        output: args.output,
                    },
                    dto: Some(dto_config),
                };
                print_codegen_outcome(app::execute_codegen(request)?);
            }
            GenerateCommand::Jsonrpc(args) => {
                println!("Generating JSON-RPC 2.0 handlers from OpenRPC schema...");
                println!("  Input: {}", args.schema.display());
                println!("  Language: {:?}", args.lang);
                if let Some(ref path) = args.output {
                    println!("  Output: {}", path.display());
                }
                let request = CodegenRequest {
                    schema_path: args.schema.clone(),
                    schema_kind: SchemaKind::OpenRpc,
                    target: CodegenTargetKind::JsonRpcHandlers {
                        language: args.lang.into(),
                        output: args.output.unwrap_or_else(|| default_jsonrpc_output(args.lang)),
                    },
                    dto: None,
                };

                let outcome = app::execute_codegen(request).context("Failed to generate code from OpenRPC schema")?;
                print_codegen_outcome(outcome);
            }
            GenerateCommand::Graphql(args) => {
                println!("Generating GraphQL code from schema...");
                println!("  Input: {}", args.schema.display());
                println!("  Language: {:?}", args.lang);
                println!("  Target: {}", args.target);
                if let Some(ref path) = args.output {
                    println!("  Output: {}", path.display());
                }
                let output_path = args.output.clone().unwrap_or_else(|| default_graphql_output(args.lang));

                let request = CodegenRequest {
                    schema_path: args.schema.clone(),
                    schema_kind: SchemaKind::GraphQL,
                    target: CodegenTargetKind::GraphQL {
                        language: args.lang.into(),
                        output: output_path,
                        target: args.target,
                    },
                    dto: None,
                };

                let outcome = app::execute_codegen(request).context("Failed to generate code from GraphQL schema")?;
                print_codegen_outcome(outcome);
            }
            GenerateCommand::Protobuf(args) => {
                println!("Generating protobuf code from schema...");
                println!("  Input: {}", args.schema.display());
                println!("  Language: {:?}", args.lang);
                println!("  Target: {}", args.target);
                println!("  Output: {}", args.output.display());

                let request = CodegenRequest {
                    schema_path: args.schema.clone(),
                    schema_kind: SchemaKind::Protobuf,
                    target: CodegenTargetKind::Protobuf {
                        language: args.lang.into(),
                        output: args.output.clone(),
                        target: args.target,
                        include_paths: args.include,
                    },
                    dto: None,
                };

                let outcome = app::execute_codegen(request).context("Failed to generate protobuf code")?;
                print_codegen_outcome(outcome);
            }
        },
        Commands::Testing { target } => match target {
            TestingCommand::Asyncapi { target } => match target {
                AsyncapiTestingTarget::Fixtures(args) => {
                    println!("Generating test fixtures from AsyncAPI schema...");
                    println!("  Input: {}", args.schema.display());
                    println!("  Output: {}", args.output.display());
                    let request = CodegenRequest {
                        schema_path: args.schema.clone(),
                        schema_kind: SchemaKind::AsyncApi,
                        target: CodegenTargetKind::AsyncFixtures { output: args.output },
                        dto: None,
                    };
                    let files = match app::execute_codegen_unvalidated(request)? {
                        CodegenOutcome::Files(files) => files,
                        CodegenOutcome::InMemory(_) => unreachable!("Fixtures always write files"),
                    };
                    println!("\n✓ Generated {} fixture files", files.len());
                }
                AsyncapiTestingTarget::TestApp(args) => {
                    println!("Generating test application from AsyncAPI schema...");
                    println!("  Input: {}", args.schema.display());
                    println!("  Language: {:?}", args.lang);
                    println!("  Output: {}", args.output.display());
                    let request = CodegenRequest {
                        schema_path: args.schema.clone(),
                        schema_kind: SchemaKind::AsyncApi,
                        target: CodegenTargetKind::AsyncTestApp {
                            language: args.lang.into(),
                            output: args.output,
                        },
                        dto: None,
                    };
                    print_codegen_outcome(app::execute_codegen_unvalidated(request)?);
                }
                AsyncapiTestingTarget::All(args) => {
                    println!("Generating all assets from AsyncAPI schema...");
                    println!("  Input: {}", args.schema.display());
                    println!("  Output directory: {}", args.output.display());
                    let request = CodegenRequest {
                        schema_path: args.schema.clone(),
                        schema_kind: SchemaKind::AsyncApi,
                        target: CodegenTargetKind::AsyncAll { output: args.output },
                        dto: None,
                    };
                    let files = match app::execute_codegen_unvalidated(request)? {
                        CodegenOutcome::Files(files) => files,
                        CodegenOutcome::InMemory(_) => unreachable!("AsyncAPI bundle writes files"),
                    };
                    println!("\n✓ Generated {} assets:", files.len());
                    for asset in files {
                        println!("  - {} -> {}", asset.description, asset.path.display());
                    }
                }
            },
        },
        Commands::Features => {
            print_feature_summary(app::feature_summary());
        }
        Commands::ValidateAsyncapi { schema } => {
            print_asyncapi_validation(app::validate_asyncapi_schema(&schema)?);
        }
    }

    Ok(())
}

fn print_init_response(response: InitResponse) {
    println!("✓ Project created successfully!");
    println!();
    println!("Created {} files:", response.files_created.len());
    for file in response.files_created {
        println!("  - {}", file.display());
    }
    println!();
    println!("Next steps:");
    for (i, step) in response.next_steps.iter().enumerate() {
        println!("  {}. {}", i + 1, step);
    }
}

fn print_codegen_outcome(outcome: CodegenOutcome) {
    match outcome {
        CodegenOutcome::InMemory(code) => println!("{code}"),
        CodegenOutcome::Files(files) => {
            for asset in files {
                println!("✓ Generated {} at {}", asset.description, asset.path.display());
            }
        }
    }
}

fn print_feature_summary(summary: app::FeatureSummary) {
    println!("Spikard - High-performance HTTP framework\n");
    println!("Rust Core: {}", if summary.rust_core { "" } else { "" });
    println!("\nLanguage Bindings:");
    for binding in &summary.language_bindings {
        println!("  {}: {}", binding.name, binding.install_hint);
    }
    println!("\nUsage:");
    for binding in &summary.language_bindings {
        println!("  {}: {}", binding.name, binding.usage_hint);
    }
    println!("\nDocumentation: {}", summary.documentation_url);
}

fn print_asyncapi_validation(summary: app::AsyncApiValidationSummary) {
    println!("✓ AsyncAPI schema is valid");
    println!("  Spec Version: {}", summary.spec_version);
    println!("  Title: {}", summary.title);
    println!("  API Version: {}", summary.api_version);
    println!("  Primary Protocol: {}", summary.primary_protocol);
    println!("  Channels: {}", summary.channel_count);
    println!("\nSchema validated successfully!");
}