main
Colby Knox 0.2.90 (source, not released; final shapes not run in Altium yet): the eleven verbs of standard 0.30.14 in the standard… 78b01ce
//! import_design: a foreign design into a new native Altium project (EDA Bridge Standard #29, native). `kicad` goes
//! through Altium's KiCad importer (import_kicad); `eagle` through Altium's Import Wizard, driven outside the script
//! engine through UI Automation and, where Altium's Delphi controls answer nothing else, a real click or key. Every
//! step is in `steps`. Other formats Altium's wizard reads are refused by name until the bridge drives them.
//!
//! EAGLE, as mapped on Altium Designer Develop 26.9 (2026-10-30):
//! - ImporterManager:RunImporterManagerDialog opens "Import Wizard" (TImporterManagerForm); the dialog scan does not
//!   list it, so it is found by title. Back / Next / Finish / Cancel take UIA Invoke.
//! - Its importer grid needs a mouse click on "EAGLE Projects and Designs": UIA Select does not reach the Delphi grid,
//!   and Next would import the first row, 99SE DDB (which asks to close every document).
//! - Next hands over to "EAGLE Import Wizard" (TImporterWizardForm): design files (Add / Remove), library files,
//!   "Analyzing Files" (all its buttons greyed; a Next pressed then is lost), Sheet_PCBMapping, Sheet_Report,
//!   Sheet_IntLib (the output folder, DirEdit_IntLib; the project goes in "Imported <name>.PrjPcb" under it),
//!   Sheet_Output (the import runs), Sheet_Finish. UIA reports no button as disabled and a greyed Finish still takes
//!   Invoke and closes the wizard with nothing imported, so the page's name decides what is pressed.
//! - Add opens "Load EAGLE Designs", an old-style Open dialog: its file name box (id 1148) takes SetValue, and only
//!   Enter takes it.
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime};

/// The EAGLE files of a design: the .sch and .brd beside the one named (either may be). Pure apart from the file check.
pub fn eagle_files(path: &str) -> Vec<PathBuf> {
    let p = PathBuf::from(path.replace('\\', "/"));
    let mut out: Vec<PathBuf> = ["sch", "brd"].iter().map(|e| p.with_extension(e)).filter(|f| f.is_file()).collect();
    if out.is_empty() && p.is_file() { out.push(p); }
    out
}

fn ab(verb: &str, args: Value) -> Value { crate::ab::call(verb, args, &[], 20) }
fn ok(r: &Value) -> bool { r.get("success").and_then(|b| b.as_bool()) != Some(false) && r.get("status").and_then(|s| s.as_str()) != Some("error") }

/// A top-level window by title, within `secs`.
fn window(title: &str, secs: u64) -> Option<i64> {
    let t0 = Instant::now();
    while t0.elapsed().as_secs() < secs {
        let r = ab("desktop_find_window", json!({"titleContains": title}));
        if let Some(h) = r["windows"].as_array().and_then(|a| a.iter().find(|w| w["title"].as_str() == Some(title))).and_then(|w| w["hwnd"].as_i64()) { return Some(h); }
        std::thread::sleep(Duration::from_millis(500));
    }
    None
}

/// The UIA tree of a window, flattened: (role, name, automationId, rect centre, node).
fn nodes(h: i64) -> Vec<Value> {
    let r = ab("desktop_ui_tree", json!({"hwnd": h, "maxDepth": 30, "maxNodes": 2000}));
    let mut out = Vec::new();
    fn walk(n: &Value, out: &mut Vec<Value>) { out.push(n.clone()); for c in n["children"].as_array().cloned().unwrap_or_default() { walk(&c, out); } }
    walk(&r["root"], &mut out);
    out
}

fn click(h: i64, name: &str) -> bool { ok(&ab("desktop_ui_click", json!({"hwnd": h, "name": name, "role": "button"}))) }

/// Add one file through the wizard's Load dialog.
fn add_file(wiz: i64, f: &Path, steps: &mut Vec<Value>) -> bool {
    if !click(wiz, "Add") { steps.push(json!({"step": "add", "file": f, "ok": false, "why": "no Add button"})); return false; }
    let Some(load) = window("Load EAGLE Designs", 15) else { steps.push(json!({"step": "add", "file": f, "ok": false, "why": "no Load EAGLE Designs dialog"})); return false; };
    let want = f.to_string_lossy().replace('/', "\\");
    let norm = |v: &str| v.replace('\\', "/").to_ascii_lowercase();
    let mut set = false;
    for _ in 0..5 {
        // the dialog takes a moment to accept a value after it opens
        std::thread::sleep(Duration::from_millis(600));
        ab("desktop_ui_set", json!({"hwnd": load, "name": "File name:", "role": "edit", "text": want}));
        let back = ab("desktop_find_controls", json!({"hwnd": load, "automationId": "1148"}));
        if back["matches"].as_array().map(|a| a.iter().any(|m| m["value"].as_str().map(norm) == Some(norm(&want)))).unwrap_or(false) { set = true; break; }
    }
    if !set { ab("desktop_ui_click", json!({"hwnd": load, "name": "Cancel", "role": "button"})); steps.push(json!({"step": "add", "file": f, "ok": false, "why": "the file name would not take"})); return false; }
    ab("desktop_press_key", json!({"keys": ["enter"], "hwnd": load, "reason": "open the EAGLE file in Altium's import wizard"}));
    let t0 = Instant::now();
    while window("Load EAGLE Designs", 1).is_some() && t0.elapsed().as_secs() < 10 { std::thread::sleep(Duration::from_millis(400)); }
    steps.push(json!({"step": "add", "file": f, "ok": true}));
    true
}

/// The newest .PrjPcb under `dir` (two levels down) written since `since`.
fn new_project(dir: &Path, since: SystemTime) -> Option<PathBuf> {
    let mut best: Option<(SystemTime, PathBuf)> = None;
    let mut walk = vec![(dir.to_path_buf(), 0)];
    while let Some((d, depth)) = walk.pop() {
        for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
            let p = e.path();
            if p.is_dir() { if depth < 2 { walk.push((p, depth + 1)); } continue; }
            if !p.extension().map(|x| x.eq_ignore_ascii_case("PrjPcb")).unwrap_or(false) { continue; }
            if let Some(m) = e.metadata().and_then(|m| m.modified()).ok().filter(|m| *m >= since) {
                if best.as_ref().map(|b| m > b.0).unwrap_or(true) { best = Some((m, p)); }
            }
        }
    }
    best.map(|b| b.1)
}

/// Close whatever wizard windows are left.
fn cancel_all() {
    for t in ["Load EAGLE Designs", "EAGLE Import Wizard", "Import Wizard"] {
        if let Some(h) = window(t, 1) { if !click(h, "Cancel") { ab("desktop_press_key", json!({"keys": ["escape"], "hwnd": h, "reason": "close the import wizard"})); } }
    }
}

/// The page a wizard shows: the id of its Sheet_ node, or the empty string on a page without one.
fn page_of(tree: &[Value]) -> String {
    tree.iter().filter_map(|n| n["automationId"].as_str()).find(|a| a.starts_with("Sheet_")).unwrap_or("").to_string()
}

#[derive(Debug, PartialEq)]
pub enum Move { Finish, Next, Wait }

/// What to press on a page: Finish only on the last one, nothing while the import runs, and Next once per page, again
/// only when the page has not moved for a while (a Next pressed while it was analysing is lost). Pure.
pub fn move_for(page: &str, pressed_on: Option<&str>, waited: Duration) -> Move {
    match page {
        "Sheet_Finish" => Move::Finish,
        "Sheet_Output" => Move::Wait,
        p if pressed_on != Some(p) || waited >= Duration::from_secs(6) => Move::Next,
        _ => Move::Wait,
    }
}

/// Walk the EAGLE wizard's pages to its end, keeping Altium's own import options.
fn drive_pages(eagle: i64, out_dir: Option<&Path>, steps: &mut Vec<Value>) -> Result<(), String> {
    let t0 = Instant::now();
    let (mut pressed_on, mut pressed_at, mut shown, mut dir_set) = (None::<String>, Instant::now(), String::new(), out_dir.is_none());
    while t0.elapsed().as_secs() < 600 {
        // once the import itself runs it goes to its end; until then a cancel closes the wizard with nothing imported
        if crate::runs::cancelled() && shown != "Sheet_Output" && shown != "Sheet_Finish" { return Err("cancelled by cancel_run".into()); }
        let tree = nodes(eagle);
        if tree.len() <= 1 && window("EAGLE Import Wizard", 1).is_none() { return Err(format!("the EAGLE Import Wizard closed on {shown} before the import finished")); }
        let page = page_of(&tree);
        if page != shown { steps.push(json!({"step": "page", "page": page, "atSec": t0.elapsed().as_secs()})); crate::runs::stage(&format!("wizard page {page}")); shown = page.clone(); }
        if page == "Sheet_IntLib" && !dir_set {
            let want = out_dir.map(|d| d.to_string_lossy().replace('/', "\\")).unwrap_or_default();
            let _ = std::fs::create_dir_all(&want);
            ab("desktop_ui_set", json!({"hwnd": eagle, "automationId": "DirEdit_IntLib", "text": want}));
            let back = ab("desktop_find_controls", json!({"hwnd": eagle, "automationId": "DirEdit_IntLib"}));
            let norm = |v: &str| v.replace('\\', "/").trim_end_matches('/').to_ascii_lowercase();
            if !back["matches"].as_array().map(|a| a.iter().any(|m| m["value"].as_str().map(norm) == Some(norm(&want)))).unwrap_or(false) {
                return Err(format!("the wizard's output folder would not take {want}"));
            }
            steps.push(json!({"step": "output_dir", "dir": want}));
            dir_set = true;
        }
        match move_for(&page, pressed_on.as_deref(), pressed_at.elapsed()) {
            Move::Finish => {
                click(eagle, "Finish");
                let t1 = Instant::now();
                while window("EAGLE Import Wizard", 1).is_some() {
                    if t1.elapsed().as_secs() > 30 { return Err("the EAGLE Import Wizard stayed open after Finish".into()); }
                    std::thread::sleep(Duration::from_millis(500));
                }
                steps.push(json!({"step": "finish", "atSec": t0.elapsed().as_secs()}));
                return Ok(());
            }
            Move::Next => { click(eagle, "Next"); pressed_on = Some(page); pressed_at = Instant::now(); }
            Move::Wait => {}
        }
        std::thread::sleep(Duration::from_millis(700));
    }
    Err(format!("the EAGLE Import Wizard was still on {shown} after 10 minutes"))
}

/// The EAGLE import, the agent stopped while it runs.
fn run_eagle(files: &[PathBuf], out_dir: Option<&Path>, steps: &mut Vec<Value>) -> Result<(), String> {
    let exe = crate::lifecycle::x2_exe_pub().ok_or("X2.exe not found")?;
    let mut child = crate::lifecycle::spawn_helper_pub(&exe, "-RImporterManager:RunImporterManagerDialog")?;
    // a freshly started Altium takes a while to show it
    let Some(wiz) = window("Import Wizard", 60) else { crate::lifecycle::wait_helper_pub(&mut child, Duration::from_secs(10)); return Err("Altium's Import Wizard did not open".into()); };
    click(wiz, "Next");
    // the EAGLE row, clicked: the grid answers no UIA pattern
    let t0 = Instant::now();
    let row = loop {
        let row = nodes(wiz).into_iter().find(|n| n["name"].as_str() == Some("EAGLE Projects and Designs"));
        if row.is_some() || t0.elapsed().as_secs() > 15 { break row; }
        std::thread::sleep(Duration::from_millis(500));
    };
    let Some(r) = row.and_then(|n| n["rect"].as_object().cloned()) else { cancel_all(); return Err("no EAGLE row in the Import Wizard's list".into()); };
    let c = ab("desktop_click", json!({"x": r["centerX"], "y": r["centerY"], "hwnd": wiz, "reason": "choose EAGLE in Altium's Import Wizard (its list answers no UI Automation)"}));
    steps.push(json!({"step": "choose_eagle", "ok": ok(&c)}));
    click(wiz, "Next");
    let Some(eagle) = window("EAGLE Import Wizard", 20) else { cancel_all(); return Err("the EAGLE Import Wizard did not open (the importer chosen was not EAGLE)".into()); };
    for f in files { if !add_file(eagle, f, steps) { cancel_all(); return Err(format!("{} could not be added", f.display())); } }
    drive_pages(eagle, out_dir, steps).inspect_err(|_| cancel_all())?;
    // the launcher returns once the wizard has closed
    crate::lifecycle::wait_helper_pub(&mut child, Duration::from_secs(600));
    Ok(())
}

/// What the EAGLE board holds, to check the import against: elements, signals and vias. Pure.
pub fn eagle_board_counts(brd: &str) -> Value {
    let n = |t: &str| brd.matches(t).count();
    let signals = brd.split("<signals>").nth(1).and_then(|x| x.split("</signals>").next()).unwrap_or("");
    json!({"components": n("<element "), "nets": signals.matches("<signal ").count(), "vias": signals.matches("<via ").count()})
}

/// After the wizard: keep the board (the wizard leaves it modified) and read it against the EAGLE source.
fn check_board(prj: &Path, files: &[PathBuf]) -> Value {
    let board = prj.with_extension("PcbDoc");
    if !board.is_file() { return json!({"board": Value::Null}); }
    let b = board.to_string_lossy().to_string();
    let saved = crate::surfaces::save(&json!({"filePath": b}));
    let r = crate::verbs::dispatch("routing_state", &json!({"filePath": b}), &[]);
    let got = &r["counts"];
    let source = files.iter().find(|f| f.extension().map(|x| x.eq_ignore_ascii_case("brd")).unwrap_or(false))
        .and_then(|f| std::fs::read_to_string(f).ok()).map(|t| eagle_board_counts(&t));
    let matches = source.as_ref().map(|s| ["components", "nets", "vias"].iter().all(|k| s[*k] == got[*k]));
    json!({"board": b, "saved": saved.get("success"), "imported": got, "source": source, "matchesSource": matches, "unconnected": r["unconnected"]})
}

/// What the importer could not bring over: its log's ERROR lines, each kind once with its count. Pure.
pub fn log_warnings(log: &str) -> Vec<String> {
    let mut seen: Vec<(String, usize)> = Vec::new();
    for l in log.lines().map(str::trim).filter_map(|l| l.strip_prefix("ERROR:")) {
        let k = l.trim().to_string();
        match seen.iter_mut().find(|(s, _)| *s == k) { Some(e) => e.1 += 1, None => seen.push((k, 1)) }
    }
    seen.into_iter().map(|(k, n)| if n > 1 { format!("{k} ({n} times)") } else { k }).collect()
}

/// altium_import_design {format, filePath, boardPath?, name?, outputDir?}
pub fn import_design(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let s = |k: &str| crate::support::s(args, k);
    let format = s("format").unwrap_or_default().to_ascii_lowercase();
    let Some(path) = s("filePath") else { return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the design to import) is required"}) };
    match format.as_str() {
        "kicad" => { let mut r = crate::outputs::import_kicad(args); r["format"] = json!("kicad"); if r.get("project").is_some() { r["design"] = r["project"].clone(); } r }
        "eagle" => {
            let mut files = eagle_files(&path);
            // a board with another name than its schematic
            if let Some(b) = s("boardPath").map(|b| PathBuf::from(b.replace('\\', "/"))) {
                if !b.is_file() { return json!({"success": false, "errorCode": "file_not_found", "error": format!("no EAGLE board at {}", b.display())}); }
                files.retain(|f| !f.extension().map(|x| x.eq_ignore_ascii_case("brd")).unwrap_or(false));
                files.push(b);
            }
            if files.is_empty() { return json!({"success": false, "errorCode": "file_not_found", "error": format!("no EAGLE .sch or .brd at {path}")}); }
            let out_dir = s("outputDir").map(PathBuf::from);
            let dir = out_dir.clone().unwrap_or_else(|| files[0].parent().map(Path::to_path_buf).unwrap_or_default());
            if let Err(e) = crate::ab::need_input_approval("answer Altium's Import Wizard for the EAGLE import (its list, file dialog and buttons)", 90) { return e; }
            let since = SystemTime::now();
            let stop = crate::lifecycle::stop();
            if stop.get("success").and_then(|v| v.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "agent_stop_failed", "stop": stop}); }
            let mut steps = Vec::new();
            let _run = crate::runs::begin("import_design");
            let run = run_eagle(&files, out_dir.as_deref(), &mut steps);
            let start = crate::lifecycle::start(Duration::from_secs(90));
            let prj = new_project(&dir, since);
            match (run, prj) {
                (Ok(()), Some(p)) => {
                    let check = check_board(&p, &files);
                    let log = std::fs::read(p.with_extension("LOG")).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();
                    // project_rename refuses an open project, and the wizard leaves this one open
                    let renamed = s("name").map(|n| {
                        for ext in ["PcbDoc", "SchDoc", "PrjPcb"] { crate::agent::call("close_document", &[("path", p.with_extension(ext).to_string_lossy().to_string())], None, Duration::from_secs(30)); }
                        crate::project::project_rename(&json!({"project": p, "newName": n}))
                    });
                    let design = match (&renamed, s("name")) {
                        (Some(r), Some(n)) if r.get("success").and_then(|b| b.as_bool()) != Some(false) => p.with_file_name(format!("{n}.PrjPcb")).to_string_lossy().to_string(),
                        _ => p.to_string_lossy().to_string(),
                    };
                    json!({"success": true, "format": "eagle", "files": files, "design": design, "project": design, "parts": check["imported"]["components"], "nets": check["imported"]["nets"],
                        "warnings": log_warnings(&log), "renamed": renamed, "steps": steps, "agentRestarted": start.get("success"), "check": check,
                        "_hint": "Altium's Import Wizard made a new project from the EAGLE schematic and board with its own import options, and left it open. check compares the board with the EAGLE file. Compile it (altium_compile) before trusting the schematic: the wizard writes EAGLE's nets as ports, which ERC can report as multiple input ports. warnings is what the importer's log says it could not read. A second import of the same design goes in a new folder, Imported (1) <name>.PrjPcb: the first is left alone."})
                }
                (Ok(()), None) => json!({"success": false, "errorCode": "no_project", "error": format!("the wizard finished but no new .PrjPcb appeared under {}", dir.display()), "steps": steps, "agentRestarted": start.get("success")}),
                (Err(e), _) => json!({"success": false, "errorCode": "wizard_failed", "error": e, "steps": steps, "agentRestarted": start.get("success")}),
            }
        }
        "" => json!({"success": false, "errorCode": "bad_args", "error": "format is required: eagle or kicad"}),
        o => json!({"success": false, "errorCode": "unsupported", "format": o, "formats": ["eagle", "kicad"],
            "error": format!("this bridge does not drive Altium's {o} importer yet"),
            "_hint": "Altium's Import Wizard also reads PADS, OrCAD, P-CAD, Allegro, xDxDesigner, CADSTAR and Zuken designs: a person can run it from File > Import Wizard."}),
    }
}

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

    #[test]
    fn an_eagle_design_is_its_sch_and_brd() {
        let d = std::env::temp_dir().join(format!("adom-eagle-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        std::fs::write(d.join("x.sch"), "<eagle/>").unwrap();
        std::fs::write(d.join("x.brd"), "<eagle/>").unwrap();
        let f = eagle_files(&d.join("x.brd").to_string_lossy());
        assert_eq!(f.len(), 2, "{f:?}");
        assert!(f[0].ends_with("x.sch"));
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn the_log_says_what_did_not_come_over() {
        let w = log_warnings("Load board\n    ERROR: Unhandled typepackages3d\n  ERROR: Unhandled typepackages3d\n    ERROR: Unhandled type <x>\nEndSection");
        assert_eq!(w, ["Unhandled typepackages3d (2 times)", "Unhandled type <x>"]);
    }

    #[test]
    fn a_page_decides_the_press() {
        let s = Duration::from_secs(1);
        assert_eq!(move_for("Sheet_Finish", None, s), Move::Finish);
        assert_eq!(move_for("Sheet_Output", None, s), Move::Wait, "the import is running");
        assert_eq!(move_for("Sheet_Report", Some("Sheet_PCBMapping"), s), Move::Next);
        assert_eq!(move_for("Sheet_Report", Some("Sheet_Report"), s), Move::Wait, "pressed already");
        assert_eq!(move_for("Sheet_Report", Some("Sheet_Report"), Duration::from_secs(7)), Move::Next, "the press was lost");
        assert_eq!(move_for("", None, s), Move::Next, "a page with no sheet name still moves");
    }

    #[test]
    fn the_page_is_the_sheet_node() {
        assert_eq!(page_of(&[json!({"automationId": "Button_Next"}), json!({"automationId": "Sheet_IntLib"})]), "Sheet_IntLib");
        assert_eq!(page_of(&[json!({"name": "x"})]), "");
    }

    #[test]
    fn a_board_counts_its_own_signals_only() {
        let c = eagle_board_counts(r#"<board><elements><element name="R1"/><element name="R2"/></elements><signals><signal name="A"><via x="1"/></signal><signal name="B"/></signals><via x="9"/></board>"#);
        assert_eq!(c, json!({"components": 2, "nets": 2, "vias": 1}));
    }
}