use crate::utils::time::diff_ymd;
use crate::Args;
use chrono::{DateTime, Local, NaiveDate, Utc};
use clap::Parser;
use colored::Colorize;
use std::fmt::Write;
use std::fs;
use std::path::Path;

fn calculate_system_age(start: DateTime<Utc>, end: DateTime<Utc>) -> (i32, i32, i32) {
    diff_ymd(start, end)
}

pub fn count_system_age() -> Result<NaiveDate, Box<dyn std::error::Error>> {
    let start_datetime = {
        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()?;
        created.into()
    };

    let now = Utc::now();

    let (years, months, days) = calculate_system_age(start_datetime, now);

    let year_label = if years == 1 { "Year" } else { "Years" };
    let month_label = if months == 1 { "Month" } else { "Months" };
    let day_label = if days == 1 { "Day" } else { "Days" };

    let args = Args::parse();

    let mut output = String::new();

    if years > 0 {
        if args.no_colors {
            write!(output, "{years} {year_label} ").unwrap();
        } else {
            write!(
                output,
                "{} {} ",
                years.to_string().yellow().bold(),
                year_label.yellow().bold()
            )
            .unwrap();
        }
    }

    if months > 0 {
        if args.no_colors {
            write!(output, "{months} {month_label} ").unwrap();
        } else {
            write!(
                output,
                "{} {} ",
                months.to_string().green().bold(),
                month_label.green().bold()
            )
            .unwrap();
        }
    }

    if days > 0 || (years == 0 && months == 0) {
        if args.no_colors {
            write!(output, "{days} {day_label}").unwrap();
        } else {
            write!(
                output,
                "{} {}",
                days.to_string().cyan().bold(),
                day_label.cyan().bold()
            )
            .unwrap();
        }
    }

    println!("{output}");

    Ok(start_datetime.with_timezone(&Local).date_naive())
}
