use crate::value_estimation_team::indicators::bollingerband::bollingerband;

use super::{
    adx, dec, decimal_add, decimal_div, decimal_sub, duplicate_filter, ema, ema_macd, ema_opclo,
    exists_record, get_server_epoch, insert_pre_suggested_coins, limit_order_sell, remove_keys,
    rsi, select_filled_buy_orders, sma, sma_opclo, stoch_rsi, supertrend, try_join_all,
    update_record3, AdxData, AllData, Arc, BollingerBandData, Client, ClientBuilder, Decimal,
    EmaData, ExchangeInfo, FilteredDataValue, HashMap, HashSet, MacdData, Mutex, RealtimePriceData,
    RoundingStrategy, RsiData, SmaData, StochRsiData, SuperTrendArea, SuperTrendSignal,
    SupertrendData, ToPrimitive, TradeFee,
};

// BUY: 30m SMA5 (opclo_price) < 30m EMA3 (opclo_price)
// SELL: 30m SMA5 (opclo_price) > 30m EMA3 (opclo_price)
pub async fn list_up_for_buy(
    alldata: &AllData,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // print rt_price for debugging
    // let a = alldata.rt_price_30m_vec.iter().position(|a| a.0 == "BTCUSDT");
    // println!("BTCUSDT: {:?}", alldata.rt_price_30m_vec[a.unwrap()].1.last().unwrap());

    // 1st filtering: filtering valid trade pair
    let mut filtered_data: HashMap<String, FilteredDataValue> = HashMap::new();
    for symbol in &alldata.valid_symbol_vec {
        filtered_data.insert(symbol.clone(), FilteredDataValue::new());
    }

    // 3rd filtering: supertrend(ATR period 20, multiplier: 4.0, 30m close price), area should be UP
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let supertrend_30m_map =
        supertrend(20, 4.0, true, &alldata.rt_price_30m_vec, &filtered_data).await?;
    let server_epoch = get_server_epoch().await;
    for (symbol, filtered_data) in &mut filtered_data {
        if let (Some(rt_30m_vec), Some(supertrend_vec)) = (
            alldata.rt_price_30m_vec.get(symbol),
            supertrend_30m_map.get(symbol),
        ) {
            if rt_30m_vec.len() >= 3
                && supertrend_vec.len() >= 3
                && rt_30m_vec.last().unwrap().close_time > server_epoch
            {
                let supertrend_search_result = supertrend_vec.binary_search_by_key(
                    &rt_30m_vec.last().unwrap().close_time,
                    |SupertrendData {
                         band_value,
                         signal,
                         area,
                         close_time,
                     }| *close_time,
                );
                if supertrend_search_result.is_ok() {
                    if supertrend_vec[supertrend_search_result.unwrap()].area == SuperTrendArea::UP
                        && supertrend_vec[supertrend_search_result.unwrap()].band_value
                            < filtered_data.current_price.to_f64().unwrap()
                    {
                    } else {
                        keys_to_remove.insert(symbol.clone());
                    }
                } else {
                    keys_to_remove.insert(symbol.clone());
                }
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // 5th filtering: 30m StochRSI (RSI_len: 30, StochRSI_len: 30, K: 3, D: 3) previous K, D / current K, D < 10 && current K > current D
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let stoch_rsis = stoch_rsi(30, 30, 3, 3, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if alldata.rt_price_30m_vec.contains_key(symbol) && stoch_rsis.contains_key(symbol) {
            let stoch_rsi_vec = stoch_rsis.get(symbol).unwrap();
            let search_result = stoch_rsi_vec
                .iter()
                .position(|x| x.close_time == values.closetime);
            if search_result.is_some_and(|a| {
                stoch_rsi_vec[a - 1].k < 10.0
                    && stoch_rsi_vec[a].k < 10.0
                    && stoch_rsi_vec[a - 1].d < 10.0
                    && stoch_rsi_vec[a].d < 10.0
                    && stoch_rsi_vec[a - 1].k <= stoch_rsi_vec[a - 1].d
                    && stoch_rsi_vec[a].k > stoch_rsi_vec[a].d
            }) {
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // 3rd filtering: the latest 5 30m candle close prices > EMA 200
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let emas = ema(200, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if emas.contains_key(symbol) && alldata.rt_price_30m_vec.contains_key(symbol) {
            let ema = emas.get(symbol).unwrap();
            let rt_price_30m = alldata.rt_price_30m_vec.get(symbol).unwrap();
            let rt_price_30m_len = rt_price_30m.len();
            let search_result = ema.binary_search_by_key(
                &alldata
                    .rt_price_30m_vec
                    .get(symbol)
                    .unwrap()
                    .last()
                    .unwrap()
                    .close_time,
                |EmaData {
                     ema_value,
                     close_time,
                 }| *close_time,
            );
            if search_result.is_ok_and(|x| {
                ema[search_result.unwrap()].ema_value
                    < rt_price_30m[rt_price_30m_len - 1].close_price
            }) && search_result.is_ok_and(|x| {
                ema[search_result.unwrap() - 1].ema_value
                    < rt_price_30m[rt_price_30m_len - 2].close_price
            }) {
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // filtering: 1d MACD (3, 7, 30) current MACD-signal > prev MACD-signal
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let macd_1d_map = ema_macd(3, 7, 30, &alldata.rt_price_1d_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if let (Some(macd_vec), Some(rt_price_vec)) =
            (macd_1d_map.get(symbol), alldata.rt_price_1d_vec.get(symbol))
        {
            if macd_vec.last().unwrap().close_time == rt_price_vec.last().unwrap().close_time
                && rt_price_vec.last().unwrap().close_time > server_epoch
            {
                if macd_vec[macd_vec.len() - 1].macd_value
                    - macd_vec[macd_vec.len() - 1].signal_value
                    > macd_vec[macd_vec.len() - 2].macd_value
                        - macd_vec[macd_vec.len() - 2].signal_value
                {
                    values.current_price = rust_decimal::prelude::FromPrimitive::from_f64(
                        rt_price_vec.last().unwrap().close_price,
                    )
                    .unwrap();
                    values.closetime = rt_price_vec.last().unwrap().close_time;
                } else {
                    keys_to_remove.insert(symbol.clone());
                }
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    let final_filtered_data = duplicate_filter(3, &filtered_data).await?;
    insert_pre_suggested_coins(3, false, &final_filtered_data).await;

    Ok(())
}

pub async fn list_up_for_sell(
    all_data: &AllData,
    exchange_info_map: &HashMap<String, ExchangeInfo>,
    trade_fee_map: &HashMap<String, TradeFee>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let filled_buy_orders = select_filled_buy_orders(3).await?;

    if !filled_buy_orders.is_empty() {
        let client = ClientBuilder::new()
            .timeout(tokio::time::Duration::from_millis(5000))
            .build()
            .unwrap();
        let mut filtered_symbols: HashMap<String, FilteredDataValue> = HashMap::new();
        for element in &filled_buy_orders {
            filtered_symbols.insert(element.symbol.clone(), FilteredDataValue::new());
        }
        let server_epoch = get_server_epoch().await;
        let stoch_rsis =
            stoch_rsi(30, 30, 3, 3, &all_data.rt_price_30m_vec, &filtered_symbols).await?;
        for element in filled_buy_orders {
            if element.used_usdt >= dec!(10.0) {
                if let (Some(exchange_info), Some(stoch_rsi)) = (
                    exchange_info_map.get(&element.symbol),
                    stoch_rsis.get(&element.symbol),
                ) {
                    let lot_step_size = exchange_info.stepsize;
                    let quote_commission_precision = exchange_info.quote_commission_precision;
                    let base_qty_to_be_ordered = element.base_qty_ordered.round_dp_with_strategy(
                        lot_step_size.normalize().scale(),
                        RoundingStrategy::ToZero,
                    );
                    let stoch_rsi_k = stoch_rsi.last().unwrap().k;
                    let stoch_rsi_k_prev = stoch_rsi[stoch_rsi.len() - 2].k;
                    let stoch_rsi_d = stoch_rsi.last().unwrap().d;
                    let stoch_rsi_d_prev = stoch_rsi[stoch_rsi.len() - 2].d;

                    if (element.is_long == 0 || element.is_long == 1)
                        && !element.current_price.is_zero()
                    {
                        if element.current_price >= element.target_price {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        } else if element.current_price <= element.stoploss {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        } else if server_epoch - element.transact_time > (1_800_000) * 35 {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        } else if stoch_rsi_k >= 90.0 {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        } else if stoch_rsi_k >= 20.0
                            && stoch_rsi_k >= 20.0
                            && stoch_rsi_k_prev >= 20.0
                            && stoch_rsi_k_prev >= 20.0
                            && stoch_rsi_k < stoch_rsi_d
                            && stoch_rsi_k_prev >= stoch_rsi_d_prev
                        {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        }
                        // TODO: sell_count가 1일 때 적용하기
                        // else if (supertrend_vec
                        //     .last()
                        //     .unwrap()
                        //     .signal
                        //     .as_ref()
                        //     .is_some_and(|x| x.contains("SELL"))
                        //     || supertrend_vec.last().unwrap().area.contains("DOWN"))
                        //     && (supertrend_vec.last().unwrap().close_time > element.close_time)
                        // {
                        //     println!(
                        //         "SELL signal selling {} {:.2}",
                        //         element.symbol, element.pure_profit_percent
                        //     );
                        //     limit_order_sell(
                        //         &element,
                        //         element.current_price,
                        //         base_qty_to_be_ordered,
                        //         &client,
                        //         &exchange_info_vec,
                        //         &trade_fee_vec,
                        //     )
                        //     .await;
                        // }
                    }
                }
            }
        }
    }

    Ok(())
}
