//! Load the JSON manifest the macro emitted at build time.

use roundabout_orm_schema::EntityDef;
use std::path::Path;

/// Read every `*.json` file in `dir` as an [`EntityDef`].
///
/// Files that fail to parse are skipped with a warning so one bad file does not
/// take the whole runtime down.
pub fn load_dir(dir: impl AsRef<Path>) -> Vec<EntityDef> {
    let dir = dir.as_ref();
    let mut out = Vec::new();
    let Ok(entries) = std::fs::read_dir(dir) else {
        eprintln!("[roundabout_orm] schema dir not found: {}", dir.display());
        return out;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        match std::fs::read_to_string(&path).map(|s| serde_json::from_str::<EntityDef>(&s)) {
            Ok(Ok(def)) => out.push(def),
            Ok(Err(e)) => eprintln!("[roundabout_orm] bad manifest {}: {e}", path.display()),
            Err(e) => eprintln!("[roundabout_orm] cannot read {}: {e}", path.display()),
        }
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}
