larakiln 0.2.0

Port Laravel PHP apps to a new Laravel runtime (Laravel Rust today) and check nothing was lost: audit, plan, codegen, route parity
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
//! Writes the predictable part of the port into a Laravel Rust app: models (from the PHP
//! migrations), input structs (from validation rules), handler stubs and routes, and Jinja views
//! (from Blade). Anything it can't map is marked `PORT-TODO`. Never overwrites a file, never
//! edits the app's own files: the wiring lines go into `larakiln-codegen.md`.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs;
use std::path::{Path, PathBuf};

use regex::Regex;
use serde_json::Value;

use crate::audit::balanced;
use crate::manifest::controller;
use crate::route_parity::{ignored, php_auth};
use crate::feasibility;

const RESERVED: &[&str] = &[
    "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for", "gen",
    "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "static", "struct", "super",
    "trait", "true", "try", "type", "unsafe", "use", "where", "while", "abstract", "become", "box", "do", "final", "macro",
    "override", "priv", "typeof", "unsized", "virtual", "yield",
];

pub fn run(inventory: &Path, rust: &Path) -> Result<(), String> {
    let mut inv = feasibility::load(inventory)?;
    feasibility::score_all(&mut inv);
    let php = PathBuf::from(inv["app"]["path"].as_str().ok_or("inventory has no app.path")?);
    if !rust.join("Cargo.toml").is_file() || !rust.join("src").is_dir() {
        return Err(format!("{} isn't a Laravel Rust app (no Cargo.toml + src/); create one with `laravel new <name> --rust`", rust.display()));
    }
    if let (Ok(p), Ok(r)) = (fs::canonicalize(&php), fs::canonicalize(rust)) {
        if r.starts_with(&p) {
            return Err("the Rust app is inside the PHP app; put it somewhere else (hard rule 2)".into());
        }
    }

    let models = Models::new(&inv, &php);
    let mut files: Vec<(String, String)> = models.files();
    let (handler_files, wiring, names) = handlers(&inv, &models);
    files.extend(handler_files);
    files.extend(views(&inv, &php, &names));

    let (mut written, mut skipped, mut skipped_notes, mut todos) = (Vec::new(), Vec::new(), Vec::new(), 0);
    for (rel, text) in &files {
        let path = rust.join(rel);
        if path.exists() {
            skipped_notes.push(match missing_fields(&path, text) {
                Some(m) => format!("- `{rel}`: lacks {m}; add them, or the relations to this model won't compile"),
                None => format!("- `{rel}`"),
            });
            skipped.push(rel.clone());
            continue;
        }
        fs::create_dir_all(path.parent().unwrap()).map_err(|e| e.to_string())?;
        fs::write(&path, text).map_err(|e| format!("{rel}: {e}"))?;
        let n = text.lines().skip(1).filter(|l| l.contains("PORT-TODO")).count();
        todos += n;
        written.push(format!("- `{rel}` ({n} PORT-TODO)"));
    }

    let mut report = format!(
        "# larakiln codegen\n\nGenerated from `{}`. {} files written, {} skipped because they already exist, {todos} `PORT-TODO` markers.\n\n\
         Nothing here is wired up yet, and nothing existing was changed. Do the wiring below, run `cargo build`, then work through the `PORT-TODO` markers item by item with `/port-next`.\n\n",
        php.display(),
        written.len(),
        skipped.len()
    );
    report += &format!("## Wiring\n\n{wiring}{}\n", models.wiring(&skipped));
    report += &format!("## Written ({})\n\n{}\n\n", written.len(), written.join("\n"));
    if !skipped.is_empty() {
        report += &format!(
            "## Skipped: already exist ({})\n\nCompare these by hand with what codegen would have written (delete the file and re-run to see it).\n\n{}\n",
            skipped.len(),
            skipped_notes.join("\n")
        );
    }
    fs::write(rust.join("larakiln-codegen.md"), report).map_err(|e| e.to_string())?;
    println!("Wrote {} files ({todos} PORT-TODO), skipped {} existing. Next: follow {}/larakiln-codegen.md", written.len(), skipped.len(), rust.display());
    Ok(())
}

// ---------- names ----------

fn snake(s: &str) -> String {
    let mut out = String::new();
    for (i, ch) in s.chars().enumerate() {
        if ch.is_uppercase() {
            if i > 0 && !out.ends_with('_') {
                out.push('_');
            }
            out.extend(ch.to_lowercase());
        } else if ch == '-' || ch == ' ' || ch == '.' {
            out.push('_');
        } else {
            out.push(ch);
        }
    }
    out
}

fn studly(s: &str) -> String {
    s.split(['_', '-']).map(|w| {
        let mut c = w.chars();
        c.next().map(|f| f.to_uppercase().chain(c).collect::<String>()).unwrap_or_default()
    }).collect()
}

// ponytail: English plural for the common cases; irregular table names come from the model's $table.
fn plural(s: &str) -> String {
    let consonant_y = s.ends_with('y') && !s.ends_with("ay") && !s.ends_with("ey") && !s.ends_with("oy") && !s.ends_with("uy");
    if consonant_y {
        format!("{}ies", &s[..s.len() - 1])
    } else if ["s", "x", "ch", "sh"].iter().any(|e| s.ends_with(e)) {
        format!("{s}es")
    } else {
        format!("{s}s")
    }
}

fn ident(s: &str) -> String {
    let s = snake(s);
    if RESERVED.contains(&s.as_str()) { format!("{s}_") } else { s }
}

/// Fields a generated model has that the existing file doesn't, as "`a`, `b`".
fn missing_fields(existing: &Path, generated: &str) -> Option<String> {
    let have = fs::read_to_string(existing).ok()?;
    let field = Regex::new(r"(?m)^\s*pub (\w+):").unwrap();
    let have: Vec<String> = field.captures_iter(&have).map(|c| c[1].to_string()).collect();
    let missing: Vec<String> = field.captures_iter(generated).map(|c| c[1].to_string()).filter(|f| !have.contains(f)).map(|f| format!("`{f}`")).collect();
    (!missing.is_empty()).then(|| missing.join(", "))
}

fn class_basename(s: &str) -> &str {
    s.rsplit('\\').next().unwrap_or(s)
}

// ---------- models ----------

#[derive(Clone)]
struct Column {
    name: String,
    ty: String,
    nullable: bool,
    note: Option<String>,
}

struct Models {
    /// model name → (inventory item, table)
    list: Vec<(String, Value, String)>,
    tables: HashMap<String, Vec<Column>>,
}

impl Models {
    fn new(inv: &Value, php: &Path) -> Self {
        let list = inv["models"].as_array().into_iter().flatten().map(|m| {
            let name = m["id"].as_str().unwrap_or("").trim_start_matches("model:").to_string();
            let table = m["table"].as_str().map(String::from).unwrap_or_else(|| plural(&snake(&name)));
            (name, m.clone(), table)
        }).collect();
        let mut models = Models { list, tables: migrations(php) };
        models.match_key_types();
        models
    }

    /// Laravel Rust needs a foreign key column of exactly its key's type: `increments('id')` (i32)
    /// with `foreignId('x_id')` (i64), or `id()` with `integer('x_id')`, would not compile.
    fn match_key_types(&mut self) {
        let id_ty = |tables: &HashMap<String, Vec<Column>>, table: &str| -> Option<String> {
            tables.get(table)?.iter().find(|c| c.name == "id").map(|c| c.ty.clone())
        };
        let mut fixes = Vec::new(); // (table, column, type)
        for (name, m, table) in &self.list {
            for r in m["relations"].as_array().into_iter().flatten() {
                let related = r["related"].as_str().unwrap_or("");
                let Some((_, _, rtable)) = self.list.iter().find(|(n, _, _)| n == related) else { continue };
                match r["type"].as_str() {
                    Some("belongsTo") => {
                        let fk = format!("{}_id", snake(r["name"].as_str().unwrap_or("")));
                        if let Some(t) = id_ty(&self.tables, rtable) {
                            fixes.push((table.clone(), fk, t));
                        }
                    }
                    Some("hasMany" | "hasOne") => {
                        if let Some(t) = id_ty(&self.tables, table) {
                            fixes.push((rtable.clone(), format!("{}_id", snake(name)), t));
                        }
                    }
                    _ => {}
                }
            }
        }
        for (table, col, ty) in fixes {
            if let Some(c) = self.tables.get_mut(&table).and_then(|cols| cols.iter_mut().find(|c| c.name == col)) {
                c.ty = ty;
            }
        }
    }

    fn has(&self, name: &str) -> bool {
        self.list.iter().any(|(n, _, _)| n == name)
    }

    fn by_table(&self, table: &str) -> Option<&str> {
        self.list.iter().find(|(_, _, t)| t == table).map(|(n, _, _)| n.as_str())
    }

    fn files(&self) -> Vec<(String, String)> {
        self.list.iter().map(|(name, m, table)| (format!("src/models/{}.rs", snake(name)), self.model(name, m, table))).collect()
    }

    /// `mod` lines for the models just written; skipped files are already wired.
    fn wiring(&self, skipped: &[String]) -> String {
        let mods: String = self
            .list
            .iter()
            .filter(|(n, _, _)| !skipped.contains(&format!("src/models/{}.rs", snake(n))))
            .map(|(n, _, _)| format!("mod {};\npub use {}::{n};\n", snake(n), snake(n)))
            .collect();
        format!("**`src/models/mod.rs`**: add\n\n```rust\n{mods}```\n\nModels need their migrations too: the PHP app keeps owning the schema while both apps run, so the Rust app reads the same tables. Port migrations only when the Rust app takes the schema over.\n\n")
    }

    fn model(&self, name: &str, m: &Value, table: &str) -> String {
        let mut uses: BTreeSet<&str> = ["model"].into();
        let mut extra_uses: BTreeSet<String> = BTreeSet::new();
        let mut body = String::new();
        let casts = &m["casts"];
        let columns = self.tables.get(table);
        match columns {
            None => body += &format!("    pub id: i64,\n    // PORT-TODO: no `Schema::create('{table}')` found in database/migrations; add the columns by hand (`php artisan db:table {table} --json`).\n"),
            Some(cols) => {
                for c in cols {
                    let mut ty = c.ty.clone();
                    let mut serde_skip = false;
                    let mut note = c.note.clone();
                    let cast = casts[c.name.as_str()].as_str();
                    match cast.map(|s| s.split(':').next().unwrap_or(s)) {
                        Some("hashed") => (ty, serde_skip) = ("PasswordHash".into(), true),
                        Some("encrypted") if cast == Some("encrypted") => ty = "Encrypted<String>".into(),
                        Some("encrypted") => {
                            ty = "Encrypted<serde_json::Value>".into();
                            note = Some(format!("PORT-TODO: `{}` cast; pick the Rust type", cast.unwrap_or("")));
                        }
                        Some("boolean" | "bool") => ty = "bool".into(),
                        Some("integer" | "int") => ty = "i64".into(),
                        Some("float" | "double") => ty = "f64".into(),
                        Some("datetime" | "immutable_datetime" | "timestamp") => ty = "Timestamp".into(),
                        Some("date" | "immutable_date") => ty = "civil::Date".into(),
                        Some("array" | "json" | "collection" | "object") => ty = "serde_json::Value".into(),
                        Some(other) if ty == "String" && !["string"].contains(&other) => note = Some(format!("PORT-TODO: `{other}` cast")),
                        _ => {}
                    }
                    if c.name == "password" && ty == "String" {
                        (ty, serde_skip) = ("PasswordHash".into(), true);
                    }
                    if ty == "RememberToken" {
                        serde_skip = true;
                    }
                    for (needle, path) in [
                        ("Timestamp", "laravel::time::Timestamp"),
                        ("civil::", "laravel::time::civil"),
                        ("PasswordHash", "laravel::hash::PasswordHash"),
                        ("Encrypted", "laravel::crypt::Encrypted"),
                        ("RememberToken", "laravel::auth::RememberToken"),
                        ("Decimal", "laravel::numeric::Decimal"),
                    ] {
                        if ty.contains(needle) {
                            extra_uses.insert(path.into());
                        }
                    }
                    if let Some(n) = note {
                        body += &format!("    // {n}\n");
                    }
                    if serde_skip {
                        body += "    #[serde(skip)]\n";
                    }
                    let field = ident(&c.name);
                    if field != c.name {
                        body += &format!("    #[column(\"{}\")]\n", c.name);
                    }
                    let ty = if c.nullable { format!("Option<{ty}>") } else { ty };
                    body += &format!("    pub {field}: {ty},\n");
                }
            }
        }

        for r in m["relations"].as_array().into_iter().flatten() {
            let (rname, related, kind) = (r["name"].as_str().unwrap_or("?"), r["related"].as_str().unwrap_or("?"), r["type"].as_str().unwrap_or("?"));
            let field = ident(rname);
            let attr = match kind {
                "belongsTo" => Some(("belongs_to", "BelongsTo")),
                "hasMany" => Some(("has_many", "HasMany")),
                "hasOne" => Some(("has_one", "HasOne")),
                _ => None,
            };
            match attr {
                Some((a, w)) if self.has(related) => {
                    uses.insert(w);
                    extra_uses.insert(format!("crate::models::{related}"));
                    let fk_nullable = columns.is_some_and(|cols| cols.iter().any(|c| c.name == format!("{}_id", snake(rname)) && c.nullable));
                    let target = if (kind == "belongsTo" && fk_nullable) || kind == "hasOne" { format!("Option<{related}>") } else { related.to_string() };
                    body += &format!("    #[{a}]\n    pub {field}: {w}<{target}>,\n");
                }
                _ => body += &format!("    // PORT-TODO: `{rname}` is a `{kind}` relation to `{related}`; map it by hand (model-relationships.md).\n"),
            }
        }

        let mut head = format!("// Generated by larakiln codegen from {} and the PHP migrations. Search for PORT-TODO.\n// larakiln: {}\n", m["file"].as_str().unwrap_or("?"), m["id"].as_str().unwrap_or("?"));
        head += &format!("use laravel::model::{{{}}};\n", uses.iter().copied().collect::<Vec<_>>().join(", "));
        for u in extra_uses.iter().filter(|u| !u.starts_with("crate::")) {
            head += &format!("use {u};\n");
        }
        let crate_uses: Vec<&String> = extra_uses.iter().filter(|u| u.starts_with("crate::")).filter(|u| !u.ends_with(&format!("::{name}"))).collect();
        if !crate_uses.is_empty() {
            head += "\n";
            for u in crate_uses {
                head += &format!("use {u};\n");
            }
        }
        let table_attr = if *table == plural(&snake(name)) { "#[model]".to_string() } else { format!("#[model(table = \"{table}\")]") };
        format!("{head}\n{table_attr}\npub struct {name} {{\n{body}}}\n")
    }
}

/// Columns per table from `Schema::create` / `Schema::table` in the PHP migrations, in file order.
fn migrations(php: &Path) -> HashMap<String, Vec<Column>> {
    let mut tables: HashMap<String, Vec<Column>> = HashMap::new();
    let Ok(dir) = fs::read_dir(php.join("database/migrations")) else { return tables };
    let mut files: Vec<PathBuf> = dir.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|e| e == "php")).collect();
    files.sort();
    let open = Regex::new(r#"Schema::(create|table)\(\s*['"]([^'"]+)['"]"#).unwrap();
    for f in files {
        let Ok(src) = fs::read_to_string(&f) else { continue };
        // Only the up() half: down() drops what up() made.
        let src = src.split("function down").next().unwrap_or(&src);
        for c in open.captures_iter(src) {
            let rest = &src[c.get(0).unwrap().end()..];
            let Some(brace) = rest.find('{') else { continue };
            let Some(body) = balanced(&rest[brace..], '{', '}') else { continue };
            let cols = tables.entry(c[2].to_string()).or_default();
            for stmt in body.trim_start_matches('{').split(';') {
                apply(cols, stmt.trim());
            }
        }
    }
    tables
}

fn apply(cols: &mut Vec<Column>, stmt: &str) {
    let call = Regex::new(r#"^\$table->(\w+)\(([^)]*)\)"#).unwrap();
    let Some(c) = call.captures(stmt) else { return };
    let (method, args) = (&c[1], &c[2]);
    let quoted = Regex::new(r#"['"]([^'"]+)['"]"#).unwrap();
    let names: Vec<String> = quoted.captures_iter(args).map(|q| q[1].to_string()).collect();
    let nullable = stmt.contains("->nullable(");
    let col = |name: &str, ty: &str, nullable: bool| Column { name: name.into(), ty: ty.into(), nullable, note: None };
    let first = names.first().cloned();
    let ty = match method {
        "id" | "bigIncrements" | "foreignId" | "unsignedBigInteger" | "bigInteger" => "i64",
        "increments" | "integer" | "unsignedInteger" | "mediumInteger" | "smallInteger" | "tinyInteger" | "unsignedSmallInteger" | "unsignedTinyInteger" | "unsignedMediumInteger" | "year" => "i32",
        "string" | "char" | "text" | "mediumText" | "longText" | "tinyText" | "uuid" | "ulid" | "enum" | "ipAddress" | "macAddress" | "set" => "String",
        "boolean" => "bool",
        "decimal" | "unsignedDecimal" => "Decimal",
        "float" | "double" => "f64",
        "date" => "civil::Date",
        "time" | "timeTz" => "civil::Time",
        "dateTime" | "dateTimeTz" | "timestamp" | "timestampTz" => "Timestamp",
        "json" | "jsonb" => "serde_json::Value",
        "binary" => "Vec<u8>",
        "foreignIdFor" => {
            let class = args.split("::class").next().unwrap_or("").trim();
            let name = first.clone().unwrap_or_else(|| format!("{}_id", snake(class_basename(class))));
            cols.push(col(&name, "i64", nullable));
            return;
        }
        "timestamps" | "timestampsTz" | "nullableTimestamps" => {
            let n = method == "nullableTimestamps";
            cols.push(col("created_at", "Timestamp", n));
            cols.push(col("updated_at", "Timestamp", n));
            return;
        }
        "softDeletes" | "softDeletesTz" => {
            let mut c = col(first.as_deref().unwrap_or("deleted_at"), "Timestamp", true);
            c.note = Some("PORT-TODO: soft deletes; check how Laravel Rust handles them before relying on this column".into());
            cols.push(c);
            return;
        }
        "rememberToken" => {
            cols.push(col("remember_token", "RememberToken", true));
            return;
        }
        "morphs" | "nullableMorphs" | "uuidMorphs" | "ulidMorphs" => {
            let base = first.unwrap_or_default();
            let n = method == "nullableMorphs";
            cols.push(col(&format!("{base}_type"), "String", n));
            cols.push(col(&format!("{base}_id"), if method == "morphs" || n { "i64" } else { "String" }, n));
            return;
        }
        "dropColumn" => {
            cols.retain(|c| !names.contains(&c.name));
            return;
        }
        "renameColumn" => {
            if let [from, to] = names.as_slice() {
                if let Some(c) = cols.iter_mut().find(|c| &c.name == from) {
                    c.name = to.clone();
                }
            }
            return;
        }
        // Indexes, keys and table options don't add columns.
        "index" | "unique" | "primary" | "foreign" | "dropForeign" | "dropIndex" | "dropUnique" | "dropPrimary" | "engine" | "charset"
        | "collation" | "comment" | "fullText" | "spatialIndex" | "dropTimestamps" | "dropSoftDeletes" | "dropRememberToken" | "dropMorphs" => return,
        other => {
            let mut c = col(first.as_deref().unwrap_or(other), "String", nullable);
            c.note = Some(format!("PORT-TODO: unmapped column type `$table->{other}(...)`"));
            cols.push(c);
            return;
        }
    };
    let name = first.unwrap_or_else(|| "id".into());
    let nullable = nullable && method != "id";
    if let Some(existing) = cols.iter_mut().find(|c| c.name == name) {
        *existing = col(&name, ty, nullable); // `->change()` in a later migration
    } else {
        cols.push(col(&name, ty, nullable));
    }
}

// ---------- input structs ----------

fn input_struct(name: &str, req: &Value, auth: &str, models: &Models) -> String {
    let id = req["id"].as_str().unwrap_or("?");
    let Some(rules) = req["rules"].as_object() else {
        return format!("// PORT-TODO: {id} builds its rules at runtime; write `{name}` by hand (validation.md).\n\n");
    };
    let mut fields = String::new();
    for (field, rs) in rules {
        let rs: Vec<&str> = rs.as_array().into_iter().flatten().filter_map(Value::as_str).collect();
        if field.contains('.') || field.contains('*') {
            fields += &format!("    // PORT-TODO: nested field `{field}`: {}\n", rs.join("|"));
            continue;
        }
        let numeric = rs.iter().any(|r| ["integer", "numeric", "decimal"].contains(&r.split(':').next().unwrap_or(r)));
        let mut ty = if rs.contains(&"boolean") || rs.contains(&"accepted") {
            "bool"
        } else if rs.contains(&"integer") {
            "i64"
        } else if numeric {
            "f64"
        } else {
            "String"
        }
        .to_string();
        let (mut out, mut todo) = (Vec::new(), Vec::new());
        for r in &rs {
            let (rule, arg) = r.split_once(':').map_or((*r, ""), |(a, b)| (a, b));
            let args: Vec<&str> = arg.split(',').filter(|a| !a.is_empty()).collect();
            let quoted = || args.iter().map(|a| format!("\"{a}\"")).collect::<Vec<_>>().join(", ");
            match rule {
                "string" | "integer" | "numeric" | "boolean" => {}
                "nullable" => ty = format!("Option<{ty}>"),
                "sometimes" => ty = format!("Sometimes<{ty}>"),
                "required" | "email" | "url" | "uuid" | "ulid" | "ip" | "ipv4" | "ipv6" | "json" | "alpha" | "alpha_num" | "alpha_dash"
                | "ascii" | "lowercase" | "uppercase" | "confirmed" | "accepted" | "declined" | "filled" | "present" | "date" | "timezone"
                | "mac_address" | "hex_color" | "bail" => out.push(rule.to_string()),
                "max" if numeric => out.push(format!("max_value({arg})")),
                "min" if numeric => out.push(format!("min_value({arg})")),
                "max" => out.push(format!("max_length({arg})")),
                "min" => out.push(format!("min_length({arg})")),
                "between" if numeric => out.push(format!("between({arg})")),
                "between" if args.len() == 2 => out.extend([format!("min_length({})", args[0]), format!("max_length({})", args[1])]),
                "in" => out.push(format!("one_of({})", quoted())),
                "not_in" => out.push(format!("not_one_of({})", quoted())),
                "digits" | "digits_between" | "same" | "different" | "gt" | "gte" | "lt" | "lte" | "decimal" | "multiple_of" => {
                    out.push(format!("{rule}({arg})"))
                }
                "starts_with" | "ends_with" | "doesnt_start_with" | "doesnt_end_with" => out.push(format!("{rule}({})", quoted())),
                "after" | "before" | "after_or_equal" | "before_or_equal" if arg == "today" => {
                    out.push(match rule { "after" => "after_today", "before" => "before_today", "after_or_equal" => "today_or_after", _ => "today_or_before" }.into())
                }
                "after" | "before" | "after_or_equal" | "before_or_equal" => out.push(format!("{rule}({arg})")),
                "unique" if !args.is_empty() => match models.by_table(args[0]) {
                    Some(model) => out.push(format!("unique({model}::{})", args.get(1).copied().unwrap_or(field.as_str()))),
                    None => todo.push(r.to_string()),
                },
                _ => todo.push(r.to_string()),
            }
        }
        if !todo.is_empty() {
            fields += &format!("    // PORT-TODO: no verified mapping for {}\n", todo.join(", "));
        }
        if !out.is_empty() {
            fields += &format!("    #[validate({})]\n", out.join(", "));
        }
        fields += &format!("    pub {}: {ty},\n", ident(field));
    }
    let authorize = match req["authorize"].as_str() {
        Some(a) if a != "true" => format!("// PORT-TODO: the FormRequest's authorize() is `{a}`; use #[validate(authorize(Policy::method, route(\"..\")))]\n"),
        _ => String::new(),
    };
    format!("/// larakiln: {id}\n{authorize}#[laravel::input]\n#[validate({auth})]\npub struct {name} {{\n{fields}}}\n\n")
}

// ---------- handlers and routes ----------

/// module → (controller class, [(route, fn name)])
type Modules<'a> = BTreeMap<String, (String, Vec<(&'a Value, String)>)>;

struct Handler {
    module: String,
    func: String,
    method: String,
    uri: String,
    auth: bool,
    api: bool,
}

/// Returns the handler + route files, the wiring text, and PHP route name → `module::fn`.
fn handlers(inv: &Value, models: &Models) -> (Vec<(String, String)>, String, HashMap<String, String>) {
    let inertia = inv["app"]["frontend"].as_str().unwrap_or("").starts_with("inertia");
    let routes: Vec<&Value> = inv["routes"].as_array().into_iter().flatten().filter(|r| ignored(r, &[]).is_none()).collect();
    let mut by_module: Modules = BTreeMap::new();
    let mut names = HashMap::new();
    let mut table: Vec<Handler> = Vec::new();

    for r in &routes {
        let class = controller(r);
        let action = r["action"].as_str().unwrap_or("Closure");
        let method = r["method"].as_str().unwrap_or("GET").to_string();
        let uri = r["uri"].as_str().unwrap_or("/").to_string();
        let (module, func) = if class == "Closure" {
            let slug = uri.trim_matches('/').replace(['/', '-', '.'], "_").replace(['{', '}', '?'], "");
            ("closures".to_string(), ident(&format!("{}_{}", method.to_lowercase(), if slug.is_empty() { "root".into() } else { slug })))
        } else {
            let base = class.trim_end_matches("Controller");
            let func = action.split_once('@').map_or("handle".to_string(), |(_, m)| if m == "__invoke" { "handle".into() } else { ident(m) });
            // `ChirpController` → `chirps`; `ContactsController` is already plural → `contacts`.
            let module = snake(if base.is_empty() { &class } else { base });
            (if module.ends_with('s') { module } else { plural(&module) }, func)
        };
        if let Some(n) = r["name"].as_str() {
            names.insert(n.to_string(), format!("{module}::{func}"));
        }
        let api = r["middleware"].as_array().into_iter().flatten().any(|m| m == "api");
        table.push(Handler { module: module.clone(), func: func.clone(), method, uri, auth: php_auth(r), api });
        let entry = by_module.entry(module).or_insert_with(|| (action.split('@').next().unwrap_or(action).to_string(), Vec::new()));
        if !entry.1.iter().any(|(_, f)| *f == func) {
            entry.1.push((r, func));
        }
    }

    let requests: Vec<&Value> = inv["requests"].as_array().into_iter().flatten().collect();
    let mut files = Vec::new();
    let param_re = Regex::new(r"\{(\w+)\??\}").unwrap();
    for (module, (class, funcs)) in &by_module {
        let controller_file = funcs.first().and_then(|(r, _)| r["action"].as_str()).map(|a| class_basename(a.split('@').next().unwrap_or(a)).to_string());
        let mut body = String::new();
        let mut uses: BTreeSet<String> = BTreeSet::new();
        let any_auth = funcs.iter().all(|(r, _)| php_auth(r));

        // Input structs: inline validate() calls in this controller's file, and FormRequests it type-hints.
        let mut n = 0;
        for req in &requests {
            let file = req["file"].as_str().unwrap_or("");
            let id = req["id"].as_str().unwrap_or("");
            let from_controller = controller_file.as_deref().is_some_and(|c| file.ends_with(&format!("/{c}.php")) && id.contains('#'));
            let form_request = !id.contains('#') && controller_uses(inv, class, class_basename(id.trim_start_matches("request:")));
            if from_controller || form_request {
                n += 1;
                let name = if form_request {
                    class_basename(id.trim_start_matches("request:")).trim_end_matches("Request").to_string()
                } else {
                    format!("{}Input{n}", studly(module))
                };
                body += &input_struct(&name, req, if any_auth { "authenticated" } else { "anyone" }, models);
                if req["rules"].as_object().is_some_and(|r| r.values().filter_map(Value::as_array).flatten().any(|v| v.as_str().is_some_and(|s| s.starts_with("unique:")))) {
                    for (m, _, _) in &models.list {
                        if body.contains(&format!("unique({m}::")) {
                            uses.insert(format!("crate::models::{m}"));
                        }
                    }
                }
                if body.contains("Sometimes<") {
                    uses.insert("laravel::validation::Sometimes".into());
                }
            }
        }
        if n > 0 {
            body = format!("// PORT-TODO: rename each input struct and take it as the handler's last argument: `Valid(input): Valid<Name>`.\n\n{body}");
        }

        for (r, func) in funcs {
            let method = r["method"].as_str().unwrap_or("GET");
            let mut args = Vec::new();
            let params: Vec<String> = param_re.captures_iter(r["uri"].as_str().unwrap_or("")).map(|c| c[1].to_string()).collect();
            if php_auth(r) {
                // `/users/{user}` binds `_user` already; the logged-in user needs another name.
                let me = if params.iter().any(|p| ident(p) == "user") { "_auth_user" } else { "_user" };
                args.push(format!("Authenticated({me}): Authenticated<User>"));
                uses.insert("crate::models::User".into());
            }
            let model_params: Vec<(String, String)> = params.iter().map(|p| (p.clone(), studly(p))).collect();
            if !params.is_empty() && model_params.iter().all(|(_, m)| models.has(m)) {
                for (p, m) in &model_params {
                    args.push(format!("_{}: {m}", ident(p)));
                    uses.insert(format!("crate::models::{m}"));
                }
            } else if params.len() == 1 {
                args.push(format!("Params(_{}): Params<String>", ident(&params[0])));
            } else if !params.is_empty() {
                let pats = params.iter().map(|p| format!("_{}", ident(p))).collect::<Vec<_>>().join(", ");
                let tys = vec!["String"; params.len()].join(", ");
                args.push(format!("Params(({pats})): Params<({tys})>"));
            }
            let ret = if method != "GET" {
                "laravel::Result<Redirect>"
            } else if inertia {
                uses.insert("laravel::inertia::Page".into());
                "laravel::Result<Page>"
            } else {
                uses.insert("laravel::view::View".into());
                "laravel::Result<View>"
            };
            let action = r["action"].as_str().unwrap_or("Closure");
            body += &format!(
                "/// larakiln: {} ({})\npub async fn {func}({}) -> {ret} {{\n    todo!(\"PORT-TODO: port {}\")\n}}\n\n",
                r["id"].as_str().unwrap_or("?"),
                class_basename(action),
                args.join(", "),
                if action == "Closure" { format!("the closure for {method} {}", r["uri"].as_str().unwrap_or("")) } else { action.replace('\\', "\\\\").replace('"', "\\\"") }
            );
        }

        let source = if class == "Closure" { "the PHP closure routes".to_string() } else { class.clone() };
        let mut head = format!("// Generated by larakiln codegen from {source}. Search for PORT-TODO.\n#![allow(unused_imports)] // PORT-TODO: remove once every handler is ported\nuse laravel::prelude::*;\n");
        for u in uses.iter().filter(|u| !u.starts_with("crate::")) {
            head += &format!("use {u};\n");
        }
        let crate_uses: Vec<String> = uses.iter().filter_map(|u| u.strip_prefix("crate::models::")).map(String::from).collect();
        if !crate_uses.is_empty() {
            head += &format!("\nuse crate::models::{{{}}};\n", crate_uses.join(", "));
        }
        files.push((format!("src/http/handlers/{module}.rs"), format!("{head}\n{}", body.trim_end().to_string() + "\n")));
    }

    let mut wiring = String::new();
    let mods: String = by_module.keys().map(|m| format!("pub mod {m};\n")).collect();
    wiring += &format!("**`src/http/handlers/mod.rs`**: add\n\n```rust\n{mods}```\n\n");
    for (file, api) in [("ported", false), ("ported_api", true)] {
        let list: Vec<&Handler> = table.iter().filter(|h| h.api == api).collect();
        if list.is_empty() {
            continue;
        }
        let modules: BTreeSet<&str> = list.iter().map(|h| h.module.as_str()).collect();
        let line = |h: &Handler| {
            let uri = if api { h.uri.strip_prefix("/api").filter(|u| !u.is_empty()).unwrap_or("/").to_string() } else { h.uri.clone() };
            let uri = uri.replace('?', "");
            format!("route.{}(\"{uri}\", {}::{});", h.method.to_lowercase(), h.module, h.func)
        };
        let open: Vec<String> = list.iter().filter(|h| !h.auth).map(|h| format!("    {}", line(h))).collect();
        let authed: Vec<String> = list.iter().filter(|h| h.auth).map(|h| format!("        {}", line(h))).collect();
        let mut text = format!(
            "// Generated by larakiln codegen from the PHP route list. Routes behind `auth` in PHP are behind `Authenticate` here.\n{}use laravel::prelude::*;\n\nuse crate::http::handlers::{{{}}};\n\npub fn routes(route: &mut Router) {{\n",
            if authed.is_empty() { "" } else { "use laravel::auth::Authenticate;\n" },
            modules.iter().copied().collect::<Vec<_>>().join(", ")
        );
        for l in &open {
            text += &format!("{l}\n");
        }
        if !authed.is_empty() {
            text += &format!("\n    route.middleware(Authenticate).group(|route| {{\n{}\n    }});\n", authed.join("\n"));
        }
        text += "}\n";
        files.push((format!("src/routes/{file}.rs"), text));
        let target = if api { "api" } else { "web" };
        wiring += &format!(
            "**`src/routes/mod.rs`**: add `pub mod {file};`. **`src/routes/{target}.rs`**: call `crate::routes::{file}::routes(route);` at the top of `routes`, before any fallback route, and delete the skeleton's own routes for the same URIs (for example `/` and `/login`), or keep them and remove the generated ones.{}\n\n",
            if api { " Laravel Rust already prefixes API routes with `/api`, so the generated URIs don't repeat it." } else { "" }
        );
    }
    (files, wiring, names)
}

/// Whether a controller's PHP source mentions a FormRequest class.
fn controller_uses(inv: &Value, class: &str, request: &str) -> bool {
    let php = Path::new(inv["app"]["path"].as_str().unwrap_or(""));
    let rel = class.trim_start_matches("App\\").replace('\\', "/");
    fs::read_to_string(php.join("app").join(format!("{rel}.php"))).is_ok_and(|s| s.contains(request))
}

// ---------- views ----------

fn views(inv: &Value, php: &Path, names: &HashMap<String, String>) -> Vec<(String, String)> {
    inv["views"].as_array().into_iter().flatten().filter_map(|v| {
        let file = v["file"].as_str()?;
        let name = v["id"].as_str()?.trim_start_matches("view:");
        let src = fs::read_to_string(php.join(file)).ok()?;
        let out = format!("{{# Generated by larakiln codegen from {file}. Search for PORT-TODO. #}}\n{{# larakiln: view:{name} #}}\n{}", blade_to_jinja(&src, names));
        Some((format!("resources/views/{}.html", name.replace('.', "/")), out))
    }).collect()
}

fn unquote(s: &str) -> String {
    s.trim().trim_matches(['\'', '"']).to_string()
}

/// Splits `a, 'b, c', [d, e]` at top-level commas.
fn split_args(s: &str) -> Vec<String> {
    let (mut out, mut cur, mut depth, mut quote) = (Vec::new(), String::new(), 0, None);
    for ch in s.chars() {
        match (quote, ch) {
            (Some(q), c) if c == q => quote = None,
            (Some(_), _) => {}
            (None, '\'' | '"') => quote = Some(ch),
            (None, '(' | '[') => depth += 1,
            (None, ')' | ']') => depth -= 1,
            (None, ',') if depth == 0 => {
                out.push(cur.trim().to_string());
                cur.clear();
                continue;
            }
            _ => {}
        }
        cur.push(ch);
    }
    if !cur.trim().is_empty() {
        out.push(cur.trim().to_string());
    }
    out
}

/// PHP expression → Jinja expression; the flag is true when something PHP-only is left.
fn expr(e: &str, names: &HashMap<String, String>) -> (String, bool) {
    let mut s = e.trim().to_string();
    let route = Regex::new(r#"route\(\s*'([^']+)'"#).unwrap();
    let mut unknown_route = false;
    s = route.replace_all(&s, |c: &regex::Captures| match names.get(&c[1]) {
        Some(h) => format!("route(\"{h}\""),
        None => {
            unknown_route = true;
            format!("route(\"{}\"", &c[1])
        }
    }).into_owned();
    let format = Regex::new(r"->format\(([^)]*)\)").unwrap();
    let php_date_format = format.is_match(&s); // PHP date() letters, not strftime: rewrite the format by hand
    s = format.replace_all(&s, "|date($1)").into_owned();
    s = s.replace("->diffForHumans()", "|for_humans");
    s = Regex::new(r"count\(\s*\$(\w+)\s*\)").unwrap().replace_all(&s, "$1|length").into_owned();
    s = s.replace("->", ".").replace("===", "==").replace("!==", "!=").replace("&&", " and ").replace("||", " or ");
    s = Regex::new(r"!([^=])").unwrap().replace_all(&s, "not $1").into_owned();
    s = Regex::new(r"\bnull\b").unwrap().replace_all(&s, "none").into_owned();
    s = Regex::new(r"\$(\w+)").unwrap().replace_all(&s, "$1").into_owned();
    s = Regex::new(r"'([^'\x22]*)'").unwrap().replace_all(&s, "\"$1\"").into_owned();
    s = Regex::new(r"\s+").unwrap().replace_all(&s, " ").trim().to_string();
    let allowed = ["route", "old", "url", "csrf_field", "vite", "session", "error", "asset", "date"];
    let code = Regex::new(r#""[^"]*""#).unwrap().replace_all(&s, "\"\"").into_owned(); // checks ignore string contents
    let calls_ok = Regex::new(r"(\w+)\(").unwrap().captures_iter(&code).all(|c| allowed.contains(&&c[1]));
    let todo = unknown_route || php_date_format || code.contains("::") || code.contains("this.") || !calls_ok;
    (s, todo)
}

fn blade_to_jinja(src: &str, names: &HashMap<String, String>) -> String {
    let mut s = Regex::new(r"(?s)\{\{--(.*?)--\}\}").unwrap().replace_all(src, "{#$1#}").into_owned();
    // Inside @error('field') … @enderror, `$message` is that field's error.
    s = Regex::new(r#"(?s)@error\(\s*['"]([^'"]+)['"]\s*\)(.*?)@enderror"#).unwrap().replace_all(&s, |c: &regex::Captures| {
        format!("@error('{}'){}@enderror", &c[1], c[2].replace("$message", &format!("error('{}')", &c[1])))
    }).into_owned();
    s = Regex::new(r"(?s)(^|[^@])\{\{(.*?)\}\}").unwrap().replace_all(&s, |c: &regex::Captures| {
        let (e, todo) = expr(&c[2], names);
        format!("{}{{{{ {e} }}}}{}", &c[1], if todo { " {# PORT-TODO: check expression #}" } else { "" })
    }).into_owned();
    s = Regex::new(r"(?s)\{!!(.*?)!!\}").unwrap().replace_all(&s, |c: &regex::Captures| {
        let (e, todo) = expr(&c[1], names);
        format!("{{{{ {e}|safe }}}}{}", if todo { " {# PORT-TODO: check expression #}" } else { "" })
    }).into_owned();

    // Directives, with balanced (...) arguments.
    let at = Regex::new(r"(^|[\s>])@(\w+)").unwrap();
    let loop_re = Regex::new(r"^(.*)\s+as\s+(?:\$(\w+)\s*=>\s*)?\$(\w+)$").unwrap();
    let mut out = String::new();
    let mut rest = s.as_str();
    let mut stack: Vec<String> = Vec::new();
    while let Some(c) = at.captures(rest) {
        let m = c.get(0).unwrap();
        let name = c[2].to_string();
        out += &rest[..m.start()];
        out += &c[1];
        let mut after = &rest[m.end()..];
        let mut arg: Option<String> = None;
        let trimmed = after.trim_start_matches([' ', '\t']);
        if trimmed.starts_with('(') {
            if let Some(b) = balanced(trimmed, '(', ')') {
                arg = Some(b[1..b.len() - 1].to_string());
                after = &trimmed[b.len()..];
            }
        }
        let a = arg.clone().unwrap_or_default();
        let ex = |e: &str| {
            let (x, todo) = expr(e, names);
            (x, if todo { " {# PORT-TODO: check expression #}" } else { "" })
        };
        let text: String = match name.as_str() {
            "extends" => format!("{{% extends \"{}\" %}}", unquote(&split_args(&a)[0])),
            "section" => {
                let args = split_args(&a);
                if args.len() > 1 {
                    let (v, t) = ex(&args[1]);
                    format!("{{% block {} %}}{{{{ {v} }}}}{{% endblock %}}{t}", unquote(&args[0]))
                } else {
                    format!("{{% block {} %}}", unquote(&a))
                }
            }
            "endsection" | "stop" | "show" => "{% endblock %}".into(),
            "yield" => {
                let args = split_args(&a);
                let default = args.get(1).map(|d| unquote(d)).unwrap_or_default();
                format!("{{% block {} %}}{default}{{% endblock %}}", unquote(&args[0]))
            }
            "include" => {
                let args = split_args(&a);
                format!("{{% include \"{}\" %}}{}", unquote(&args[0]), if args.len() > 1 { " {# PORT-TODO: pass the include's data #}" } else { "" })
            }
            "foreach" | "forelse" => {
                stack.push(name.clone());
                match loop_re.captures(a.trim()) {
                    Some(f) => {
                        let (list, t) = ex(&f[1]);
                        match f.get(2) {
                            Some(k) => format!("{{% for {}, {} in {list}|items %}}{t}", k.as_str(), &f[3]),
                            None => format!("{{% for {} in {list} %}}{t}", &f[3]),
                        }
                    }
                    None => format!("{{# PORT-TODO: @{name}({a}) #}}"),
                }
            }
            "empty" if stack.last().is_some_and(|t| t == "forelse") && arg.is_none() => "{% else %}".into(),
            "endforeach" | "endforelse" => {
                stack.pop();
                "{% endfor %}".into()
            }
            "if" => {
                let (x, t) = ex(&a);
                format!("{{% if {x} %}}{t}")
            }
            "elseif" => {
                let (x, t) = ex(&a);
                format!("{{% elif {x} %}}{t}")
            }
            "else" => "{% else %}".into(),
            "unless" => {
                let (x, t) = ex(&a);
                format!("{{% if not ({x}) %}}{t}")
            }
            "isset" => {
                let (x, t) = ex(&a);
                format!("{{% if {x} is defined and {x} is not none %}}{t}")
            }
            "empty" => {
                let (x, t) = ex(&a);
                format!("{{% if not {x} %}}{t}")
            }
            "endif" | "endunless" | "endisset" | "endempty" => "{% endif %}".into(),
            "csrf" => "{{ csrf_field() }}".into(),
            "method" => format!("<input type=\"hidden\" name=\"_method\" value=\"{}\">", unquote(&a).to_uppercase()),
            "error" => format!("{{% if error(\"{}\") %}}", unquote(&split_args(&a)[0])),
            "enderror" => "{% endif %}".into(),
            "vite" => {
                let inner = a.trim().trim_start_matches('[').trim_end_matches(']');
                split_args(inner).iter().map(|f| format!("{{{{ vite(\"{}\") }}}}", unquote(f))).collect()
            }
            "json" => {
                let (x, t) = ex(&split_args(&a)[0]);
                format!("{{{{ {x}|tojson }}}}{t}")
            }
            "inertia" => "{{ inertia }}".into(),
            "inertiaHead" => "{{ inertia_head }}".into(),
            _ if name.chars().next().is_some_and(char::is_lowercase) => {
                format!("{{# PORT-TODO: @{name}{} has no verified Jinja mapping #}}", arg.map(|a| format!("({a})")).unwrap_or_default())
            }
            _ => format!("@{name}"),
        };
        out += &text;
        rest = after;
    }
    out += rest;
    let components = Regex::new(r"<(x-[\w.\-:]+|livewire:[\w.\-]+)").unwrap();
    components.replace_all(&out, "{# PORT-TODO: Blade component <$1> #}<$1").into_owned()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn migrations_become_columns() {
        let mut cols = Vec::new();
        for s in [
            "{\n            $table->id()".trim_start_matches('{').trim(),
            "$table->foreignId('user_id')->constrained()->cascadeOnDelete()",
            "$table->string('message')",
            "$table->timestamp('seen_at')->nullable()",
            "$table->unique('message')",
            "$table->timestamps()",
            "$table->rememberToken()",
        ] {
            apply(&mut cols, s);
        }
        let got: Vec<(String, String, bool)> = cols.into_iter().map(|c| (c.name, c.ty, c.nullable)).collect();
        let want = [("id", "i64", false), ("user_id", "i64", false), ("message", "String", false), ("seen_at", "Timestamp", true), ("created_at", "Timestamp", false), ("updated_at", "Timestamp", false), ("remember_token", "RememberToken", true)];
        assert_eq!(got, want.map(|(a, b, c)| (a.to_string(), b.to_string(), c)));
    }

    #[test]
    fn rules_become_validate_attributes() {
        let models = Models { list: vec![("User".into(), json!({}), "users".into())], tables: HashMap::new() };
        let req = json!({"id": "request:X#1", "rules": {
            "message": ["required", "string", "max:255"],
            "age": ["nullable", "integer", "min:18"],
            "email": ["required", "email", "unique:users,email"],
            "role": ["in:admin,editor"],
            "photo": ["image"]
        }});
        let s = input_struct("NewChirp", &req, "authenticated", &models);
        assert!(s.contains("#[validate(authenticated)]\npub struct NewChirp"), "{s}");
        assert!(s.contains("#[validate(required, max_length(255))]\n    pub message: String,"), "{s}");
        assert!(s.contains("#[validate(min_value(18))]\n    pub age: Option<i64>,"), "{s}");
        assert!(s.contains("#[validate(required, email, unique(User::email))]"), "{s}");
        assert!(s.contains("one_of(\"admin\", \"editor\")"), "{s}");
        assert!(s.contains("PORT-TODO: no verified mapping for image"), "{s}");
    }

    #[test]
    fn blade_becomes_jinja() {
        let names: HashMap<String, String> = [("chirps.store".to_string(), "chirps::store".to_string()), ("chirps.edit".to_string(), "chirps::edit".to_string())].into();
        let blade = "@extends('layout')\n@section('content')\n<form action=\"{{ route('chirps.store') }}\">\n@csrf\n@method('delete')\n@error('message')\n<p>{{ $message }}</p>\n@enderror\n@foreach ($chirps as $chirp)\n<a href=\"{{ route('chirps.edit', $chirp) }}\">{{ $chirp->user->name }}</a>\n@if ($chirp->user->is(auth()->user()))\nx\n@endif\n@endforeach\n@endsection\nmail@example.com\n";
        let j = blade_to_jinja(blade, &names);
        for want in [
            "{% extends \"layout\" %}",
            "{% block content %}",
            "{{ route(\"chirps::store\") }}",
            "{{ csrf_field() }}",
            "value=\"DELETE\"",
            "{% if error(\"message\") %}\n<p>{{ error(\"message\") }}</p>\n{% endif %}",
            "{% for chirp in chirps %}",
            "{{ route(\"chirps::edit\", chirp) }}",
            "{{ chirp.user.name }}",
            "{% if chirp.user.is(auth().user()) %} {# PORT-TODO: check expression #}",
            "action=\"{{ route(\"chirps::store\") }}\">",
            "{% endfor %}\n{% endblock %}",
            "mail@example.com",
        ] {
            assert!(j.contains(want), "missing {want:?} in:\n{j}");
        }
    }

    #[test]
    fn foreign_keys_take_their_keys_type() {
        let col = |name: &str, ty: &str| Column { name: name.into(), ty: ty.into(), nullable: false, note: None };
        let mut models = Models {
            list: vec![
                ("Account".into(), json!({"relations": [{"name": "contacts", "related": "Contact", "type": "hasMany"}]}), "accounts".into()),
                ("Contact".into(), json!({"relations": [{"name": "organization", "related": "Organization", "type": "belongsTo"}]}), "contacts".into()),
                ("Organization".into(), json!({}), "organizations".into()),
            ],
            tables: HashMap::from([
                ("accounts".into(), vec![col("id", "i32")]),
                ("contacts".into(), vec![col("id", "i64"), col("account_id", "i64"), col("organization_id", "i64")]),
                ("organizations".into(), vec![col("id", "i32")]),
            ]),
        };
        models.match_key_types();
        let ty = |c: &str| models.tables["contacts"].iter().find(|x| x.name == c).unwrap().ty.clone();
        assert_eq!((ty("account_id"), ty("organization_id"), ty("id")), ("i32".into(), "i32".into(), "i64".into()));
    }

}