master
Colby Knox v2.1.11: A part request is answered in the thread that asked, not by email (the wiki thread's handoff; John's report th… 6752e69
//! When a part request is due, and what to do once it is late.
//!
//! The wiki answers with its own clock from 2026-12-04 on (`deadline_at`, `deadline_passed`), so the CLI, AI Flow and
//! Parts Search agree on one time. Older wikis do not, so the time is then worked out here as PR #6 did: Component
//! Ocean's next retry, or a stated service limit from the time the part was requested.

/// Service limits quoted when Component Ocean gives no retry time (component-factory#3: 20 minutes for an urgent part,
/// an hour for one in review); a `later` request is due within a day.
const LIMIT_NOW_SECS: i64 = 20 * 60;
const LIMIT_REVIEW_SECS: i64 = 60 * 60;
const LIMIT_LATER_SECS: i64 = 24 * 60 * 60;
const SKILL_BUILD_PAGE: &str = "build-a-component-page skill (https://wiki.adom.inc/adom/build-a-component-page)";

#[derive(Debug)]
pub struct Deadline { pub at: i64, pub source: String, pub passed: bool, pub eta_text: Option<String> }

impl Deadline {
    pub fn line(&self) -> String {
        if self.passed { format!("LATE: was due {} ({})", fmt_utc(self.at), self.source) }
        else { format!("due by {} ({})", fmt_utc(self.at), self.source) }
    }
}

/// When the request is due. Component Ocean's `not_before` (its next retry) plus `eta_seconds` when CO gives one,
/// otherwise `requested_at` plus the service limit. None once the request is built or finished.
pub fn deadline(req: &serde_json::Value, now: i64) -> Option<Deadline> {
    let state = req.get("state").and_then(|v| v.as_str()).unwrap_or("");
    if matches!(state, "built" | "done" | "published" | "public" | "cancelled" | "canceled" | "") { return None; }
    let eta = req.get("eta_seconds").and_then(|v| v.as_i64()).unwrap_or(0).max(0);
    let (at, source) = if let Some(nb) = req.get("not_before").and_then(epoch) {
        (nb + eta, format!("Component Ocean not_before: next retry {}{}", fmt_utc(nb),
            if eta > 0 { format!(", plus its {} s ETA", eta) } else { String::new() }))
    } else if let Some(t0) = req.get("requested_at").and_then(epoch) {
        let (lim, what) = if state == "review" { (LIMIT_REVIEW_SECS, "in review") }
            else if req.get("urgency").and_then(|v| v.as_str()) == Some("later") { (LIMIT_LATER_SECS, "a `later` request") }
            else { (LIMIT_NOW_SECS, "an urgent request") };
        (t0 + lim, format!("service limit: {} min for {} from requested_at", lim / 60, what))
    } else if eta > 0 {
        (now + eta, "Component Ocean eta_seconds".to_string())
    } else { return None; };
    let passed = now > at || matches!(state, "failed" | "error" | "rejected");
    let eta_text = if passed { Some(format!("late: was due {}", fmt_utc(at))) }
        else if at - now > eta + 120 || req.get("not_before").is_some() { Some(format!("due by {}", fmt_utc(at))) }
        else { None };
    Some(Deadline { at, source, passed, eta_text })
}

/// The wiki's hint code once a request is past its deadline with the part unbuilt.
pub const LATE_CODE: &str = "PART_REQUEST_DEADLINE_PASSED";

/// A field of a status or request answer, read at the top level first, then inside `request`.
pub fn field<'a>(r: &'a serde_json::Value, k: &str) -> Option<&'a serde_json::Value> {
    r.get(k).filter(|v| !v.is_null()).or_else(|| r.get("request").and_then(|q| q.get(k)).filter(|v| !v.is_null()))
}

/// The request's state ("queued", "building", "review", "built", ...), "?" when the answer has none.
pub fn state(r: &serde_json::Value) -> &str {
    r.get("request").and_then(|q| q.get("state")).or(r.get("state")).and_then(|v| v.as_str()).unwrap_or("?")
}

/// Nothing more will happen on its own: the part is built, or the request ended.
pub fn is_final(state: &str) -> bool {
    matches!(state, "built" | "done" | "published" | "public" | "cancelled" | "canceled" | "failed" | "error" | "rejected")
}

/// The wiki keeps the clock and holds status answers (`?wait`): it sends `deadline_at` or `deadline_passed`.
pub fn wiki_keeps_the_clock(r: &serde_json::Value) -> bool {
    field(r, "deadline_at").is_some() || field(r, "deadline_passed").is_some()
}

/// The wiki says the request is late: `deadline_passed`, or its PART_REQUEST_DEADLINE_PASSED hint.
pub fn wiki_says_late(r: &serde_json::Value) -> bool {
    if field(r, "deadline_passed").and_then(|v| v.as_bool()) == Some(true) { return true; }
    let is_late = |v: &serde_json::Value| v.as_str() == Some(LATE_CODE)
        || v.get("code").and_then(|c| c.as_str()) == Some(LATE_CODE);
    ["code", "hint_code", "hint"].iter().any(|k| field(r, k).map(is_late).unwrap_or(false))
        || field(r, "hints").and_then(|h| h.as_array()).map(|a| a.iter().any(is_late)).unwrap_or(false)
}

/// When the request is due: the wiki's own `deadline_at` and `deadline_passed` when it sends them, else the time
/// worked out here from Component Ocean's answer (older wikis). None once the part is built or the request ended.
pub fn due(r: &serde_json::Value, now: i64) -> Option<Deadline> {
    let req = r.get("request").cloned().unwrap_or(serde_json::Value::Null);
    if is_final(state(r)) { return None; }
    if wiki_keeps_the_clock(r) {
        let at = field(r, "deadline_at").and_then(epoch);
        let passed = wiki_says_late(r);
        return at.map(|at| Deadline { at, source: "the wiki's deadline".into(), passed,
            eta_text: Some(if passed { format!("late: was due {}", fmt_utc(at)) } else { format!("due by {}", fmt_utc(at)) }) })
            .or_else(|| passed.then(|| Deadline { at: now, source: "the wiki says the deadline passed".into(), passed, eta_text: None }));
    }
    deadline(&req, now)
}

/// The Hint once the deadline has passed: use a verified page, finish an existing one, or build the part yourself.
pub fn late_hint_text(slug: &str, due: &str, page: &crate::wiki::PageState) -> String {
    use crate::wiki::PageState::*;
    let r = format!("adom/{}", slug);
    match page {
        Exists { verified: true } => format!("The factory is late (due {}), but {} already exists and is verified: use it \
            (https://wiki.adom.inc/{}). Do not build this part yourself and do not overwrite that page.", due, r, r),
        Exists { verified: false } => format!("The factory is late (due {}). {} already exists: finish that page with the {} \
            instead of creating a second one, and keep anything a person edited or verified on it.", due, r, SKILL_BUILD_PAGE),
        Missing | Unknown(_) => format!("The factory is late (due {}). You may build this part yourself with the {}, publishing \
            to {}.{} Never create a duplicate page and never overwrite a page that has a verification record or a person's edit; \
            if the factory finishes later, its build does not replace yours.", due, SKILL_BUILD_PAGE, r,
            if let Unknown(e) = page { format!(" Could not check whether {} exists ({}): check it before you publish.", r, e) }
            else { format!(" {} does not exist yet; check again right before you publish.", r) }),
    }
}

/// The page the request will fill: CO's page_url when set, else the MPN as a wiki slug (LTST-C19HE1WT -> ltst-c19he1wt).
pub fn page_slug(req: &serde_json::Value) -> String {
    if let Some(u) = req.get("page_url").and_then(|v| v.as_str()).filter(|u| !u.is_empty()) {
        return u.trim_end_matches('/').rsplit('/').next().unwrap_or(u).to_string();
    }
    let s: String = req.get("mpn").and_then(|v| v.as_str()).unwrap_or("").to_lowercase().chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
    s.trim_matches('-').to_string()
}

/// Seconds since the epoch, UTC: "2026-11-26 04:15:13" (CO's form), RFC 3339 with Z or an offset, or a number.
pub fn epoch(v: &serde_json::Value) -> Option<i64> {
    if let Some(n) = v.as_i64() { return Some(if n > 100_000_000_000 { n / 1000 } else { n }); }
    let s = v.as_str()?.trim();
    if let Ok(n) = s.parse::<i64>() { return epoch(&serde_json::json!(n)); }
    let n = |a: usize, b: usize| s.get(a..b).and_then(|x| x.parse::<i64>().ok());
    let t = days_from_civil(n(0, 4)?, n(5, 7)?, n(8, 10)?) * 86400 + n(11, 13)? * 3600 + n(14, 16)? * 60 + n(17, 19)?;
    let tail = s.get(19..).unwrap_or("").trim_start_matches(|c: char| c == '.' || c.is_ascii_digit());
    let off = match tail.as_bytes().first() {
        Some(b'+') | Some(b'-') => {
            let sign = if tail.starts_with('-') { -1 } else { 1 };
            let h = tail.get(1..3)?.parse::<i64>().ok()?;
            let m = tail.get(4..6).or(tail.get(3..5)).and_then(|x| x.parse::<i64>().ok()).unwrap_or(0);
            sign * (h * 3600 + m * 60)
        }
        _ => 0,
    };
    Some(t - off)
}

fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;
    era * 146097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719468
}

pub fn fmt_utc(t: i64) -> String {
    let (days, secs) = (t.div_euclid(86400), t.rem_euclid(86400));
    let z = days + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    let doe = z - era * 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
    format!("{:04}-{:02}-{:02} {:02}:{:02} UTC", y, m, d, secs / 3600, secs % 3600 / 60)
}

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

    fn at(s: &str) -> i64 { epoch(&json!(s)).unwrap() }

    #[test]
    fn retry_hours_away_quotes_the_deadline_not_about_a_minute() {
        let now = at("2026-11-26 14:30:00");
        let req = json!({"mpn": "LTST-C19HE1WT", "state": "queued", "position": 1, "eta_seconds": 0,
            "eta_text": "about a minute", "urgency": "now", "requested_at": "2026-11-26 14:25:00",
            "not_before": "2026-11-26T18:00:00Z"});
        let d = deadline(&req, now).unwrap();
        assert_eq!(fmt_utc(d.at), "2026-11-26 18:00 UTC");
        assert!(!d.passed);
        assert!(d.source.contains("not_before"), "{}", d.source);
        assert!(d.line().contains("due by 2026-11-26 18:00 UTC"));
        let t = d.eta_text.unwrap();
        assert!(!t.contains("minute"), "{}", t);
    }

    #[test]
    fn deadline_passed_gives_the_build_it_yourself_hint() {
        // the LTST-C19HE1WT stall: queued at 04:15, eta 0 "about a minute", still there 10 hours later
        let req = json!({"mpn": "LTST-C19HE1WT", "state": "queued", "position": 1, "eta_seconds": 0,
            "eta_text": "about a minute", "urgency": "now", "requested_at": "2026-11-26 04:15:13"});
        let d = deadline(&req, at("2026-11-26 14:30:00")).unwrap();
        assert!(d.passed);
        assert_eq!(fmt_utc(d.at), "2026-11-26 04:35 UTC");
        assert!(d.source.starts_with("service limit"));
        assert!(!d.eta_text.as_deref().unwrap().contains("minute"));
        assert_eq!(page_slug(&req), "ltst-c19he1wt");
        let h = late_hint_text(&page_slug(&req), &fmt_utc(d.at), &PageState::Missing);
        assert!(h.contains("factory is late") && h.contains("build-a-component-page") && h.contains("adom/ltst-c19he1wt"), "{}", h);
        assert!(h.contains("duplicate") && h.contains("verification record"), "{}", h);
        // not yet due: no deadline passed
        assert!(!deadline(&req, at("2026-11-26 04:20:00")).unwrap().passed);
    }

    #[test]
    fn verified_page_exists_hint_says_use_it_do_not_build() {
        let h = late_hint_text("ltst-c19he1wt", "2026-11-26 04:35 UTC", &PageState::Exists { verified: true });
        assert!(h.contains("use it") && h.contains("Do not build") && h.contains("do not overwrite"), "{}", h);
        assert!(!h.contains("build-a-component-page"), "{}", h);
        assert!(crate::wiki::has_verification(&json!({"verification": {"entries": [{"status": "verified"}]}})));
        assert!(!crate::wiki::has_verification(&json!({"verification": {"entries": []}})));
    }

    #[test]
    fn the_wikis_deadline_wins_over_the_local_estimate() {
        // the wiki says 04:35 and not late, though Component Ocean's not_before would say 18:00
        let r = json!({"request": {"mpn": "LM358", "state": "queued", "requested_at": "2026-12-04 04:15:00",
            "not_before": "2026-12-04T18:00:00Z"}, "deadline_at": "2026-12-04T04:35:00Z", "deadline_passed": false});
        let d = due(&r, at("2026-12-04 04:20:00")).unwrap();
        assert_eq!(fmt_utc(d.at), "2026-12-04 04:35 UTC");
        assert!(!d.passed && d.source == "the wiki's deadline");
        assert!(wiki_keeps_the_clock(&r));
        // the wiki's word decides late, not this machine's clock
        let d = due(&r, at("2026-12-04 09:00:00")).unwrap();
        assert!(!d.passed, "local clock must not override deadline_passed: false");
    }

    #[test]
    fn late_from_deadline_passed_or_the_hint_code() {
        let r = json!({"request": {"state": "queued", "deadline_at": "2026-12-04 04:35:00", "deadline_passed": true}});
        let d = due(&r, at("2026-12-04 05:00:00")).unwrap();
        assert!(d.passed && d.line().starts_with("LATE: was due 2026-12-04 04:35 UTC"), "{}", d.line());
        let r = json!({"request": {"state": "queued"}, "deadline_at": "2026-12-04T04:35:00Z",
            "hint": {"code": "PART_REQUEST_DEADLINE_PASSED", "text": "late"}});
        assert!(wiki_says_late(&r) && due(&r, 0).unwrap().passed);
        let r = json!({"request": {"state": "queued"}, "deadline_passed": true});
        assert!(due(&r, 100).unwrap().passed, "late with no deadline_at still reads late");
    }

    #[test]
    fn an_older_wiki_falls_back_to_the_local_estimate() {
        let r = json!({"request": {"mpn": "LTST-C19HE1WT", "state": "queued", "urgency": "now", "requested_at": "2026-11-26 04:15:13"}});
        assert!(!wiki_keeps_the_clock(&r));
        let d = due(&r, at("2026-11-26 14:30:00")).unwrap();
        assert!(d.passed && d.source.starts_with("service limit"));
        // built: nothing is due, whatever the wiki sends
        assert!(due(&json!({"request": {"state": "built"}, "deadline_passed": true}), 0).is_none());
    }

    #[test]
    fn built_request_has_no_deadline() {
        assert!(deadline(&json!({"state": "built", "requested_at": "2026-11-26 04:15:13"}), at("2026-11-27 00:00:00")).is_none());
    }
}