main
Colby Knox 0.2.89: import_design reads EAGLE through Altium's Import Wizard, driven by page name; tool_update reads the offer from… 721883c
//! tool_update: Altium's own updates (EDA Bridge Standard #29, app tier).
//! - `check`: every Altium on the machine with its exact build (X2.EXE), against the newest release on Altium's public
//!   downloads page. Altium's Extensions & Updates page is not in UI Automation and the "Update Available" box at
//!   start-up names no version (measured 2026-10-30), so the page is where the version comes from; the box, which the
//!   reaper closes, is reported as `noticeSeen`.
//! - `apply`: refuses with the unsaved documents. Altium's installer is Altium's own and asks for a Windows approval,
//!   so with work safe the bridge starts it only when a person is there to approve (humanIsPresent) and answers
//!   `needs_user` with what to approve.
//! - `auto`: Altium's update check is its UpdatesCheckFrequency preference (HKCU, ExtensionManager\AutoUpdatePrefs). It
//!   reads any time; it is set only with Altium closed, because Altium writes its preferences back when it exits.
use serde_json::{json, Value};

const DOWNLOADS: &str = "https://www.altium.com/products/downloads";
/// Altium's "Never" in Preferences > System > Installation > Check frequency. The value `on: true` gives is its default.
const NEVER: i64 = 0;
const DEFAULT_FREQUENCY: i64 = 2;

/// X2.EXE's product version.
fn exe_version(exe: &str) -> Option<String> {
    let ps = format!("(Get-Item -LiteralPath '{}').VersionInfo.ProductVersion", exe.replace('\'', "''"));
    let o = std::process::Command::new("powershell").args(["-NoProfile", "-Command", &ps]).output().ok()?;
    let v = String::from_utf8_lossy(&o.stdout).trim().to_string();
    (!v.is_empty()).then_some(v)
}

/// A version's numbers. Pure.
fn numbers(v: &str) -> Vec<u32> { v.split('.').filter_map(|x| x.trim().parse().ok()).collect() }

/// The newest `version="a.b.c"` on Altium's downloads page. Pure.
pub fn newest_on_page(html: &str) -> Option<String> {
    html.split("version=\"").skip(1).filter_map(|t| t.split('"').next())
        .filter(|v| v.split('.').count() == 3 && !numbers(v).is_empty() && numbers(v).len() == 3)
        .max_by_key(|v| numbers(v)).map(str::to_string)
}

/// Is `latest` (a release, a.b.c) newer than `installed` (a build, a.b.c.d)? Pure.
pub fn is_newer(latest: &str, installed: &str) -> bool {
    let (l, i) = (numbers(latest), numbers(installed));
    l.iter().take(3).cmp(i.iter().take(3)) == std::cmp::Ordering::Greater
}

fn fetch_newest() -> Result<String, String> {
    let body = ureq::get(DOWNLOADS).timeout(std::time::Duration::from_secs(30)).call().map_err(|e| e.to_string())?.into_string().map_err(|e| e.to_string())?;
    newest_on_page(&body).ok_or_else(|| "the downloads page lists no version any more".to_string())
}

/// The open documents with unsaved changes.
fn unsaved() -> Vec<String> {
    let d = crate::project::document_info(&json!({}));
    d["openDocuments"].as_array().cloned().unwrap_or_default().iter()
        .filter(|x| x["modified"] == json!(true)).filter_map(|x| x["path"].as_str().or(x["name"].as_str()).map(str::to_string)).collect()
}

/// HKCU preference keys of each Altium: (key under HKCU, edition).
fn pref_keys() -> Vec<(String, String)> {
    let ps = "Get-ChildItem 'HKCU:\\Software\\Altium' -ErrorAction SilentlyContinue | ForEach-Object { $_.PSChildName }";
    let Ok(o) = std::process::Command::new("powershell").args(["-NoProfile", "-Command", ps]).output() else { return vec![] };
    String::from_utf8_lossy(&o.stdout).lines().map(str::trim).filter(|l| l.starts_with("Altium Designer") && !l.ends_with("_Security"))
        .map(|l| (format!("HKCU:\\Software\\Altium\\{l}\\DesignExplorer\\Preferences\\ExtensionManager\\AutoUpdatePrefs"),
            if l.contains("Develop") { "Altium Designer Develop".to_string() } else { "Altium Designer".to_string() })).collect()
}

fn read_frequency(key: &str) -> Option<i64> {
    let ps = format!("(Get-ItemProperty -LiteralPath '{key}' -Name UpdatesCheckFrequency -ErrorAction Stop).UpdatesCheckFrequency");
    let o = std::process::Command::new("powershell").args(["-NoProfile", "-Command", &ps]).output().ok()?;
    String::from_utf8_lossy(&o.stdout).trim().parse().ok()
}

fn write_frequency(key: &str, v: i64) -> bool {
    let ps = format!("Set-ItemProperty -LiteralPath '{key}' -Name UpdatesCheckFrequency -Value '{v}' -ErrorAction Stop");
    std::process::Command::new("powershell").args(["-NoProfile", "-Command", &ps]).status().map(|s| s.success()).unwrap_or(false)
}

/// altium_tool_update {action: check | apply | auto, on?, humanIsPresent?}
pub fn tool_update(args: &Value) -> Value {
    let action = crate::support::s(args, "action").unwrap_or_else(|| "check".into()).to_ascii_lowercase();
    let installs: Vec<Value> = crate::support::detect_installs().into_iter().map(|mut i| {
        let v = i["exe"].as_str().and_then(exe_version);
        let folder = i["base_dir"].as_str().unwrap_or("").rsplit(['\\', '/']).next().unwrap_or("").to_string();
        i["edition"] = json!(if folder.to_ascii_lowercase().contains("develop") { "Altium Designer Develop" } else { "Altium Designer" });
        if i["major"] == json!("0") { if let Some(m) = v.as_deref().and_then(|v| v.split('.').next()) { i["major"] = json!(m); } }
        i["version"] = json!(v);
        i
    }).collect();
    if installs.is_empty() { return crate::support::not_installed(); }
    let running = crate::health::is_running();
    let first = installs[0]["version"].as_str().unwrap_or("").to_string();
    match action.as_str() {
        "check" => {
            let notice = crate::dialogs::reaped_log(500).iter().any(|r| r.to_string().contains("update_notice"));
            match fetch_newest() {
                Ok(newest) => {
                    let installs: Vec<Value> = installs.into_iter().map(|mut i| { let o = i["version"].as_str().map(|v| is_newer(&newest, v)).unwrap_or(false); i["offered"] = if o { json!(newest) } else { Value::Null }; i }).collect();
                    // an update is offered when any Altium here is behind; current is then that one's build
                    let behind = installs.iter().find(|i| !i["offered"].is_null());
                    let offered = if behind.is_some() { json!(newest) } else { Value::Null };
                    let current = behind.and_then(|i| i["version"].as_str()).unwrap_or(&first).to_string();
                    json!({"success": true, "current": current, "offered": offered, "newest": newest, "offeredFrom": DOWNLOADS, "installs": installs, "running": running, "checked": true, "noticeSeen": notice,
                        "_hint": "installs gives each Altium here with its exact build and the release it could move to. newest is the newest release on Altium's own downloads page. noticeSeen says Altium raised its Update Available box since the bridge started (it names no version; the bridge closes it)."})
                }
                Err(e) => json!({"success": true, "current": first, "offered": Value::Null, "installs": installs, "running": running, "checked": false, "noticeSeen": notice, "why": format!("Altium's downloads page could not be read: {e}"),
                    "_hint": "installs is exact. Whether a newer release is offered is unknown: the page did not answer."}),
            }
        }
        "apply" => {
            let open = if running { unsaved() } else { vec![] };
            if !open.is_empty() {
                return json!({"success": false, "errorCode": "unsaved_work", "unsaved": open, "applied": false, "error": format!("{} open document(s) have unsaved changes: save them first", open.len()), "_hint": "apply never closes unsaved work. altium_save keeps them; call again after."});
            }
            let newest = match fetch_newest() { Ok(n) => n, Err(e) => return json!({"success": false, "errorCode": "check_failed", "applied": false, "current": first, "error": format!("Altium's downloads page could not be read: {e}")}) };
            let Some(target) = installs.iter().find(|i| i["version"].as_str().map(|v| is_newer(&newest, v)).unwrap_or(false)) else {
                return json!({"success": true, "applied": false, "current": first, "offered": Value::Null, "newest": newest, "needsRestart": false, "_hint": "Every Altium here is on the newest release: nothing to apply."});
            };
            let edition = target["edition"].clone();
            let what = format!("Windows asks for an administrator's approval for Altium's installer, then it updates {} to {newest}. Altium has to be closed for it.", edition.as_str().unwrap_or("Altium"));
            let base = json!({"success": false, "errorCode": "needs_user", "applied": false, "needsRestart": true, "current": target["version"], "offered": newest, "edition": edition, "whatToApprove": what});
            if args.get("humanIsPresent").and_then(|v| v.as_bool()) != Some(true) {
                let mut out = base;
                out["error"] = json!("the update needs a person at the Windows approval prompt, which refuses itself after about two minutes with nobody there");
                out["_hint"] = json!("Tell the user what will change, then call again with humanIsPresent:true when they are at the machine: the bridge closes Altium (nothing unsaved) and starts Altium's own installer. Or they update from Altium: Help > Check for Updates.");
                return out;
            }
            if running {
                let c = crate::verbs::dispatch("close", &json!({}), &[]);
                if c.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "close_failed", "applied": false, "error": "Altium did not close, so its installer was not started", "close": c}); }
            }
            let inst = std::path::Path::new(target["base_dir"].as_str().unwrap_or("")).join("System").join("Installation").join("AltiumInstaller.exe");
            let started = std::process::Command::new(&inst).arg("-Update").spawn();
            let mut out = base;
            match started {
                Ok(_) => { out["started"] = json!(inst); out["_hint"] = json!("Altium's installer is running: the person approves the Windows prompt and follows its pages. Check afterwards with action:check; altium_launch starts Altium again."); }
                Err(e) => { out["started"] = Value::Null; out["error"] = json!(format!("Altium's installer did not start: {e}")); out["errorCode"] = json!("installer_failed"); }
            }
            out
        }
        "auto" => {
            // only the keys that hold the setting: an old install's key may have none
            let keys: Vec<(String, String)> = pref_keys().into_iter().filter(|(k, _)| read_frequency(k).is_some()).collect();
            let read: Vec<Value> = keys.iter().map(|(k, e)| { let f = read_frequency(k); json!({"edition": e, "checkFrequency": f, "auto": f.map(|v| v != NEVER)}) }).collect();
            let want = args.get("on").or(args.get("enabled")).and_then(|v| v.as_bool());
            if let Some(on) = want {
                if running {
                    return json!({"success": false, "errorCode": "altium_running", "auto": read.first().map(|r| r["auto"].clone()), "settings": read,
                        "error": "Altium writes its preferences back when it exits, so its update check is set with Altium closed", "_hint": "altium_close, then call again."});
                }
                let value = if on { DEFAULT_FREQUENCY } else { NEVER };
                let done = keys.iter().filter(|(k, _)| read_frequency(k).map(|f| (f != NEVER) != on).unwrap_or(false)).all(|(k, _)| write_frequency(k, value));
                let back: Vec<Value> = keys.iter().map(|(k, e)| { let f = read_frequency(k); json!({"edition": e, "checkFrequency": f, "auto": f.map(|v| v != NEVER)}) }).collect();
                let all = back.iter().all(|b| b["auto"] == json!(on));
                return json!({"success": done && all && !back.is_empty(), "mutated": true, "auto": on, "settings": back, "needsRestart": false, "_hint": "Altium's check frequency, read back. Altium reads it when it starts."});
            }
            let auto = read.iter().find_map(|r| r["auto"].as_bool());
            json!({"success": true, "auto": auto, "settings": read, "_hint": "Altium's own update check for each edition: checkFrequency is its Preferences > System > Installation setting, 0 is never. auto with on sets it, Altium closed."})
        }
        o => json!({"success": false, "errorCode": "bad_args", "error": format!("action is check, apply or auto (got {o})")}),
    }
}

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

    #[test]
    fn the_newest_release_on_the_page() {
        let html = r#"<a version="26.9.1" x><a version="26.11.1"><a version="26.10.1"><meta version="1.0"><a version="9.9.9.9">"#;
        assert_eq!(newest_on_page(html).as_deref(), Some("26.11.1"), "numbers, not text: 26.11 beats 26.9");
        assert_eq!(newest_on_page("<html/>"), None);
    }

    #[test]
    fn a_release_is_newer_by_its_three_numbers() {
        assert!(is_newer("26.11.1", "26.9.1.9"));
        assert!(!is_newer("26.11.1", "26.11.1.5"), "the same release at any build");
        assert!(!is_newer("26.9.1", "26.11.1.5"));
    }
}