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

use defmt::*;
use embassy_executor::Spawner;
use embassy_time::{Instant, Timer, Duration};
use embassy_stm32::dma::Request;
use embassy_stm32::gpio::{Input, Output, Level, Pull, Speed};
use dma_gpio::software_uart::{
    dma_timer::{init_tim6_for_uart, init_tim7_for_uart},
    gpio_dma_uart_rx::rx_dma_task,
    debug::dump_tim6_regs,
};
use dma_gpio::config::{BAUD, RX_OVERSAMPLE, TX_OVERSAMPLE};
use dma_gpio::config::{TX_RING_BYTES, RX_RING_BYTES};
use dma_gpio::software_uart::gpio_dma_uart_tx::tx_dma_task;
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, PIPE_SW_RX};
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>;
});

// Software uart
pub const TIM6_UP_REQ: Request = 4;
static SW_TX_RING: StaticCell<[u32; TX_RING_BYTES]> = StaticCell::new();
static SW_RX_RING: StaticCell<[u8; RX_RING_BYTES]> = StaticCell::new();

#[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();

    // Safe one-time init from StaticCell
    let sw_tx_ring: &mut [u32; TX_RING_BYTES] = SW_TX_RING.init([0; TX_RING_BYTES]);
    
    let bsrr_ptr = embassy_stm32::pac::GPIOB.bsrr().as_ptr() as *mut u32; // POZOR B REGISTER
    // let odr_ptr = embassy_stm32::pac::GPIOA.odr().as_ptr() as *mut u32; // NEEDS DECODE CHANGE
    spawner.spawn(tx_dma_task(p.GPDMA1_CH0, bsrr_ptr, sw_tx_ring, &PIPE_SW_TX).unwrap());
    // EDN OF SOFTWARE UART 


    let mut last_yield = Instant::now();
    let mut buf = [0u8; 32];
    let mut counter: u32 = 0;

    loop {
        info!("tick start");
        // Timer::after(Duration::from_millis(100)).await;
        // info!("tick end");

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

        Timer::after(Duration::from_secs(3)).await;
        // Also read any incoming data from SW RX pipe
        let n2 = PIPE_INT_RX.read(&mut buf).await;
        if n2 > 0 {
            info!("HW INT UART RX pipe: {:a}", &buf[..n2]);
        }

        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);
        }
    }
}
