main
Colby Knox 0.2.120 source: repair libraries with 1024 mechanical layers (#44): xcopy makes toLib and copies height, layer_map get… d910148
//! altium_layer_map and the layer map's files (#41). The organisation's default is `adom-layer-map.json` beside its
//! library; the user's default is `layer-map.json` in the bridge's own folder. The footprint verbs call `agent_params`
//! for the map in effect and `report` to say in their reply which layer each kind of graphic went on.
use crate::layermap::{self, Effective};
use crate::support::s;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};

const LIBRARY_FILE: &str = "adom-layer-map.json";

fn user_file() -> PathBuf { crate::agent::cache_dir().join("layer-map.json") }

fn library_file(lib: &str) -> Option<PathBuf> {
    let p = Path::new(lib);
    let dir = if p.is_dir() { p } else { p.parent()? };
    Some(dir.join(LIBRARY_FILE))
}

fn read_json(p: &Path) -> Option<Value> { serde_json::from_str(&std::fs::read_to_string(p).ok()?).ok() }

/// A template's library path as written, made absolute against the folder of the file that named it.
fn absolute(t: &str, base: Option<&Path>) -> String {
    let p = Path::new(t);
    if p.is_absolute() || t.contains(':') { return t.to_string(); }
    base.and_then(|b| b.parent()).map(|d| d.join(p).to_string_lossy().to_string()).unwrap_or_else(|| t.to_string())
}

fn with_template_abs(doc: Option<Value>, file: &Path) -> Option<Value> {
    let mut d = doc?;
    if let Some(l) = d.pointer("/template/libraryPath").and_then(|v| v.as_str()).map(|v| absolute(v, Some(file))) {
        d["template"]["libraryPath"] = json!(l);
    }
    Some(d)
}

/// The call's own map: `layerMap` and `template` ({libraryPath, footprint}) from the verb's arguments.
fn call_doc(args: &Value) -> Option<Value> {
    let m = args.get("layerMap").filter(|v| v.is_object());
    let t = args.get("template").filter(|v| v.is_object());
    if m.is_none() && t.is_none() { return None; }
    let mut d = json!({});
    if let Some(m) = m { d["layerMap"] = m.clone(); }
    if let Some(t) = t { d["template"] = t.clone(); }
    Some(d)
}

/// The map in effect for a footprint in `lib`.
pub fn effective(args: &Value, lib: Option<&str>) -> Effective {
    let lf = lib.and_then(library_file);
    let library = lf.as_ref().and_then(|f| with_template_abs(read_json(f), f));
    let uf = user_file();
    let user = with_template_abs(read_json(&uf), &uf);
    layermap::merge(call_doc(args).as_ref(), library.as_ref(), user.as_ref())
}

/// The agent parameters for the map in effect (empty when no map is set: footprints come out as before), and the map.
pub fn agent_params(args: &Value, lib: Option<&str>) -> (Vec<(&'static str, String)>, Effective) {
    let e = effective(args, lib);
    let mut p = Vec::new();
    let lm = layermap::agent_param(&e);
    if !lm.is_empty() { p.push(("lmap", lm)); }
    if let Some((l, f, _)) = &e.template { p.push(("tplLib", l.replace('/', "\\"))); p.push(("tplFp", f.clone())); }
    (p, e)
}

/// Adds `layerMap` to a footprint verb's reply: the map, with the layers the agent used (`layersUsed`) and what a
/// template copy did.
pub fn report(r: &mut Value, e: &Effective) {
    let d = r.get("data").cloned().unwrap_or_else(|| r.clone());
    let mut m = layermap::report(e, &d["layersUsed"]);
    if let Some(t) = d.get("template").filter(|t| t["library"].as_str().is_some_and(|l| !l.is_empty())) { m["templateCopy"] = t.clone(); }
    r["layerMap"] = m;
}

fn write(p: &Path, doc: &Value) -> Result<(), String> {
    if let Some(d) = p.parent() { std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?; }
    std::fs::write(p, serde_json::to_string_pretty(doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", p.display()))
}

fn scope_file(args: &Value) -> Result<PathBuf, Value> {
    match s(args, "scope").as_deref() {
        Some("user") => Ok(user_file()),
        Some("library") => s(args, "libraryPath").and_then(|l| library_file(&l)).ok_or_else(|| json!({"success": false, "errorCode": "bad_args", "error": "scope library needs libraryPath (the library, or its folder)"})),
        _ => Err(json!({"success": false, "errorCode": "bad_args", "error": "scope is user (your default) or library (adom-layer-map.json beside libraryPath: everyone using that folder)"})),
    }
}

/// A PcbLib's layer records as saved (read from the file, no Altium): how many mechanical layers it defines and how
/// many are on. Up to 0.2.118 the footprint verbs left every library they touched with all 1024 mechanical layers
/// defined (#44); `bloated` says so (1000 or more defined, under half on). Copy such a library's footprints into a fresh
/// one (altium_xcopy_footprint) to repair it.
pub fn library_layers(bytes: &[u8]) -> Value {
    let t = String::from_utf8_lossy(bytes);
    let (mut records, mut mech, mut on) = (std::collections::BTreeSet::new(), 0usize, 0usize);
    for (i, _) in t.match_indices("LAYER_V8_") {
        let rest = &t[i + 9..];
        let n: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
        if n.is_empty() { continue; }
        let after = &rest[n.len()..];
        if after.starts_with("NAME=") { records.insert(n.clone()); }
        if let Some(v) = after.strip_prefix("MECHENABLED=") {
            mech += 1;
            if v.starts_with("TRUE") { on += 1; }
        }
    }
    json!({"layerRecords": records.len(), "mechanicalLayers": mech, "mechanicalLayersOn": on, "bloated": mech >= 1000 && on < mech / 2,
        "_hint": if mech >= 1000 { "This file defines all 1024 mechanical layers (left by altium-bridge 0.2.118 and earlier, #44). A library: copy its footprints into a fresh one with altium_xcopy_footprint. A board: it still works, only larger." } else { "Counted from the saved file: save the library first for its current state." }})
}

fn get(args: &Value) -> Value {
    let lib = s(args, "libraryPath");
    let e = effective(args, lib.as_deref());
    let lf = lib.as_deref().and_then(library_file);
    let mut r = json!({"success": true, "files": {"user": {"path": user_file(), "exists": user_file().is_file()}}});
    if let Some(f) = lf { r["files"]["library"] = json!({"path": f, "exists": f.is_file()}); }
    let m = layermap::report(&e, &json!([]));
    r["layerMap"] = m;
    if let Some(stats) = lib.as_deref().filter(|l| { let l = l.to_lowercase(); l.ends_with(".pcblib") || l.ends_with(".pcbdoc") }).and_then(|l| std::fs::read(l).ok()).map(|b| library_layers(&b)) {
        r["libraryLayers"] = stats;
    }
    r["_hint"] = json!("Each key shows the layer asked for and where it comes from: the call, the library's adom-layer-map.json, your default, or the built-in layer. A typed layer (CourtyardTop) the library lacks is made, as a top/bottom pair, the first time a footprint uses it.");
    r
}

fn set(args: &Value) -> Value {
    let file = match scope_file(args) { Ok(f) => f, Err(e) => return e };
    let incoming = call_doc(args).unwrap_or(json!({}));
    let check = layermap::merge(Some(&incoming), None, None);
    if !check.errors.is_empty() { return json!({"success": false, "errorCode": "bad_layer_map", "error": "nothing was written", "refused": check.errors}); }
    if incoming.get("layerMap").is_none() && incoming.get("template").is_none() {
        return json!({"success": false, "errorCode": "bad_args", "error": "set takes layerMap ({key: layer}) and/or template ({libraryPath, footprint})"});
    }
    let replace = args.get("replace").and_then(|b| b.as_bool()) == Some(true);
    let mut doc = if replace { json!({}) } else { read_json(&file).unwrap_or(json!({})) };
    if let Some(m) = incoming["layerMap"].as_object() {
        let cur = doc["layerMap"].as_object().cloned().unwrap_or_default();
        let mut merged = cur;
        for (k, v) in m { if v.is_null() { merged.remove(k); } else { merged.insert(k.clone(), v.clone()); } }
        doc["layerMap"] = json!(merged);
    }
    if let Some(t) = incoming.get("template") { doc["template"] = t.clone(); }
    doc["note"] = json!("Read by altium-bridge for every footprint it builds in this scope (altium_layer_map). Keys: overlay, fab, courtyard, body3d, comment, balls, centroid, designator, outline, dimensions.");
    if let Err(e) = write(&file, &doc) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }
    let mut r = get(args);
    r["written"] = json!(file);
    r["_hint"] = json!("Written. Footprints built from now on use it; ones already built keep their layers. altium_layer_map {action:'get'} shows the map in effect.");
    r
}

fn clear(args: &Value) -> Value {
    let file = match scope_file(args) { Ok(f) => f, Err(e) => return e };
    if !file.is_file() { return json!({"success": true, "cleared": false, "path": file, "_hint": "There was no map in this scope."}); }
    let keys: Vec<String> = args.get("keys").and_then(|k| k.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();
    if keys.is_empty() {
        if let Err(e) = std::fs::remove_file(&file) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }
        return json!({"success": true, "cleared": true, "path": file, "_hint": "The map in this scope is gone; the next scope down (or the built-in layers) applies."});
    }
    let mut doc = read_json(&file).unwrap_or(json!({}));
    for k in &keys {
        if k == "template" { if let Some(o) = doc.as_object_mut() { o.remove("template"); } }
        else if let Some(m) = doc["layerMap"].as_object_mut() { m.remove(k); }
    }
    if let Err(e) = write(&file, &doc) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }
    json!({"success": true, "cleared": keys, "path": file})
}

fn from_template(args: &Value) -> Value {
    let (Some(lib), Some(fp)) = (s(args, "libraryPath"), s(args, "footprint")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "libraryPath and footprint (the template footprint) are required"});
    };
    let read = crate::project::read_footprint(&json!({"libraryPath": lib, "name": fp}));
    if read["success"] != true { return read; }
    let details = read["layerDetails"].as_array().cloned().unwrap_or_default();
    let (map, notes) = layermap::propose(&details);
    let proposal = json!({"layerMap": map, "template": {"libraryPath": lib, "footprint": fp}});
    let keep: Vec<Value> = read["texts"].as_array().cloned().unwrap_or_default().into_iter().filter(|t| t["text"].as_str().is_some_and(|x| x.starts_with('.'))).collect();
    let mut r = json!({"success": true, "proposal": proposal, "notes": notes, "templateLayers": details,
        "templateCopy": {"keeps": {"specialStrings": keep, "centroidLayer": map.get("centroid")}, "leavesOut": "pads, the example outline, courtyard, assembly and silkscreen graphics, dimensions, and texts that are not special strings"}});
    if let Some(scope) = s(args, "save") {
        let mut a = proposal.clone();
        a["scope"] = json!(scope);
        a["libraryPath"] = json!(s(args, "saveTo").unwrap_or(lib.clone()));
        let w = set(&a);
        if w["success"] != true { return w; }
        r["written"] = w["written"].clone();
    }
    r["_hint"] = json!(if r.get("written").is_some() { "Saved: footprints built in that scope now use these layers and start from the template." }
        else { "A proposal only: altium_layer_map {action:'set', scope:'library'|'user', layerMap, template} keeps it (or call again with save)." });
    r
}

/// PcbLib files under a folder, a few levels deep.
fn pcblibs(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
    if depth == 0 || out.len() > 200 { return; }
    let Ok(rd) = std::fs::read_dir(dir) else { return };
    for e in rd.flatten() {
        let p = e.path();
        if p.is_dir() { pcblibs(&p, depth - 1, out); }
        else if p.extension().and_then(|x| x.to_str()).is_some_and(|x| x.eq_ignore_ascii_case("pcblib")) { out.push(p); }
    }
}

fn find_template(args: &Value) -> Value {
    let mut pa = json!({"under": "WorkspaceManager"});
    if let Some(ed) = s(args, "edition") { pa["edition"] = json!(ed); }
    let prefs = crate::prefs::preferences(&pa);
    let cur = prefs["current"].as_object().cloned().unwrap_or_default();
    let pick = |suffix: &str| cur.iter().find(|(k, _)| k.ends_with(suffix)).and_then(|(_, v)| v.as_str()).unwrap_or("").to_string();
    let files = pick("Template Files");
    let local = pick("Template Path");
    let entries = layermap::template_entries(&files);
    let pcb: Vec<&(String, String, Option<String>)> = entries.iter().filter(|e| e.0.to_ascii_uppercase().ends_with("PCBLIB")).collect();
    let mut found = Vec::new();
    let pd = std::env::var("ProgramData").unwrap_or_else(|_| "C:\\ProgramData".into());
    if let Ok(rd) = std::fs::read_dir(Path::new(&pd).join("Altium")) {
        for e in rd.flatten() { pcblibs(&e.path().join("VaultsFileCache"), 6, &mut found); }
    }
    let mut local_libs = Vec::new();
    if !local.is_empty() { pcblibs(Path::new(&local), 3, &mut local_libs); }
    let guids: Vec<String> = pcb.iter().filter_map(|e| e.2.clone()).map(|g| g.to_ascii_lowercase().trim_matches(['{', '}']).to_string()).collect();
    let cached: Vec<Value> = found.iter().map(|p| {
        let ps = p.to_string_lossy().to_string();
        let matches = guids.iter().any(|g| ps.to_ascii_lowercase().contains(g.as_str()));
        let modified = std::fs::metadata(p).and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs());
        json!({"path": ps, "matchesPreference": matches, "modifiedUnix": modified})
    }).collect();
    let best: Vec<&Value> = cached.iter().filter(|c| c["matchesPreference"] == true).collect();
    let mut r = json!({"success": prefs["success"] == true, "edition": prefs["edition"], "templateFiles": files,
        "entries": entries.iter().map(|e| json!({"kind": e.0, "value": e.1, "itemGuid": e.2})).collect::<Vec<_>>(),
        "cachedLibraries": cached, "localTemplatePath": local, "localLibraries": local_libs});
    if best.len() == 1 { r["template"] = json!({"libraryPath": best[0]["path"]}); }
    r["_hint"] = json!(if pcb.is_empty() {
        "Altium's Template Files names no PCB library template here: give the template yourself (altium_layer_map {action:'from_template', libraryPath, footprint})."
    } else if best.len() == 1 {
        "The cached copy of your PCB library template is template.libraryPath: altium_list_library lists its footprints, then altium_layer_map {action:'from_template', libraryPath, footprint, save:'library'}."
    } else {
        "Your Template Files names a PCB library template, but its cached copy was not told apart from the others (cachedLibraries): open it in Altium once so it is cached, or pick the right path, then altium_layer_map {action:'from_template'}."
    });
    r
}

pub fn layer_map(args: &Value) -> Value {
    match s(args, "action").as_deref().unwrap_or("get") {
        "get" => get(args),
        "set" => set(args),
        "clear" => clear(args),
        "from_template" => from_template(args),
        "find_template" => find_template(args),
        a => json!({"success": false, "errorCode": "bad_args", "error": format!("unknown action {a}: get, set, clear, from_template or find_template")}),
    }
}

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

    #[test]
    fn a_relative_template_is_read_beside_the_file_that_names_it() {
        assert_eq!(absolute("C:/org/T.PcbLib", Some(Path::new("D:/lib/adom-layer-map.json"))), "C:/org/T.PcbLib");
        let a = absolute("Templates/T.PcbLib", Some(Path::new("/lib/adom-layer-map.json")));
        assert!(a.ends_with("Templates/T.PcbLib") && a.starts_with("/lib"), "{a}");
    }

    #[test]
    fn the_call_map_comes_from_layer_map_and_template() {
        assert!(call_doc(&json!({"libraryPath": "x"})).is_none());
        let d = call_doc(&json!({"layerMap": {"fab": "AssemblyTop"}, "template": {"libraryPath": "T.PcbLib", "footprint": "F"}})).unwrap();
        assert_eq!(d["layerMap"]["fab"], "AssemblyTop");
        assert_eq!(d["template"]["footprint"], "F");
    }
}

#[cfg(test)]
mod layer_count_tests {
    use super::*;

    #[test]
    fn a_library_with_every_mechanical_layer_reads_as_bloated() {
        let mut s = String::from("|LAYER_V8_0NAME=Top Paste|LAYER_V8_0LAYERID=35|");
        for i in 1..=1024 { s.push_str(&format!("|LAYER_V8_{}NAME=Mechanical {i}|LAYER_V8_{}MECHENABLED={}|", 10 + i, 10 + i, if i < 3 { "TRUE" } else { "FALSE" })); }
        let r = library_layers(s.as_bytes());
        assert_eq!((r["layerRecords"].as_u64(), r["mechanicalLayers"].as_u64(), r["mechanicalLayersOn"].as_u64(), r["bloated"].as_bool()), (Some(1025), Some(1024), Some(2), Some(true)));
        let small = library_layers(b"|LAYER_V8_11NAME=Mechanical 1|LAYER_V8_11MECHENABLED=TRUE|LAYER_V8_12MECHENABLED=FALSE|");
        assert_eq!(small["bloated"], json!(false));
    }
}