use chrono::{DateTime, Datelike, Local, Timelike, Utc};
use std::{fs, path::Path};

pub fn get_system_creation_date() -> Result<DateTime<Local>, Box<dyn std::error::Error>> {
    let root_dir = if Path::new("/bedrock").exists() {
        "/bedrock"
    } else if Path::new("/ostree").exists() {
        "/ostree"
    } else {
        "/"
    };

    let metadata = fs::metadata(root_dir)?;
    let created = metadata.created()?; // System creation timestamp
    let created_datetime: DateTime<Utc> = created.into();

    Ok(created_datetime.with_timezone(&Local))
}

pub fn diff_ymd(start: DateTime<Utc>, end: DateTime<Utc>) -> (i32, i32, i32) {
    let mut years = end.year() - start.year();
    let mut months = end.month() as i32 - start.month() as i32;
    let mut days = end.day() as i32 - start.day() as i32;

    // Adjust for time of day
    if end.hour() < start.hour()
        || (end.hour() == start.hour() && end.minute() < start.minute())
        || (end.hour() == start.hour()
            && end.minute() == start.minute()
            && end.second() < start.second())
    {
        days -= 1;
    }

    if days < 0 {
        months -= 1;
        
        let last_day_of_prev_month = chrono::NaiveDate::from_ymd_opt(end.year(), end.month(), 1)
            .and_then(|d| d.pred_opt());

        let days_in_prev_month = last_day_of_prev_month.map(|d| d.day() as i32).unwrap_or(0);

        days += days_in_prev_month;
    }

    if months < 0 {
        months += 12;
        years -= 1;
    }

    (years, months, days)
}
