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
//! `request <MPN>` and `request-status <id> [--wait]`: the wiki's own part-request flow.
//!
//! A signed-in request is answered in the thread that asked (wikis from 2026-12-04 on): no email, a status to follow
//! and a deadline. `--email` asks for the email instead. `request-status --wait` lets the wiki hold each answer until
//! something changes, so a thread follows its request without polling.

use crate::deadline::{self, due, fmt_utc, is_final, late_hint_text, page_slug, state, wiki_keeps_the_clock, wiki_says_late};
use serde_json::Value;
use std::time::{Duration, Instant};

/// Seconds the wiki is asked to hold one status answer (it allows 55).
const WAIT_SECS: u64 = 50;
/// The longest `--wait` follows a request: past the longest deadline the wiki accepts (1440 minutes).
const FOLLOW_MAX: Duration = Duration::from_secs(25 * 3600);
/// A wiki that answers at once with nothing new is not asked again sooner than this.
const MIN_GAP: Duration = Duration::from_secs(10);

fn now() -> i64 {
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}

/// The request id from an answer: `request.id`, else the last part of its status link.
pub fn request_id(r: &Value) -> Option<String> {
    if let Some(i) = r.pointer("/request/id").filter(|v| !v.is_null()) {
        return Some(i.as_str().map(String::from).unwrap_or_else(|| i.to_string()));
    }
    ["status_api", "status_url"].iter().filter_map(|k| deadline::field(r, k).and_then(|v| v.as_str()))
        .filter_map(|u| u.trim_end_matches('/').rsplit('/').next().map(String::from)).find(|s| !s.is_empty())
}

/// Where the answer goes, in words: this thread (no email), or an email. None when the part already has a page.
pub fn notify_line(r: &Value, id: Option<&str>) -> Option<String> {
    if r.get("already").and_then(|v| v.as_str()) == Some("built") { return None; }
    let due = deadline::field(r, "deadline_at").and_then(|v| deadline::epoch(v)).map(|t| format!(", due by {}", fmt_utc(t)))
        .unwrap_or_default();
    let follow = id.map(|i| format!("`adom-parts-search request-status {} --wait`", i)).unwrap_or_else(|| "request-status --wait".into());
    match r.get("notify").and_then(|v| v.as_str()) {
        Some("thread") => Some(format!("No email: this thread follows it with {}{}", follow, due)),
        Some("email") => Some(format!("The wiki emails you when it is ready{}", due)),
        Some(other) => Some(format!("Answered by {}{}", other, due)),
        None => Some("The wiki emails you when it is ready (this wiki does not answer in the thread yet)".into()),
    }
}

pub fn run_request(a: crate::RequestArgs) -> Result<(), String> {
    if a.urgency != "now" && a.urgency != "later" { return Err("--urgency is now or later".into()); }
    if let Some(m) = a.deadline { if !(1..=1440).contains(&m) { return Err("--deadline is 1 to 1440 minutes".into()); } }
    let opts = crate::wiki::RequestOpts { notify: a.email.then(|| "email".to_string()), deadline_minutes: a.deadline };
    let r = crate::wiki::request(&a.mpn, &a.urgency, &opts)?;
    let req = r.get("request").cloned().unwrap_or(Value::Null);
    let status = r.get("status_url").and_then(|v| v.as_str()).unwrap_or("");
    let id = request_id(&r);
    let head = match (r.get("already").and_then(|v| v.as_str()), state(&r)) {
        (Some("built"), _) => format!("{} already has a page: {}", a.mpn, req.get("page_url").or(r.get("outcome_url")).and_then(|v| v.as_str()).unwrap_or("")),
        (Some("building"), _) => format!("{} is already being built; follow it: {}", a.mpn, status),
        (_, st) => format!("{} requested ({}{}); status: {}", a.mpn, st,
                     r.get("position").and_then(|v| v.as_u64()).map(|p| format!(", position {}", p)).unwrap_or_default(), status),
    };
    crate::ok(match notify_line(&r, id.as_deref()) { Some(n) => format!("{}. {}", head, n), None => head });
    println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
    if r.get("notify").and_then(|v| v.as_str()) == Some("thread") {
        if let Some(i) = &id {
            crate::hint(format!("Follow it with `adom-parts-search request-status {} --wait`: one line per change, until the part \
                is built, goes to review or passes its deadline. Do not loop request-status yourself.", i));
        }
    }
    Ok(())
}

/// One line for where a request stands: state, reason, position, and when it is due.
pub fn status_line(id: &str, r: &Value, now: i64) -> String {
    let reason = deadline::field(r, "public_reason").or(deadline::field(r, "reason")).and_then(|v| v.as_str())
        .map(|x| format!(" ({})", x)).unwrap_or_default();
    let pos = deadline::field(r, "position").and_then(|v| v.as_u64()).map(|p| format!(", position {}", p)).unwrap_or_default();
    let d = due(r, now).map(|d| format!("; {}", d.line())).unwrap_or_default();
    format!("request {}: {}{}{}{}", id, state(r), reason, pos, d)
}

/// Following stops once the part is built or the request ended, it went to a person's review, or it is late.
fn settled(r: &Value) -> bool { is_final(state(r)) || state(r) == "review" || wiki_says_late(r) }

pub fn run_request_status(id: &str, wait: bool) -> Result<(), String> {
    let id = id.trim_end_matches('/').rsplit('/').next().unwrap_or(id).to_string();
    let mut r = crate::wiki::request_status(&id, None)?;
    let mut last = status_line(&id, &r, now());
    crate::ok(&last);
    if wait && !settled(&r) {
        if !wiki_keeps_the_clock(&r) {
            crate::warn("this wiki does not hold status answers yet (its answer has no deadline_at), so --wait cannot \
                follow the request; run request-status again later");
        } else {
            r = follow(&id, r, &mut last)?;
        }
    }
    finish(r)
}

/// Long-poll the wiki (`?wait=50&since=<state>`) and print a line each time something changes.
fn follow(id: &str, mut r: Value, last: &mut String) -> Result<Value, String> {
    let started = Instant::now();
    let mut errors = 0;
    while !settled(&r) && started.elapsed() < FOLLOW_MAX {
        let t0 = Instant::now();
        let since = state(&r).to_string();
        match crate::wiki::request_status(id, Some((WAIT_SECS, Some(&since)))) {
            Ok(n) => { errors = 0; r = n; }
            Err(e) => {
                errors += 1;
                if errors >= 3 { return Err(format!("lost the wiki while following request {}: {}", id, e)); }
                std::thread::sleep(Duration::from_secs(15));
                continue;
            }
        }
        let line = status_line(id, &r, now());
        if line != *last { crate::ok(&line); *last = line; }
        else if t0.elapsed() < Duration::from_secs(5) { std::thread::sleep(MIN_GAP); }
    }
    Ok(r)
}

/// The full answer on stdout with the deadline written in, and once late, the Hint to build the part.
fn finish(mut r: Value) -> Result<(), String> {
    let req = r.get("request").cloned().unwrap_or(Value::Null);
    let mut late_hint = None;
    if let Some(d) = due(&r, now()) {
        // CO's eta_text is not quoted when it contradicts the deadline (a retry hours away, or already late)
        if let Some(t) = d.eta_text.clone() { if r["request"].is_object() { r["request"]["eta_text"] = Value::String(t); } }
        r["deadline"] = serde_json::json!({"at": fmt_utc(d.at), "source": d.source, "passed": d.passed});
        if d.passed {
            let slug = page_slug(&req);
            late_hint = Some(late_hint_text(&slug, &fmt_utc(d.at), &crate::wiki::page_state("adom", &slug, Some(&crate::wiki::request_base()))));
        }
    }
    println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
    if let Some(h) = late_hint { crate::hint(h); }
    Ok(())
}

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

    #[test]
    fn a_thread_request_says_no_email_and_how_to_follow() {
        let r = json!({"request": {"id": "abc123", "state": "queued"}, "notify": "thread",
            "deadline_at": "2026-12-04T04:35:00Z", "status_api": "https://wiki.adom.inc/api/part-request/status/abc123"});
        let id = request_id(&r);
        assert_eq!(id.as_deref(), Some("abc123"));
        let l = notify_line(&r, id.as_deref()).unwrap();
        assert!(l.starts_with("No email") && l.contains("request-status abc123 --wait") && l.contains("due by 2026-12-04 04:35 UTC"), "{}", l);
    }

    #[test]
    fn email_and_older_wikis_say_email() {
        assert!(notify_line(&json!({"notify": "email"}), None).unwrap().starts_with("The wiki emails you"));
        assert!(notify_line(&json!({"request": {"state": "queued"}}), None).unwrap().contains("does not answer in the thread yet"));
        assert!(notify_line(&json!({"already": "built"}), None).is_none());
        // the id from a status link when the request has none
        assert_eq!(request_id(&json!({"status_url": "https://wiki.adom.inc/part-request/41zd/"})).as_deref(), Some("41zd"));
    }

    #[test]
    fn following_stops_at_built_review_or_late() {
        assert!(settled(&json!({"request": {"state": "built"}})));
        assert!(settled(&json!({"request": {"state": "review"}})));
        assert!(settled(&json!({"request": {"state": "queued"}, "deadline_passed": true})));
        assert!(!settled(&json!({"request": {"state": "queued"}, "deadline_passed": false})));
        let l = status_line("abc", &json!({"request": {"state": "queued", "position": 2}, "deadline_at": "2026-12-04T04:35:00Z",
            "deadline_passed": false}), 0);
        assert_eq!(l, "request abc: queued, position 2; due by 2026-12-04 04:35 UTC (the wiki's deadline)");
    }
}