use chrono::{Duration, Local};
#[cfg(target_os = "linux")]
use std::process::{Command, Stdio};
use crate::config;
use crate::notifications;
use crate::utils::{get_last_update_time, is_live_environment};

pub fn run_scheduled() {
    if is_live_environment() {
        return;
    }

    let last_update = get_last_update_time();
    let now = Local::now();

    let should_run = if let Some(modified_dt) = last_update {
        (now - modified_dt) > Duration::days(config::UPDATE_INTERVAL_DAYS)
    } else {
        true
    };

    if should_run {
        match notifications::send_update_available() {
            Some(handle) => {
                #[cfg(target_os = "linux")]
                handle.wait_for_action(|action| {
                    if action == "open_gui" {
                        if let Ok(exe) = std::env::current_exe() {
                            let _ = Command::new(exe)
                                .arg("gui")
                                .stdin(Stdio::null())
                                .stdout(Stdio::null())
                                .stderr(Stdio::null())
                                .spawn();
                        }
                    }
                });
                #[cfg(not(target_os = "linux"))]
                { let _ = handle; }
            },
            None => eprintln!("Failed to send notification"),
        }
    } else if let Some(last_run) = last_update {
        let next_run = last_run + Duration::days(config::UPDATE_INTERVAL_DAYS);
        let remaining = next_run - now;

        if remaining.num_seconds() > 0 {
            let days = remaining.num_days();
            let hours = remaining.num_hours() % 24;
            let mins = remaining.num_minutes() % 60;
            let secs = remaining.num_seconds() % 60;

            if days > 0 {
                println!("No updates needed. Next check in {}d {}h {}m.", days, hours, mins);
            } else if hours > 0 {
                println!("No updates needed. Next check in {}h {}m {}s.", hours, mins, secs);
            } else {
                println!("No updates needed. Next check in {}m {}s.", mins, secs);
            }
            return;
        }
    } else {
        println!("No updates needed.");
    }
}
