gize 0.8.1

The Gize command-line interface: productivity-first backend framework for Rust.
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Command handlers. These translate parsed CLI input into generator plans and apply them
//! through the safe [`Writer`].

use std::fs;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail};
use gize_core::naming::{snake_case, table_name};
use gize_core::{Api, Dialect, Manifest, ModelSpec, Module};
use gize_generator::{Options, Plan, Writer, diff, registry, scaffold, sync};

use crate::cli::GenFlags;

impl From<GenFlags> for Options {
    fn from(f: GenFlags) -> Self {
        Options {
            force: f.force,
            dry_run: f.dry_run,
            // The CLI formats generated Rust with rustfmt on write (ADR-020); tests/plugins
            // that use `Options::default()` keep the raw template output.
            format: true,
        }
    }
}

/// A high-resolution, monotonic stamp for migration filenames and sqlx versions.
///
/// Nanoseconds since the Unix epoch. Second-resolution stamps collided when two resources
/// were generated within the same second (two migrations sharing one sqlx version — a
/// duplicate-key error on `migrate`); nanoseconds make each invocation's stamp distinct.
/// It also stays strictly greater than any earlier (including second-based, 0.5.0) stamp,
/// so migration ordering is preserved. (A calendar-formatted stamp was considered for
/// readability but rejected — it sorts before existing nanosecond stamps; see ADR-011.)
fn migration_timestamp() -> String {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    format!("{nanos:020}")
}

/// `gize new <name>` — scaffold a project into a new directory named `name`. Unless
/// `no_user` is set, a built-in `users` resource (model, CRUD, migration with an `is_admin`
/// flag) is generated and wired in.
pub fn new_project(
    name: &str,
    no_user: bool,
    openapi: bool,
    ws: bool,
    database: &str,
    api_version: Option<&str>,
    flags: GenFlags,
) -> Result<()> {
    let root = Path::new(name);
    if root.exists() && !flags.force {
        bail!("directory `{name}` already exists (use --force to generate into it)");
    }

    let dialect = Dialect::from_database(database);
    let api = api_version.map(Api::from_version);
    let plan = scaffold::new_project(
        name,
        !no_user,
        openapi,
        ws,
        dialect,
        api,
        &migration_timestamp(),
    );
    let report = Writer::new(flags.into())
        .apply(root, &plan)
        .with_context(|| format!("scaffolding project `{name}`"))?;

    println!(
        "Created project `{name}`:\n{}",
        report.render(flags.dry_run)
    );
    if !flags.dry_run {
        if !no_user {
            println!(
                "\nIncludes a `users` resource (id, name, email, password, is_admin). \
                 Set DATABASE_URL, then `gize migrate` to create the table."
            );
        }
        if openapi {
            println!("OpenAPI spec at `/openapi.json` and docs at `/docs` once running.");
        }
        if ws {
            let route = api_version
                .map(|v| format!("{}/ws", Api::from_version(v).mount_path()))
                .unwrap_or_else(|| "/ws".to_string());
            println!("WebSocket echo endpoint at `{route}` (typed messages in src/app/ws/).");
        }
        println!("Next:\n  cd {name}\n  cp .env.example .env\n  gize serve");
    }
    Ok(())
}

/// `gize make app <name>` — scaffold a module and wire it into `app/mod.rs` and
/// `gize.toml` (idempotently; ADR-004 / ADR-012).
pub fn make_app(name: &str, flags: GenFlags) -> Result<()> {
    ensure_in_project()?;
    let module = snake_case(name);

    // 1. Generate the module's own files through the safe writer.
    let plan = scaffold::make_app(&module);
    let report = Writer::new(flags.into())
        .apply(Path::new("."), &plan)
        .context("generating module files")?;
    println!(
        "Generated module `{module}`:\n{}",
        report.render(flags.dry_run)
    );

    // 2. Register the module + its routes in src/app/mod.rs (edit of an existing file).
    register_in_app_mod(&module, flags)?;

    // 3. Record the module in the manifest.
    register_in_manifest(&module, flags)?;

    if !flags.dry_run {
        println!("\nDefine its model with:\n  gize make model <Name> field:Type ... --force");
    }
    Ok(())
}

/// Insert `mod <module>;` and `.merge(<module>::routes())` into `src/app/mod.rs`.
fn register_in_app_mod(module: &str, flags: GenFlags) -> Result<()> {
    let path = Path::new("src/app/mod.rs");
    let source = fs::read_to_string(path).context("reading src/app/mod.rs")?;
    let edit = registry::register_module(&source, module)?;

    if !edit.changed {
        println!("  skip    src/app/mod.rs (module already registered)");
        return Ok(());
    }
    if flags.dry_run {
        println!("  update  src/app/mod.rs (would register module + routes)");
    } else {
        fs::write(path, edit.content).context("writing src/app/mod.rs")?;
        // rustfmt normalizes the wiring we just edited: sorts the `mod` declarations and
        // collapses/wraps the merge chain, so `app/mod.rs` stays rustfmt-clean (ADR-020).
        gize_generator::format_rust_files(&[path.to_path_buf()]);
        println!("  update  src/app/mod.rs (registered module + routes)");
    }
    Ok(())
}

/// Register a module by name only (`gize make app`). Add-only: never clobbers a module that
/// already carries a declared shape (e.g. one created by `make crud`).
fn register_in_manifest(module: &str, flags: GenFlags) -> Result<()> {
    let source = fs::read_to_string("gize.toml").context("reading gize.toml")?;
    let mut manifest = Manifest::from_toml(&source)?;

    if !manifest.add_module(module) {
        println!("  skip    gize.toml (module already listed)");
        return Ok(());
    }
    write_manifest(&manifest, flags, "added module")
}

/// Record a module's full shape (name + fields) in the manifest (`gize make crud`). Upserts,
/// so re-running with changed fields refreshes the recorded shape (ADR-009 revision).
fn record_module_in_manifest(module: Module, flags: GenFlags) -> Result<()> {
    let source = fs::read_to_string("gize.toml").context("reading gize.toml")?;
    let mut manifest = Manifest::from_toml(&source)?;

    if manifest.module(&module.name) == Some(&module) {
        println!("  skip    gize.toml (module already up to date)");
        return Ok(());
    }
    let existed = manifest.module(&module.name).is_some();
    manifest.upsert_module(module);
    write_manifest(
        &manifest,
        flags,
        if existed {
            "updated module"
        } else {
            "added module"
        },
    )
}

/// Refresh the derived `openapi.json` from the current manifest when `features.openapi` is on,
/// keeping the spec in parity with the routes after a structural change (ADR-010). No-op when
/// the feature is off. The spec is always overwritten (it is generated, not hand-edited).
fn refresh_openapi_if_enabled(flags: GenFlags) -> Result<()> {
    let manifest =
        Manifest::from_toml(&fs::read_to_string("gize.toml").context("reading gize.toml")?)?;
    if !manifest.features.openapi {
        return Ok(());
    }
    if flags.dry_run {
        println!("  update  openapi.json (would refresh the spec)");
    } else {
        fs::write("openapi.json", scaffold::openapi_json(&manifest)?)
            .context("writing openapi.json")?;
        println!("  update  openapi.json (refreshed from gize.toml)");
    }
    Ok(())
}

/// Persist a manifest, honoring `--dry-run`, with a consistent one-line report.
fn write_manifest(manifest: &Manifest, flags: GenFlags, what: &str) -> Result<()> {
    if flags.dry_run {
        println!("  update  gize.toml (would record module)");
    } else {
        fs::write("gize.toml", manifest.to_toml()?).context("writing gize.toml")?;
        println!("  update  gize.toml ({what})");
    }
    Ok(())
}

/// `gize make crud <Name> field:Type ...` — generate a full, wired CRUD resource.
pub fn make_crud(name: &str, fields: &[String], flags: GenFlags) -> Result<()> {
    ensure_in_project()?;
    let model = ModelSpec::parse(name, fields).context("invalid model definition")?;
    if model.fields.is_empty() {
        bail!(
            "`gize make crud` needs at least one field, e.g. \
             `gize make crud Product name:String price:i32`"
        );
    }
    let module = table_name(&model.name);

    let plan = scaffold::make_crud(&model, project_dialect()?, &migration_timestamp());
    let report = Writer::new(flags.into())
        .apply(Path::new("."), &plan)
        .context("generating CRUD")?;
    println!(
        "Generated CRUD for `{}`:\n{}",
        model.name,
        report.render(flags.dry_run)
    );

    register_in_app_mod(&module, flags)?;
    record_module_in_manifest(
        Module {
            name: module.clone(),
            fields: model.to_field_tokens(),
            belongs_to: model.relations.clone(),
        },
        flags,
    )?;
    refresh_openapi_if_enabled(flags)?;

    if !flags.dry_run {
        println!("\nApply the migration with:\n  gize migrate");
    }
    Ok(())
}

/// `gize make admin` — generate the admin SPA (ADR-006) for every resource in the manifest.
///
/// The admin is a **separate** Vite + React + TypeScript app under `admin/`, data-driven from
/// `gize.toml`. The static shell is written drift-aware; `admin/src/resources.ts` is a derived
/// artifact refreshed from the current manifest. The app reaches the API through a Vite dev
/// proxy, so the backend needs no CORS or other changes.
pub fn make_admin(_name: Option<&str>, flags: GenFlags) -> Result<()> {
    ensure_in_project()?;
    let mut manifest =
        Manifest::from_toml(&fs::read_to_string("gize.toml").context("reading gize.toml")?)?;
    if manifest.modules.is_empty() {
        bail!("no resources in gize.toml — add one with `gize make crud` first");
    }

    let report = Writer::new(flags.into())
        .apply(Path::new("."), &scaffold::admin_shell_plan(&manifest))
        .context("generating the admin app")?;
    println!("Admin SPA (admin/):\n{}", report.render(flags.dry_run));

    // Refresh the derived descriptors from the current manifest (always overwritten).
    if flags.dry_run {
        println!("  update  admin/src/resources.ts (would refresh descriptors)");
    } else {
        fs::create_dir_all("admin/src").context("creating admin/src")?;
        fs::write(
            "admin/src/resources.ts",
            scaffold::admin_resources_ts(&manifest)?,
        )
        .context("writing admin/src/resources.ts")?;
        println!("  update  admin/src/resources.ts (from gize.toml)");
    }

    // Record the feature so `gize sync` reconciles the admin.
    if !manifest.features.admin && !flags.dry_run {
        manifest.features.admin = true;
        fs::write("gize.toml", manifest.to_toml()?).context("writing gize.toml")?;
    }

    if !flags.dry_run {
        println!(
            "\nNext:\n  cd admin\n  npm install\n  npm run dev   \
             # http://localhost:5173 (proxies /api to your `gize serve` backend)"
        );
    }
    Ok(())
}

/// `gize make model <Name> field:Type ...` — generate a model + migration in the current
/// project.
pub fn make_model(name: &str, fields: &[String], flags: GenFlags) -> Result<()> {
    ensure_in_project()?;
    let model = ModelSpec::parse(name, fields).context("invalid model definition")?;
    let plan = scaffold::make_model(&model, project_dialect()?, &migration_timestamp());
    let report = Writer::new(flags.into())
        .apply(Path::new("."), &plan)
        .context("generating model")?;

    println!(
        "Generated model `{name}`:\n{}",
        report.render(flags.dry_run)
    );
    Ok(())
}

/// `gize make migration [name]` (ADR-011).
///
/// - **With a name**: generate a blank, timestamped SQL migration to fill in by hand — the
///   escape hatch for indexes, constraints and backfills.
/// - **Without a name**: diff each module's declared fields (`gize.toml`) against the columns
///   in its existing migrations and emit `ALTER TABLE` migrations to reconcile. New columns
///   are added automatically (nullable, for safety); dropped columns are withheld unless
///   `--force` is given.
pub fn make_migration(name: Option<&str>, flags: GenFlags) -> Result<()> {
    ensure_in_project()?;
    match name {
        Some(name) => make_blank_migration(name, flags),
        None => make_diff_migrations(flags),
    }
}

/// The named escape hatch: a single blank, timestamped migration to edit by hand.
fn make_blank_migration(name: &str, flags: GenFlags) -> Result<()> {
    let migration_name = slugify(name);
    if migration_name.is_empty() {
        bail!("migration name must contain at least one letter or digit");
    }

    let plan = scaffold::make_migration(&migration_name, &migration_timestamp());
    let report = Writer::new(flags.into())
        .apply(Path::new("."), &plan)
        .context("generating migration")?;
    println!(
        "Generated migration `{migration_name}`:\n{}",
        report.render(flags.dry_run)
    );
    if !flags.dry_run {
        println!("\nEdit the SQL, then apply it with:\n  gize migrate");
    }
    Ok(())
}

/// Model-change diffing: reconcile each module's table to its `gize.toml` shape (ADR-011).
fn make_diff_migrations(flags: GenFlags) -> Result<()> {
    let manifest =
        Manifest::from_toml(&fs::read_to_string("gize.toml").context("reading gize.toml")?)?;
    let dir = Path::new("migrations");

    let mut plan = Plan::new();
    let mut withheld_drops = 0usize;
    for module in &manifest.modules {
        if module.fields.is_empty() {
            continue; // no declared shape to diff (e.g. a bare `make app` module)
        }
        let model = module.model_spec()?;
        let Some(schema_diff) = diff::diff_model(dir, &module.name, &model)? else {
            println!(
                "  skip    {} (no create migration yet — run `gize make crud`/`gize sync` first)",
                module.name
            );
            continue;
        };
        if schema_diff.is_empty() {
            continue;
        }

        for f in &schema_diff.added {
            println!("  add     {}.{} {}", module.name, f.name, f.ty.sql_type());
        }
        for c in &schema_diff.dropped {
            if flags.force {
                println!("  drop    {}.{c} (--force)", module.name);
            } else {
                println!("  hold    {}.{c} (drop withheld; use --force)", module.name);
                withheld_drops += 1;
            }
        }

        // Only emit a migration when there is something to apply: any added column, or a drop
        // the developer opted into with --force.
        if !schema_diff.added.is_empty() || (flags.force && !schema_diff.dropped.is_empty()) {
            plan = plan.create(
                format!(
                    "migrations/{}_alter_{}.sql",
                    migration_timestamp(),
                    module.name
                ),
                diff::alter_sql(&module.name, &schema_diff, flags.force),
            );
        }
    }

    if plan.is_empty() {
        println!("Schema matches gize.toml — no model-change migrations to generate.");
        if withheld_drops > 0 {
            println!(
                "({withheld_drops} column drop(s) withheld — re-run with --force to emit them.)"
            );
        }
        return Ok(());
    }

    let report = Writer::new(flags.into())
        .apply(Path::new("."), &plan)
        .context("writing alter migrations")?;
    println!("\n{}", report.render(flags.dry_run));
    if !flags.dry_run {
        println!("Review the generated SQL, then apply it with:\n  gize migrate");
    }
    Ok(())
}

/// `gize sync` — reconcile the project from `gize.toml` (ADR-009).
///
/// Regenerates any module declared in the manifest whose code is missing, creates a
/// `CREATE TABLE` migration for any module that lacks one, and wires each module into
/// `src/app/mod.rs`. Files that exist but differ from the manifest are reported as **drift**
/// and left untouched unless `--force` is given; `--dry-run` previews without writing.
pub fn sync(flags: GenFlags) -> Result<()> {
    ensure_in_project()?;
    let manifest =
        Manifest::from_toml(&fs::read_to_string("gize.toml").context("reading gize.toml")?)?;

    if manifest.modules.is_empty() {
        println!("No modules declared in gize.toml — nothing to sync.");
        return Ok(());
    }

    let dialect = Dialect::from_database(&manifest.stack.database);

    // 1. Desired code files for every declared module (deterministic; no timestamps). The
    //    auth module is part of the skeleton the CRUD routes depend on, so reconcile it too.
    let mut plan = Plan::new().create("src/auth/mod.rs", scaffold::auth_mod_rs());
    for module in &manifest.modules {
        plan = plan.extend(
            scaffold::module_code(module, dialect)
                .with_context(|| format!("planning module `{}`", module.name))?,
        );
    }

    // 2. A CREATE TABLE migration only for tables that do not already have one, so re-running
    //    `sync` never spawns duplicate migrations (idempotent — ADR-011). Ordered so a
    //    foreign key's target table is created before the table that references it (ADR-014).
    for module in manifest.modules_in_dependency_order()? {
        if !create_migration_exists(&module.name)? {
            let sql = scaffold::module_migration_sql(module, dialect)?;
            plan = plan.create(
                format!(
                    "migrations/{}_create_{}.sql",
                    migration_timestamp(),
                    module.name
                ),
                sql,
            );
        }
    }

    // 2b. OpenAPI (ADR-010): when enabled, reconcile the (static) route module drift-aware.
    //     The spec itself is a derived artifact, refreshed unconditionally after apply below.
    if manifest.features.openapi {
        plan = plan.create("src/app/openapi.rs", scaffold::openapi_module_rs());
    }

    // 2c. Admin (ADR-006): reconcile the static SPA shell drift-aware; the resource
    //     descriptors are a derived artifact, refreshed after apply below.
    if manifest.features.admin {
        plan = plan.extend(scaffold::admin_shell_plan(&manifest));
    }

    // 2d. WebSocket (ADR-018): reconcile the static `src/app/ws/` module drift-aware.
    if manifest.features.websocket {
        plan = plan.extend(scaffold::ws_module_plan());
    }

    // 3. Diff against the filesystem and apply per the safety flags.
    let root = Path::new(".");
    let recon = sync::reconcile(root, &plan)?;
    let applied = sync::apply(root, &recon, flags.force, flags.dry_run)?;
    // Format the Rust files sync just wrote, matching `gize new`/`make` output (ADR-020).
    if !flags.dry_run {
        let written: Vec<std::path::PathBuf> = applied
            .created
            .iter()
            .chain(applied.overwritten.iter())
            .filter(|f| f.ends_with(".rs"))
            .map(|f| root.join(f))
            .collect();
        gize_generator::format_rust_files(&written);
    }
    println!(
        "Reconciling from gize.toml:\n{}",
        applied.render(flags.dry_run)
    );

    // 4. Wire each module into src/app/mod.rs (idempotent; a no-op for already-wired ones).
    for module in &manifest.modules {
        register_in_app_mod(&module.name, flags)?;
    }
    // The OpenAPI module is wired like any module, but is never listed in `[[module]]` (it is
    // not a resource), so register it here when the feature is on, and refresh the derived
    // spec from the current manifest (always overwritten — it is generated, not hand-edited).
    if manifest.features.openapi {
        register_in_app_mod("openapi", flags)?;
        if flags.dry_run {
            println!("  update  openapi.json (would refresh the spec)");
        } else {
            fs::write("openapi.json", scaffold::openapi_json(&manifest)?)
                .context("writing openapi.json")?;
            println!("  update  openapi.json (refreshed from gize.toml)");
        }
    }
    // The WebSocket module is wired like any module but is not a `[[module]]` resource, so
    // register it here when the feature is on (ADR-018).
    if manifest.features.websocket {
        register_in_app_mod("ws", flags)?;
    }

    // Refresh the derived admin descriptors from the current manifest (always overwritten).
    if manifest.features.admin {
        if flags.dry_run {
            println!("  update  admin/src/resources.ts (would refresh descriptors)");
        } else {
            fs::create_dir_all("admin/src").context("creating admin/src")?;
            fs::write(
                "admin/src/resources.ts",
                scaffold::admin_resources_ts(&manifest)?,
            )
            .context("writing admin/src/resources.ts")?;
            println!("  update  admin/src/resources.ts (refreshed from gize.toml)");
        }
    }

    // 5. Surface drift explicitly — the conservative default never overwrites hand edits.
    if !recon.drift.is_empty() && !flags.force {
        println!(
            "\n{} file(s) drifted from the manifest and were left untouched. \
             Review them, or re-run `gize sync --force` to overwrite.",
            recon.drift.len()
        );
    }
    Ok(())
}

/// Whether a `*_create_<table>.sql` migration already exists under `migrations/`.
fn create_migration_exists(table: &str) -> Result<bool> {
    let dir = Path::new("migrations");
    if !dir.exists() {
        return Ok(false);
    }
    let suffix = format!("_create_{table}.sql");
    for entry in fs::read_dir(dir).context("reading migrations/")? {
        let name = entry?.file_name();
        if name.to_string_lossy().ends_with(&suffix) {
            return Ok(true);
        }
    }
    Ok(false)
}

/// `gize fmt` — format the project with rustfmt (thin wrapper; ADR-012).
pub fn fmt() -> Result<()> {
    ensure_in_project()?;
    run_cargo(&["fmt", "--all"], "cargo fmt")
}

/// `gize check` — lint the project with clippy, denying warnings (thin wrapper; ADR-012).
pub fn check() -> Result<()> {
    ensure_in_project()?;
    run_cargo(
        &["clippy", "--all-targets", "--", "-D", "warnings"],
        "cargo clippy",
    )
}

/// Turn a free-text migration name into a filename-safe snake_case slug. Handles both
/// PascalCase (`AddIndexToUsers`) and loose text (`add index to users`) by snake-casing first,
/// then collapsing every run of non-alphanumeric characters into a single `_`.
fn slugify(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut pending_sep = false;
    for ch in snake_case(input).chars() {
        if ch.is_ascii_alphanumeric() {
            if pending_sep && !out.is_empty() {
                out.push('_');
            }
            out.push(ch);
            pending_sep = false;
        } else {
            pending_sep = true;
        }
    }
    out
}

/// Run a `cargo` subcommand inheriting stdio, mapping a non-zero exit into an error.
fn run_cargo(args: &[&str], label: &str) -> Result<()> {
    let status = std::process::Command::new("cargo")
        .args(args)
        .status()
        .with_context(|| format!("failed to launch `{label}` — is cargo installed?"))?;
    if !status.success() {
        bail!("`{label}` exited with a non-zero status");
    }
    Ok(())
}

/// `gize migrate [--status]` — apply pending SQL migrations (ADR-011), or report state.
pub fn migrate(show_status: bool) -> Result<()> {
    ensure_in_project()?;
    let database_url = std::env::var("DATABASE_URL").context(
        "DATABASE_URL must be set — in your environment or a project `.env` \
         (e.g. postgres://user:pass@localhost:5432/dbname)",
    )?;
    let dir = Path::new("migrations");

    if show_status {
        let status = gize_db::migrate::status(&database_url, dir)?;
        if status.applied.is_empty() && status.pending.is_empty() {
            println!("No migrations found in ./migrations.");
            return Ok(());
        }
        println!("Applied:");
        if status.applied.is_empty() {
            println!("  (none)");
        }
        for m in &status.applied {
            println!("  [x] {m}");
        }
        println!("Pending:");
        if status.pending.is_empty() {
            println!("  (none)");
        }
        for m in &status.pending {
            println!("  [ ] {m}");
        }
        return Ok(());
    }

    let newly = gize_db::migrate::run(&database_url, dir)?;
    if newly.is_empty() {
        println!("Database is up to date — no pending migrations.");
    } else {
        println!("Applied {} migration(s):", newly.len());
        for m in newly {
            println!("  {m}");
        }
    }
    Ok(())
}

/// `gize createadmin` — create the first admin user in the database (ADR-017). Interactive by
/// default; `--email`/`--name` + `--password-env` drive it non-interactively for CI. The
/// password is only ever read from a hidden prompt or an env var, never from argv.
pub fn create_admin(
    email: Option<String>,
    name: Option<String>,
    password_env: Option<String>,
) -> Result<()> {
    ensure_in_project()?;
    let dialect = project_dialect()?;
    let database_url = std::env::var("DATABASE_URL").context(
        "DATABASE_URL must be set — in your environment or a project `.env` \
         (e.g. postgres://user:pass@localhost:5432/dbname)",
    )?;

    // Email — from the flag or an interactive prompt — then a light sanity check.
    let email = match email {
        Some(e) => e.trim().to_string(),
        None => prompt("Email: ")?,
    };
    if !looks_like_email(&email) {
        bail!("`{email}` does not look like an email address");
    }

    // Display name (the `users.name` column).
    let name = match name {
        Some(n) => n.trim().to_string(),
        None => prompt("Name: ")?,
    };
    if name.is_empty() {
        bail!("name must not be empty");
    }

    // Password: from an env var (CI) or a hidden, confirmed prompt. Never from an argument.
    let password = match password_env {
        Some(var) => std::env::var(&var)
            .with_context(|| format!("reading the password from ${var} (is it set?)"))?,
        None => {
            let first = rpassword::prompt_password("Password: ").context("reading password")?;
            let confirm =
                rpassword::prompt_password("Confirm password: ").context("reading password")?;
            if first != confirm {
                bail!("passwords do not match");
            }
            first
        }
    };
    if password.len() < 8 {
        bail!("password must be at least 8 characters");
    }

    let hash = crate::password::hash_password(&password)?;
    gize_db::admin::create(&database_url, dialect, &email, &name, &hash)
        .context("creating the admin user")?;
    println!("Created admin `{email}`.");
    Ok(())
}

/// Print a label and read one trimmed line from stdin (for interactive prompts).
fn prompt(label: &str) -> Result<String> {
    use std::io::Write;
    print!("{label}");
    std::io::stdout().flush().ok();
    let mut line = String::new();
    std::io::stdin()
        .read_line(&mut line)
        .context("reading input")?;
    Ok(line.trim().to_string())
}

/// A light "is this an email?" check (an `@` with a non-empty local part and a dotted domain).
/// Deliberately loose — the backend `validator` rules are authoritative; this just catches typos.
fn looks_like_email(s: &str) -> bool {
    match s.split_once('@') {
        Some((local, domain)) => {
            !local.is_empty()
                && domain.contains('.')
                && !domain.starts_with('.')
                && !domain.ends_with('.')
        }
        None => false,
    }
}

/// `gize serve` — run the generated application, and (by default, when an admin has been
/// generated) its admin dev server alongside it (ADR-019). Flags select the mode: `--api-only`,
/// `--admin-only`, or `--with-admin` (the explicit form of the default).
pub fn serve(api_only: bool, admin_only: bool, with_admin: bool) -> Result<()> {
    ensure_in_project()?;
    let manifest =
        Manifest::from_toml(&fs::read_to_string("gize.toml").context("reading gize.toml")?)?;
    let admin_available = manifest.features.admin && Path::new("admin").is_dir();

    let (run_api, run_admin) =
        resolve_run_targets(api_only, admin_only, with_admin, admin_available);

    if run_admin && !admin_available {
        bail!(
            "no admin to serve — run `gize make admin` first (expected an `admin/` directory \
             and `features.admin` in gize.toml)"
        );
    }

    let port = std::env::var("PORT")
        .ok()
        .and_then(|p| p.parse::<u16>().ok())
        .unwrap_or(8080);

    match (run_api, run_admin) {
        // Admin only: run its dev server in the foreground.
        (false, true) => {
            let mut admin = spawn_admin_dev()?;
            let status = admin.wait().context("waiting for the admin dev server")?;
            if !status.success() {
                bail!("the admin dev server exited with a non-zero status");
            }
            Ok(())
        }
        // API only: the classic path.
        (true, false) => {
            println!("Starting the API with `cargo run` (Ctrl-C to stop)...\n");
            println!("  API:  http://localhost:{port}\n");
            let status = std::process::Command::new("cargo")
                .arg("run")
                .status()
                .context("failed to launch `cargo run` — is cargo installed?")?;
            if !status.success() {
                bail!("the application exited with a non-zero status");
            }
            Ok(())
        }
        // Both: spawn each and supervise so neither is left orphaned.
        (true, true) => {
            println!("Starting the API and the admin dev server (Ctrl-C to stop)...\n");
            println!("  API:   http://localhost:{port}");
            println!(
                "  Admin: http://localhost:5173  (the dev server prints the exact URL below)\n"
            );
            let mut api = std::process::Command::new("cargo")
                .arg("run")
                .spawn()
                .context("failed to launch `cargo run` — is cargo installed?")?;
            let mut admin = match spawn_admin_dev() {
                Ok(child) => child,
                Err(e) => {
                    let _ = api.kill();
                    let _ = api.wait();
                    return Err(e);
                }
            };
            supervise(&mut api, &mut admin);
            Ok(())
        }
        (false, false) => unreachable!("run_api is always true unless admin_only"),
    }
}

/// Decide what `gize serve` runs, from the flags and whether an admin has been generated.
/// Returns `(run_api, run_admin)`. With no flag the default runs the admin only when one is
/// available, so a project without an admin behaves exactly as before.
fn resolve_run_targets(
    api_only: bool,
    admin_only: bool,
    with_admin: bool,
    admin_available: bool,
) -> (bool, bool) {
    if api_only {
        (true, false)
    } else if admin_only {
        (false, true)
    } else if with_admin {
        (true, true)
    } else {
        (true, admin_available)
    }
}

/// Detect a package manager, install the admin's dependencies on first run, then spawn its dev
/// server in `admin/`. Streams the dev server's output (inherited stdio).
fn spawn_admin_dev() -> Result<std::process::Child> {
    let pm = detect_package_manager().context(
        "no package manager found on PATH — install pnpm, npm or yarn (the admin needs Node.js)",
    )?;
    let admin = Path::new("admin");
    if !admin.join("node_modules").is_dir() {
        println!("Installing admin dependencies with `{pm} install` (first run)...");
        let status = std::process::Command::new(pm)
            .arg("install")
            .current_dir(admin)
            .status()
            .with_context(|| format!("running `{pm} install` in admin/"))?;
        if !status.success() {
            bail!("`{pm} install` failed in admin/");
        }
    }
    println!("Starting the admin dev server with `{pm} run dev` (admin/)...");
    std::process::Command::new(pm)
        .arg("run")
        .arg("dev")
        .current_dir(admin)
        .spawn()
        .with_context(|| format!("launching `{pm} run dev` in admin/"))
}

/// Prefer pnpm, then npm, then yarn — the first one available on PATH.
fn detect_package_manager() -> Option<&'static str> {
    ["pnpm", "npm", "yarn"].into_iter().find(|pm| which(pm))
}

/// Wait until either child exits, then stop the other so nothing is left orphaned. An
/// interactive Ctrl-C is delivered by the terminal to the whole foreground process group, so
/// both children receive it and shut down; this loop then reaps them and, if only one exited on
/// its own (e.g. a crash), tears down the survivor.
fn supervise(api: &mut std::process::Child, admin: &mut std::process::Child) {
    loop {
        if matches!(api.try_wait(), Ok(Some(_)) | Err(_)) {
            let _ = admin.kill();
            let _ = admin.wait();
            break;
        }
        if matches!(admin.try_wait(), Ok(Some(_)) | Err(_)) {
            let _ = api.kill();
            let _ = api.wait();
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
}

/// `gize <name> …` — dispatch an unknown subcommand to a `gize-<name>` plugin on PATH
/// (ADR-008, v0). The plugin is a normal executable; it receives the remaining arguments and
/// generates through the same safe writer via `gize_generator::plugin`.
pub fn run_external(args: Vec<String>) -> Result<()> {
    let Some((name, rest)) = args.split_first() else {
        bail!("no command given");
    };
    let bin = format!("gize-{name}");
    match std::process::Command::new(&bin).args(rest).status() {
        Ok(status) if status.success() => Ok(()),
        Ok(_) => bail!("`{bin}` exited with a non-zero status"),
        Err(_) => bail!(
            "unknown command `{name}`, and no `{bin}` plugin was found on PATH.\n\
             Plugins are `gize-<name>` executables on your PATH (ADR-008, v0)."
        ),
    }
}

/// `gize doctor` — sanity-check the environment and project.
pub fn doctor() -> Result<()> {
    println!("gize doctor\n");

    report("cargo available", which("cargo"));
    report("rustfmt available", which("rustfmt"));
    report(
        "inside a gize project (gize.toml)",
        Path::new("gize.toml").exists(),
    );
    report("`.env` file present", Path::new(".env").exists());
    // `.env` is auto-loaded at startup, so these reflect the effective values.
    report("DATABASE_URL set", std::env::var("DATABASE_URL").is_ok());
    report(
        "GIZE_JWT_SECRET set (auth token signing)",
        std::env::var("GIZE_JWT_SECRET").is_ok(),
    );

    Ok(())
}

fn report(label: &str, ok: bool) {
    let mark = if ok { "ok  " } else { "warn" };
    println!("  [{mark}] {label}");
}

fn which(bin: &str) -> bool {
    std::process::Command::new(bin)
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

fn ensure_in_project() -> Result<()> {
    if !Path::new("gize.toml").exists() {
        bail!("not a gize project (no gize.toml here). Run `gize new <name>` first.");
    }
    Ok(())
}

/// The database dialect for the current project, read from `gize.toml` (ADR-015).
fn project_dialect() -> Result<Dialect> {
    let manifest =
        Manifest::from_toml(&fs::read_to_string("gize.toml").context("reading gize.toml")?)?;
    Ok(Dialect::from_database(&manifest.stack.database))
}

#[cfg(test)]
mod tests {
    use super::{looks_like_email, resolve_run_targets, slugify};

    #[test]
    fn serve_targets_default_to_admin_only_when_available() {
        // No flag: API always; admin follows availability.
        assert_eq!(resolve_run_targets(false, false, false, true), (true, true));
        assert_eq!(
            resolve_run_targets(false, false, false, false),
            (true, false)
        );
        // Explicit flags override availability (the guard rejects the impossible case later).
        assert_eq!(resolve_run_targets(true, false, false, true), (true, false));
        assert_eq!(
            resolve_run_targets(false, true, false, false),
            (false, true)
        );
        assert_eq!(resolve_run_targets(false, false, true, false), (true, true));
    }

    #[test]
    fn slugify_handles_pascal_case_and_loose_text() {
        assert_eq!(slugify("AddIndexToUsers"), "add_index_to_users");
        assert_eq!(slugify("add index to users"), "add_index_to_users");
        assert_eq!(slugify("  Add  Index  "), "add_index");
        assert_eq!(slugify("add-index_to.users"), "add_index_to_users");
        assert_eq!(slugify("migration"), "migration");
        assert_eq!(slugify("!!!"), "");
    }

    #[test]
    fn email_check_accepts_plausible_and_rejects_typos() {
        assert!(looks_like_email("admin@example.com"));
        assert!(looks_like_email("a.b+tag@sub.example.co"));
        assert!(!looks_like_email("admin"));
        assert!(!looks_like_email("admin@localhost"));
        assert!(!looks_like_email("@example.com"));
        assert!(!looks_like_email("admin@.com"));
        assert!(!looks_like_email("admin@example."));
    }
}