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

use defmt::*;
use embassy_executor::Spawner;
use embassy_stm32::spi::{Config, Spi};
use embassy_stm32::gpio::{Level, Speed, Output};
use embassy_time::{Duration, Timer};
use {defmt_rtt as _, panic_probe as _};

#[embassy_executor::main]
async fn main(_spawner: Spawner) {
    info!("tititi");

    let p = embassy_stm32::init(Default::default());

    let mut spi = Spi::new_blocking(p.SPI1, p.PB3, p.PB5, p.PB4, Config::default());
    let mut cs = Output::new(p.PA4, Level::High, Speed::VeryHigh);

    cs.set_low();
    let _ = spi.blocking_write(&[0x01u8, 0x79u8]);
    cs.set_high();

    loop {
        let mut data = [0u8; 10];

        data[0] = 0xA4;
        cs.set_low();
        let result = spi.blocking_transfer_in_place(&mut data);
        cs.set_high();

        match result {
            Ok(_) => {
                let raw = &data[1..];

                // 1. Correct 24-bit Signed Conversion (Minimal change)
                let x = (((raw[0] as i32) << 24) | ((raw[1] as i32) << 16) | ((raw[2] as i32) << 8)) >> 8;
                let y = (((raw[3] as i32) << 24) | ((raw[4] as i32) << 16) | ((raw[5] as i32) << 8)) >> 8;
                let z = (((raw[6] as i32) << 24) | ((raw[7] as i32) << 16) | ((raw[8] as i32) << 8)) >> 8;

                // 2. Display in Relevant Decimal Format
                info!("X: {} Y: {} Z: {}", x, y, z);
            }
            Err(e) => error!("SPI error: {:?}", e),
        }

        Timer::after(Duration::from_millis(10)).await;
    }
}
