// In buy_token function, replace these lines:
dict.set_item("quote", &serde_json::to_string(&quote_data)?)?;
dict.set_item("swap", &serde_json::to_string(&swap_data)?)?;

// With these:
dict.set_item("quote", &serde_json::to_string(&quote_data)
    .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Quote serialize error: {}", e)))?)?;
dict.set_item("swap", &serde_json::to_string(&swap_data)
    .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Swap serialize error: {}", e)))?)?;

// And in sell_token function, make the same changes:
dict.set_item("quote", &serde_json::to_string(&quote_data)
    .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Quote serialize error: {}", e)))?)?;
dict.set_item("swap", &serde_json::to_string(&swap_data)
    .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Swap serialize error: {}", e)))?)?; add these to this    use pyo3::prelude::*;
use pyo3::types::PyDict;
use solana_sdk::signature::{Keypair, Signer};
use serde::{Serialize, Deserialize};
use serde_json::Value;
use reqwest::blocking::Client;
use std::time::Duration;
use std::thread;
use std::sync::{Arc, Mutex};

#[derive(Serialize, Deserialize, Debug, Clone)]
struct MarketData {
    price: f64,
    volume_24h: f64,
    liquidity: f64,
    timestamp: i64,
    last_update_slot: u64,
}

#[pyclass]
struct TradingCore {
    keypair: Keypair,
    config: Value,
    http_client: Client,
    max_retries: u32,
    retry_delay: u64,
    market_data: Arc<Mutex<Option<MarketData>>>,
}

#[pymethods]
impl TradingCore {
    #[new]
    fn new(config_str: &str) -> PyResult<Self> {
        let config: Value = serde_json::from_str(config_str)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Config error: {}", e)))?;

        // Get keypair bytes from config
        let keypair_bytes = config["wallet"]["keypair_bytes"]
            .as_array()
            .ok_or_else(|| PyErr::new::<pyo3::exceptions::PyValueError, _>("Missing keypair bytes"))?
            .iter()
            .map(|v| v.as_u64().unwrap() as u8)
            .collect::<Vec<u8>>();

        let keypair = Keypair::from_bytes(&keypair_bytes)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Keypair error: {}", e)))?;

        let http_client = Client::builder()
            .timeout(Duration::from_secs(45))
            .pool_idle_timeout(Duration::from_secs(90))
            .pool_max_idle_per_host(32)
            .build()
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Client error: {}", e)))?;

        Ok(Self {
            keypair,
            config,
            http_client,
            max_retries: 3,
            retry_delay: 1000,
            market_data: Arc::new(Mutex::new(None)),
        })
    }

    fn get_price<'a>(&self, py: Python<'a>, token_mint: String) -> PyResult<&'a PyDict> {
        let dict = PyDict::new(py);
        let quote_url = format!(
            "{}?inputMint={}&outputMint=So11111111111111111111111111111111111111112&amount=1000000000&slippageBps=50",
            self.config["jupiter"]["quote_api"].as_str().unwrap(),
            token_mint,
        );

        let auth_header = format!("Bearer {}", self.config["rpc"]["quicknode"]["api_key"].as_str().unwrap());
        let mut retries = 0;

        while retries < self.max_retries {
            match self.http_client.get(&quote_url)
                .header("Authorization", &auth_header)
                .send() {
                    Ok(response) => {
                        if let Ok(quote) = response.json::<Value>() {
                            if let Some(price) = quote["data"]["price"].as_f64() {
                                dict.set_item("price", price)?;
                                return Ok(dict);
                            }
                        }
                    },
                    Err(_) => {}
                }

            retries += 1;
            thread::sleep(Duration::from_millis(self.retry_delay));
        }

        dict.set_item("price", 0.0)?;
        Ok(dict)
    }

    fn buy_token<'a>(&self, py: Python<'a>, token_mint: String, amount_sol: f64) -> PyResult<&'a PyDict> {
        let dict = PyDict::new(py);
        let priority_fee = self.config["trading"]["priority_fee"].as_u64().unwrap_or(50000);
        let auth_header = format!("Bearer {}", self.config["rpc"]["quicknode"]["api_key"].as_str().unwrap());
        
        let quote_url = format!(
            "{}?inputMint=So11111111111111111111111111111111111111112&outputMint={}&amount={}&slippageBps={}&priorityFee={}",
            self.config["jupiter"]["quote_api"].as_str().unwrap(),
            token_mint,
            (amount_sol * 1e9) as u64,
            self.config["jupiter"]["default_slippage_bps"].as_u64().unwrap_or(50),
            priority_fee
        );

        let quote_response = self.http_client.get(&quote_url)
            .header("Authorization", &auth_header)
            .send()
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Quote error: {}", e)))?;

        let quote_data = quote_response.json::<Value>()
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Quote parse error: {}", e)))?;

        let swap_url = self.config["jupiter"]["swap_api"].as_str().unwrap();
        let swap_response = self.http_client.post(swap_url)
            .header("Authorization", &auth_header)
            .json(&serde_json::json!({
                "quoteResponse": quote_data,
                "userPublicKey": self.keypair.pubkey().to_string(),
                "wrapUnwrapSOL": true
            }))
            .send()
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Swap error: {}", e)))?;

        let swap_data = swap_response.json::<Value>()
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Swap parse error: {}", e)))?;

        dict.set_item("status", "success")?;
        dict.set_item("quote", &serde_json::to_string(&quote_data)?)?;
        dict.set_item("swap", &serde_json::to_string(&swap_data)?)?;
        Ok(dict)
    }

    fn sell_token<'a>(&self, py: Python<'a>, token_mint: String, amount_tokens: f64) -> PyResult<&'a PyDict> {
        let dict = PyDict::new(py);
        let priority_fee = self.config["trading"]["priority_fee"].as_u64().unwrap_or(50000);
        let auth_header = format!("Bearer {}", self.config["rpc"]["quicknode"]["api_key"].as_str().unwrap());
        
        let quote_url = format!(
            "{}?inputMint={}&outputMint=So11111111111111111111111111111111111111112&amount={}&slippageBps={}&priorityFee={}",
            self.config["jupiter"]["quote_api"].as_str().unwrap(),
            token_mint,
            (amount_tokens * 1e9) as u64,
            self.config["jupiter"]["default_slippage_bps"].as_u64().unwrap_or(50),
            priority_fee
        );

        let quote_response = self.http_client.get(&quote_url)
            .header("Authorization", &auth_header)
            .send()
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Quote error: {}", e)))?;

        let quote_data = quote_response.json::<Value>()
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Quote parse error: {}", e)))?;

        let swap_url = self.config["jupiter"]["swap_api"].as_str().unwrap();
        let swap_response = self.http_client.post(swap_url)
            .header("Authorization", &auth_header)
            .json(&serde_json::json!({
                "quoteResponse": quote_data,
                "userPublicKey": self.keypair.pubkey().to_string(),
                "wrapUnwrapSOL": true
            }))
            .send()
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Swap error: {}", e)))?;

        let swap_data = swap_response.json::<Value>()
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Swap parse error: {}", e)))?;

        dict.set_item("status", "success")?;
        dict.set_item("quote", &serde_json::to_string(&quote_data)?)?;
        dict.set_item("swap", &serde_json::to_string(&swap_data)?)?;
        Ok(dict)
    }
}

#[pymodule]
fn solana_rust_bot(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<TradingCore>()?;
    Ok(())
}