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
//! Turns a scored inventory into PORTING.md: the porting checklist in dependency order.
//! `/port-next` takes the first unchecked item. Re-running keeps every `[x]` already ticked.

use std::collections::HashSet;
use std::fs;
use std::path::Path;

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

use crate::feasibility;

/// (heading, sections, what to know before starting the phase)
const PHASES: &[(&str, &[&str], &str)] = &[
    ("1. Data and dependencies", &["data_risks", "packages"], "Decide these first: they change what the Rust app reads from the shared database and which crates it needs. Green packages need nothing and aren't listed."),
    ("2. Models and policies", &["models", "policies"], "Each model before the models that belong to it. Policies go in their model's file."),
    ("3. Input structs", &["requests"], "One `#[laravel::input]` struct per form request or `validate()` call (validation.md)."),
    ("4. Views", &["views"], "Layouts first, then the pages that extend them (blade-to-jinja.md)."),
    ("5. Routes and handlers", &["routes"], "One handler module per controller (routing-handlers.md)."),
    ("6. Background work", &["middleware", "jobs", "mail", "notifications", "events", "listeners", "commands", "schedule"], "Drain the PHP queue before switching jobs over."),
    ("7. Tests", &["tests"], "Port each PHP test as `#[laravel::test]`; a passing port is part of each item's proof."),
];

pub fn run(inventory: &Path, out: &Path) -> Result<(), String> {
    let mut inv = feasibility::load(inventory)?;
    feasibility::score_all(&mut inv);

    if let Some(app) = inv["app"]["path"].as_str() {
        let dir = out.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
        if let (Ok(app), Ok(dir)) = (fs::canonicalize(app), fs::canonicalize(dir)) {
            if dir.starts_with(&app) {
                return Err(format!("{} is inside the PHP app; write it somewhere else (hard rule 2)", out.display()));
            }
        }
    }

    let done = fs::read_to_string(out).map(|s| checked(&s)).unwrap_or_default();
    let (text, total, ticked) = render(&inv, &done);
    fs::write(out, text).map_err(|e| e.to_string())?;
    println!("Wrote {}: {ticked}/{total} items done.", out.display());
    Ok(())
}

/// Ids ticked in an existing PORTING.md.
fn checked(md: &str) -> HashSet<String> {
    let re = Regex::new(r"(?m)^\s*- \[[xX]\] `([^`]+)`").unwrap();
    re.captures_iter(md).map(|c| c[1].to_string()).collect()
}

fn items<'a>(inv: &'a Value, section: &str) -> Vec<&'a Value> {
    inv[section].as_array().into_iter().flatten().collect()
}

/// Models whose belongs-to targets are already placed come first; cycles fall back to name order.
fn models_in_order(models: Vec<&Value>) -> Vec<&Value> {
    let names: HashSet<&str> = models.iter().filter_map(|m| m["id"].as_str()?.strip_prefix("model:")).collect();
    let needs = |m: &Value| -> Vec<String> {
        m["relations"].as_array().into_iter().flatten()
            .filter(|r| r["type"] == "belongsTo")
            .filter_map(|r| r["related"].as_str())
            .filter(|r| names.contains(r))
            .map(String::from)
            .collect()
    };
    let mut left = models;
    let mut placed: HashSet<String> = HashSet::new();
    let mut ordered = Vec::new();
    while !left.is_empty() {
        let ready = left.iter().position(|m| {
            let me = m["id"].as_str().unwrap_or("").trim_start_matches("model:");
            needs(m).iter().all(|n| n == me || placed.contains(n))
        });
        let next = left.remove(ready.unwrap_or(0)); // ponytail: cycle → take the next by name
        placed.insert(next["id"].as_str().unwrap_or("").trim_start_matches("model:").to_string());
        ordered.push(next);
    }
    ordered
}

fn line(item: &Value, done: &HashSet<String>, note: Option<String>) -> String {
    let id = item["id"].as_str().unwrap_or("?");
    let mark = if done.contains(id) { "x" } else { " " };
    let mut s = format!("- [{mark}] `{id}`");
    if let Some(n) = note {
        s += &format!(" · {n}");
    }
    if item["status"] == "yellow" {
        s += &format!(" · **needs a human:** {}", item["reason"].as_str().unwrap_or(""));
    }
    s + "\n"
}

pub(crate) fn controller(route: &Value) -> String {
    let action = route["action"].as_str().unwrap_or("Closure");
    let class = action.split('@').next().unwrap_or(action);
    class.rsplit('\\').next().unwrap_or(class).to_string()
}

fn render(inv: &Value, done: &HashSet<String>) -> (String, usize, usize) {
    let mut body = String::new();
    let (mut total, mut ticked) = (0, 0);
    let mut count = |item: &Value| {
        total += 1;
        if done.contains(item["id"].as_str().unwrap_or("")) {
            ticked += 1;
        }
    };

    for (heading, sections, hint) in PHASES {
        let mut list: Vec<&Value> = sections.iter().flat_map(|s| items(inv, s)).filter(|i| i["status"] != "red").collect();
        list.retain(|i| !(i["id"].as_str().unwrap_or("").starts_with("pkg:") && i["status"] == "green"));
        if list.is_empty() {
            continue;
        }
        body += &format!("## {heading}\n\n{hint}\n\n");
        match sections[0] {
            "models" => {
                let (models, rest): (Vec<_>, Vec<_>) = list.into_iter().partition(|i| i["id"].as_str().unwrap_or("").starts_with("model:"));
                for m in models_in_order(models).into_iter().chain(rest) {
                    count(m);
                    body += &line(m, done, None);
                }
            }
            "views" => {
                list.sort_by_key(|v| !v["directives"].as_array().is_some_and(|d| d.iter().any(|x| x == "@yield")));
                for v in list {
                    count(v);
                    body += &line(v, done, v["file"].as_str().map(|f| format!("`{f}`")));
                }
            }
            "routes" => {
                let mut groups: Vec<String> = list.iter().map(|r| controller(r)).collect();
                let mut seen = HashSet::new();
                groups.retain(|g| seen.insert(g.clone()));
                for g in groups {
                    body += &format!("### {g}\n\n");
                    for r in list.iter().filter(|r| controller(r) == g) {
                        count(r);
                        let action = r["action"].as_str().unwrap_or("");
                        let method = action.split_once('@').map(|(_, m)| format!("`{m}`"));
                        body += &line(r, done, method);
                    }
                    body += "\n";
                }
            }
            _ => {
                for i in list {
                    count(i);
                    body += &line(i, done, None);
                }
            }
        }
        if !body.ends_with("\n\n") {
            body += "\n";
        }
    }

    let blocked: Vec<&Value> = PHASES.iter().flat_map(|(_, s, _)| s.iter()).flat_map(|s| items(inv, s)).filter(|i| i["status"] == "red").collect();
    if !blocked.is_empty() {
        body += &format!(
            "## Blocked ({})\n\nNo verified mapping. Don't port these piecemeal (hard rule 3): decide per item to keep it in PHP behind the path split, rewrite it first, or wait for a verified mapping (livewire-filament.md, packages.md). They aren't counted in the progress above.\n\n",
            blocked.len()
        );
        for b in blocked {
            body += &format!("- `{}`: {}\n", b["id"].as_str().unwrap_or("?"), b["reason"].as_str().unwrap_or(""));
        }
        body += "\n";
    }

    let app = &inv["app"];
    let head = format!(
        "# Porting plan: {}\n\nLaravel {} · DB {} · frontend {}\n\n**Progress: {ticked}/{total} items done.** Generated by `larakiln manifest`; re-run it after a new `larakiln audit` and ticked items stay ticked.\n\n**How to use:** `/port-next` takes the first unticked item from the top. Tick it only when its Rust code compiles and its ported tests pass.\n\n",
        app["path"].as_str().unwrap_or("?"),
        app["laravel"].as_str().unwrap_or("?"),
        app["db"].as_str().unwrap_or("?"),
        app["frontend"].as_str().unwrap_or("?"),
    );
    let mut notes = String::new();
    for note in inv["notes"].as_array().into_iter().flatten() {
        notes += &format!("> Note: {}\n", note.as_str().unwrap_or(""));
    }
    if !notes.is_empty() {
        notes += "\n";
    }
    (head + &notes + &body, total, ticked)
}

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

    #[test]
    fn orders_models_keeps_ticks_and_sets_aside_blockers() {
        let mut inv = json!({
            "app": {"path": "/nowhere"},
            "models": [
                {"id": "model:Chirp", "relations": [{"type": "belongsTo", "related": "User"}]},
                {"id": "model:User", "relations": [{"type": "hasMany", "related": "Chirp"}]}
            ],
            "packages": [
                {"id": "pkg:laravel/framework", "name": "laravel/framework", "dev": false},
                {"id": "pkg:livewire/livewire", "name": "livewire/livewire", "dev": false}
            ],
            "routes": [
                {"id": "route:GET:/chirps", "action": "App\\Http\\Controllers\\ChirpController@index", "uri": "/chirps"}
            ]
        });
        feasibility::score_all(&mut inv);
        let done: HashSet<String> = ["model:User".to_string()].into();
        let (md, total, ticked) = render(&inv, &done);

        assert!(md.find("`model:User`").unwrap() < md.find("`model:Chirp`").unwrap(), "{md}");
        assert!(md.contains("- [x] `model:User`"));
        assert!(md.contains("### ChirpController") && md.contains("`route:GET:/chirps` · `index`"));
        assert!(!md.contains("pkg:laravel/framework"), "green packages need no work");
        assert!(md.contains("## Blocked (1)") && md.contains("- `pkg:livewire/livewire`"));
        assert_eq!((total, ticked), (3, 1));
        assert_eq!(checked(&md), done);
    }
}