// src/bin/main.rs
#![no_std]
#![no_main]

use defmt::*;
use embassy_executor::Spawner;
use embassy_time::{Timer, Duration};
use embassy_stm32::gpio::{Output, Level, Speed};
use dma_gpio::software_uart::{
    dma_timer::init_tim6_for_uart,
    debug::dump_tim6_regs,
};
use dma_gpio::config::{BAUD, TX_OVERSAMPLE, TX_PIN_BIT, UART_CFG};
use static_cell::StaticCell;
use embassy_futures::yield_now;
use dma_gpio::hw_uart_pc::usart1;
use dma_gpio::hw_uart_pc::driver::uart_task;
use embassy_stm32::usart::{BufferedUart, Config, BufferedInterruptHandler};
use embassy_stm32::peripherals;
use embassy_stm32::bind_interrupts;
use dma_gpio::config::{PIPE_HW_TX, PIPE_HW_RX, PIPE_SW_TX};
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, pipe::Pipe};
use dma_gpio::hw_uart_internal::usart2;
use dma_gpio::hw_uart_internal::driver::uart_task as uart_task_internal;
use dma_gpio::config::{PIPE_INT_TX, PIPE_INT_RX};
use {defmt_rtt as _, panic_probe as _};

bind_interrupts!(struct Irqs {
    USART1 => BufferedInterruptHandler<peripherals::USART1>;
});
bind_interrupts!(struct Irqs2 {
    USART2 => BufferedInterruptHandler<peripherals::USART2>;
});

#[embassy_executor::main]
async fn main(spawner: Spawner) {
    info!("boot");
    let p = embassy_stm32::init(Default::default());
    info!("init m8");

    // HARDWARE UART to the PC
    let mut cfg = Config::default();
    cfg.baudrate = BAUD;
    static TX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
    static RX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
    let uart = BufferedUart::new(
        p.USART1,
        p.PA10, // RX pin
        p.PA9,  // TX pin
        TX_BUF.init([0; 256]),
        RX_BUF.init([0; 256]),
        Irqs,
        cfg,
    ).unwrap();
    let _yield_period = usart1::setup_and_spawn(BAUD);
    spawner.spawn(uart_task(uart, &PIPE_HW_TX, &PIPE_HW_RX).unwrap());
    // END OF HARDWARE UART to the PC

    // INTERNAL HARDWARE UART (USART2)
    let mut cfg2 = Config::default();
    cfg2.baudrate = BAUD;
    static TX_BUF2: StaticCell<[u8; 256]> = StaticCell::new();
    static RX_BUF2: StaticCell<[u8; 256]> = StaticCell::new();

    let uart2 = BufferedUart::new(
        p.USART2,
        p.PD6, // RX
        p.PA2, // TX
        TX_BUF2.init([0; 256]),
        RX_BUF2.init([0; 256]),
        Irqs2,
        cfg2,
    ).unwrap();

    let _ = usart2::setup_and_spawn(BAUD);
    spawner.spawn(uart_task_internal(uart2, &PIPE_INT_TX, &PIPE_INT_RX).unwrap());
    info!("USART2 ready");
    // END OF INTERNAL HARDWARE UART (USART2)

    // USART1 <-> USART2 bridge
    spawner.spawn(bridge_usart1_rx_to_usart2_tx(&PIPE_HW_RX, &PIPE_INT_TX).unwrap());
    spawner.spawn(bridge_usart2_rx_to_usart1_tx(&PIPE_INT_RX, &PIPE_HW_TX).unwrap());
    info!("USART1 <-> USART2 bridge active");
    // END OF USART1 <-> USART2 bridge

    // SOFTWARE UART
    let _tx = Output::new(p.PB0, Level::High, Speed::VeryHigh);
    init_tim6_for_uart(p.TIM6, BAUD, TX_OVERSAMPLE);
    dump_tim6_regs();

    let bsrr_ptr = embassy_stm32::pac::GPIOB.bsrr().as_ptr() as *mut u32; // POZOR B REGISTER
    spawner.spawn(tx_cpu_task(bsrr_ptr, &PIPE_SW_TX).unwrap());
    // END OF SOFTWARE UART

    let mut buf = [0u8; 32];
    let mut counter: u32 = 0;

    loop {
        info!("tick start");

        counter += 1;
        let msg = if counter % 2 == 0 {
            b"AAAAA\r\n"
        } else {
            b"Hello\r\n"
        };
        PIPE_SW_TX.write(msg).await;
        info!("Sent: {:a}", msg);

        Timer::after(Duration::from_secs(3)).await;

        yield_now().await;
    }
}

#[embassy_executor::task]
pub async fn bridge_usart1_rx_to_usart2_tx(
    usart1_rx: &'static Pipe<CriticalSectionRawMutex, 1024>,
    usart2_tx: &'static Pipe<CriticalSectionRawMutex, 1024>,
) {
    let mut buf = [0u8; 64];
    loop {
        let n = usart1_rx.read(&mut buf).await;
        if n > 0 {
            let _ = usart2_tx.write(&buf[..n]).await;
            info!("bridge: USART1 -> USART2 sent {} bytes", n);
        }
    }
}

#[embassy_executor::task]
pub async fn bridge_usart2_rx_to_usart1_tx(
    usart2_rx: &'static Pipe<CriticalSectionRawMutex, 1024>,
    usart1_tx: &'static Pipe<CriticalSectionRawMutex, 1024>,
) {
    let mut buf = [0u8; 64];
    loop {
        let n = usart2_rx.read(&mut buf).await;
        if n > 0 {
            let _ = usart1_tx.write(&buf[..n]).await;
            info!("bridge: USART2 -> USART1 sent {} bytes", n);
        }
    }
}

#[embassy_executor::task]
pub async fn tx_cpu_task(
    bsrr_ptr: *mut u32,
    pipe_tx: &'static embassy_sync::pipe::Pipe<embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex, 1024>,
) {
    use dma_gpio::software_uart::uart_emulation::encode_uart_byte_cfg;
    use embassy_futures::yield_now;
    use dma_gpio::config::{TX_PIN_BIT, UART_CFG};

    // Access TIM6 registers directly via PAC
    let tim6_regs = embassy_stm32::pac::TIM6;
    let mut rx_buf = [0u8; 256];
    let mut frame_buf = [0u32; 12];

    loop {
        let n = pipe_tx.read(&mut rx_buf).await;
        if n == 0 {
            yield_now().await;
            continue;
        }

        for &byte in &rx_buf[..n] {
            let used = encode_uart_byte_cfg(TX_PIN_BIT, byte, &UART_CFG, &mut frame_buf);

            // === SYNC LOGIC ===
            // Reset timer counter to 0 using Event Generation Register (UG bit)
            // This ensures we start counting exactly from now.
            tim6_regs.egr().write(|w| w.set_ug(true));
            // The UG event sets the UIF flag immediately. We must clear it.
            tim6_regs.sr().write(|w| w.set_uif(false));

            // Now we loop through the encoded frame.
            // Since we just reset the timer and cleared UIF, the first wait
            // will block for exactly 1 bit-period.
            // This effectively adds 1 bit of idle time before the Start Bit,
            // which guarantees the line is stable High before dropping Low.
            for word in &frame_buf[..used] {
                while !tim6_regs.sr().read().uif() {
                    yield_now().await;
                }
                tim6_regs.sr().write(|w| w.set_uif(false));
                unsafe { core::ptr::write_volatile(bsrr_ptr, *word) };
            }
        }
    }
}
