use alpha2_diagnose::advise::Context;
use alpha2_diagnose::codes::{SHAPE_NOT_INTEGER, SHAPE_WRONG_TYPE};
use alpha2_diagnose::{Diagnostic, Edit, Fix, Node};
const LONGEST_SECONDS_GUESSED: f64 = 86_400.0;
#[expect(clippy::cast_precision_loss, reason = "the tick rate is exact in f64")]
const TICKS_PER_SECOND: f64 = alpha2_time::TICKS_PER_SECOND as f64;
pub const TICKS_HELP: &str = "times are integer ticks, 120000 per second";
fn is_ticks(diagnostic: &Diagnostic) -> bool {
diagnostic
.reference
.as_ref()
.is_some_and(|reference| reference.definition == "MediaTime")
|| diagnostic
.path
.last_key()
.is_some_and(|key| key.ends_with("_ticks"))
}
fn seconds(node: &Node) -> Option<f64> {
let value = match node.as_str() {
Some(text) => {
let text = text.trim();
text.strip_suffix('s')
.unwrap_or(text)
.trim_end()
.parse::<f64>()
.ok()?
}
None => node.as_number()?.as_f64(),
};
(value.is_finite() && value.abs() < LONGEST_SECONDS_GUESSED).then_some(value)
}
pub fn ticks_for_seconds(diagnostic: &mut Diagnostic, context: &Context<'_>) {
let fraction = diagnostic.is(&SHAPE_NOT_INTEGER) && diagnostic.datum("whole").is_none();
let text = diagnostic.is(&SHAPE_WRONG_TYPE)
&& context
.tree
.at(&diagnostic.path)
.is_some_and(|node| node.as_str().is_some());
if !(fraction || text) || !is_ticks(diagnostic) {
return;
}
diagnostic.help.push(TICKS_HELP.to_owned());
let Some(value) = context.tree.at(&diagnostic.path).and_then(seconds) else {
return;
};
#[expect(
clippy::cast_possible_truncation,
reason = "the value is under a day in seconds, far inside i64"
)]
let ticks = (value * TICKS_PER_SECOND).round() as i64;
diagnostic.help.push(format!(
"if this is {value} seconds, it is {ticks} ticks (a guess)"
));
diagnostic.fixes.push(Fix::likely(
format!("write {ticks} ticks"),
vec![Edit::Replace {
path: diagnostic.path.clone(),
value: Node::integer(ticks),
}],
));
}