// src/logic/handler.rs

use embassy_time::{Duration, Timer};
use embassy_stm32::peripherals;
use embassy_stm32::Peri;

use crate::sleep::stop::{enter_stop0, enter_stop1, enter_stop2, enter_stop3};
use crate::sleep::sleep::{enter_sleep_mode, SleepEntry};
use crate::sleep::{standby, shutdown};
use crate::wakeup::iwdg::init_watchdog_reset;
use crate::logic::uart_cmd::{LowPowerCmd, StopMode, StopModeConfig};

use defmt::info;

pub async fn execute_low_power(
    cmd: LowPowerCmd, 
    iwdg: &mut Option<Peri<'static, peripherals::IWDG>>
) {
    Timer::after(Duration::from_millis(10)).await;

    match cmd {
        LowPowerCmd::Standby8k => {
            info!("Entering Standby with 8KB SRAM2 retention");
            if let Some(wdg) = iwdg.take() {
                init_watchdog_reset(wdg).await;
            }
            standby::enter_standby_with_sram2_8kb();
        }
        LowPowerCmd::StandbyFull => {
            info!("Entering Standby with full SRAM2 retention");
            if let Some(wdg) = iwdg.take() {
                init_watchdog_reset(wdg).await;
            }
            standby::enter_standby_with_sram2_full();
        }
        LowPowerCmd::Standby => {
            info!("Entering minimal Standby");
            if let Some(wdg) = iwdg.take() {
                init_watchdog_reset(wdg).await;
            }
            standby::enter_standby();
        }
        LowPowerCmd::Shutdown => {
            info!("Entering Shutdown mode");
            shutdown::enter_shutdown();
        }
        LowPowerCmd::StopMode(StopModeConfig { mode, entry }) => {
            info!("Entering {:?} with {:?}", mode, entry);
            match mode {
                StopMode::Stop0 => enter_stop0(),
                StopMode::Stop1 => enter_stop1(entry),
                StopMode::Stop2 => enter_stop2(entry),
                StopMode::Stop3 => {
                    if let Some(wdg) = iwdg.take() {
                        init_watchdog_reset(wdg).await;
                    }
                    enter_stop3(entry);
                }
            }
        }
        LowPowerCmd::Sleep => {
            info!("Entering Sleep mode (WFI)...");
            enter_sleep_mode(SleepEntry::Wfi);
            info!("Woke up from Sleep mode.");
        }
    }
}
