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

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

// BB lowerband + SuperTrend + StochRSI
// SuperTrend length: 20, multiplier: 1.5, BUY signal
// ADX(10, 10) < 25.0
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());
    }

    // 5th filtering: 0.5% <= the average amplitude of the latest 10 30m candles <= 1.0%
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    for (symbol, filtered_data) in &mut filtered_data {
        if let Some(rt_price_30m_vec) = alldata.rt_price_30m_vec.get(symbol) {
            let vec_len = rt_price_30m_vec.len();
            if vec_len >= 11 {
                let candles = rt_price_30m_vec.get(vec_len - 12..vec_len - 1).unwrap();
                let windows = candles.windows(2);
                let mut average_amplitude = 0.0;

                for window in windows {
                    average_amplitude += (window.last().unwrap().high_price
                        - window.last().unwrap().low_price)
                        / window.first().unwrap().close_price;
                }
                average_amplitude /= 10.0;

                if 0.005 <= average_amplitude && average_amplitude <= 0.01 {
                } 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;

    // 2nd filtering: BollingerBand (len:30, multiplier 3) previous_30m_price (close or low price) < lower_band
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let bollingerband_map =
        bollingerband(30, 3.0, &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(bb_vec), Some(rt_30m_vec)) = (
            bollingerband_map.get(symbol),
            alldata.rt_price_30m_vec.get(symbol),
        ) {
            if rt_30m_vec.len() >= 3
                && bb_vec.len() >= 3
                && rt_30m_vec.last().unwrap().close_time > server_epoch
            {
                let bb_search_result = bb_vec.binary_search_by_key(
                    &rt_30m_vec.last().unwrap().close_time,
                    |BollingerBandData {
                         sma,
                         upperband,
                         lowerband,
                         close_time,
                     }| *close_time,
                );
                if bb_search_result.is_ok() {
                    if bb_vec[bb_search_result.unwrap() - 1].lowerband
                        > rt_30m_vec[rt_30m_vec.len() - 2].low_price
                        && rt_30m_vec[rt_30m_vec.len() - 2].opclo_price
                            > rt_30m_vec.last().unwrap().close_price
                        && rt_30m_vec[rt_30m_vec.len() - 2].candle_type == CandleType::DOWN
                        && rt_30m_vec[rt_30m_vec.len() - 2].high_price
                            < bb_vec[bb_search_result.unwrap() - 1].sma
                    {
                        filtered_data.closetime = rt_30m_vec.last().unwrap().close_time;
                        filtered_data.current_price =
                            rust_decimal::prelude::FromPrimitive::from_f64(
                                rt_30m_vec.last().unwrap().close_price,
                            )
                            .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;

    // 3rd filtering: supertrend(ATR period 10, multiplier: 2, 30m close price), area should be DOWN
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let server_epoch = get_server_epoch().await;
    let supertrend_30m_map =
        supertrend(10, 2.0, true, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, filtered_data) in &mut filtered_data {
        if let (Some(supertrend_vec), Some(rt_30m_vec)) = (
            supertrend_30m_map.get(symbol),
            alldata.rt_price_30m_vec.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_and(|x| {
                    supertrend_vec[x].area == SuperTrendArea::DOWN
                        && supertrend_vec[x].band_value
                            > filtered_data.current_price.to_f64().unwrap()
                }) {
                    filtered_data.target_price = rust_decimal::prelude::FromPrimitive::from_f64(
                        supertrend_vec[supertrend_search_result.unwrap()].band_value,
                    )
                    .unwrap();
                    let stop_loss = decimal_sub(
                        filtered_data.current_price,
                        decimal_div(
                            decimal_sub(filtered_data.target_price, filtered_data.current_price),
                            dec!(2),
                        ),
                    );
                    filtered_data.stoploss = stop_loss;
                } 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;

    // 4th filtering: the latest 5 30m candle close prices > EMA 200
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let ema_map = ema(200, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, filtered_data) in &mut filtered_data {
        if let (Some(ema_vec), Some(rt_30m_vec)) =
            (ema_map.get(symbol), alldata.rt_price_30m_vec.get(symbol))
        {
            let search_result = ema_vec.binary_search_by_key(
                &rt_30m_vec.last().unwrap().close_time,
                |EmaData {
                     ema_value,
                     close_time,
                 }| *close_time,
            );
            if search_result.is_ok_and(|x| {
                ema_vec[search_result.unwrap()].ema_value
                    < rt_30m_vec[rt_30m_vec.len() - 1].close_price
            }) && search_result.is_ok_and(|x| {
                ema_vec[search_result.unwrap() - 1].ema_value
                    < rt_30m_vec[rt_30m_vec.len() - 2].close_price
            }) && search_result.is_ok_and(|x| {
                ema_vec[search_result.unwrap() - 2].ema_value
                    < rt_30m_vec[rt_30m_vec.len() - 3].close_price
            }) && search_result.is_ok_and(|x| {
                ema_vec[search_result.unwrap() - 3].ema_value
                    < rt_30m_vec[rt_30m_vec.len() - 4].close_price
            }) && search_result.is_ok_and(|x| {
                ema_vec[search_result.unwrap() - 4].ema_value
                    < rt_30m_vec[rt_30m_vec.len() - 5].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;

    // 6th filtering: 30m StochRSI (RSI_len: 10, StochRSI_len: 10, K: 3, D: 3) current K, D < 20
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let stoch_rsi_map = stoch_rsi(10, 10, 3, 3, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, filtered_data) in &mut filtered_data {
        if let Some(stoch_rsi_vec) = stoch_rsi_map.get(symbol) {
            let search_result = stoch_rsi_vec
                .iter()
                .position(|x| x.close_time == filtered_data.closetime);
            if search_result.is_some_and(|a| stoch_rsi_vec[a].k < 15.0 && stoch_rsi_vec[a].d < 15.0)
            {
            } 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(4, &filtered_data).await?;
    insert_pre_suggested_coins(4, 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(4).await?;

    if !filled_buy_orders.is_empty() {
        let client = ClientBuilder::new()
            .timeout(tokio::time::Duration::from_millis(5000))
            .build()
            .unwrap();
        let mut supertrend_vec: Vec<SupertrendData> = Vec::new();
        let server_epoch = get_server_epoch().await;
        for element in filled_buy_orders {
            if element.used_usdt >= dec!(10.0) {
                if let Some(exchange_info) = exchange_info_map.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,
                    );

                    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) * 20 {
                            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(())
}
