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

// BUY conditions
// (1) 1d MACD (3, 7, 30): MACD_current - Signal_current < 0, MACD_prev - Signal_prev < MACD_current - Signal_current
// (2) stoch RSI(30, 30, 2, 2): K_prev < 10, K_prev < K_current
// stoploss: (update) supertrend(10, 1.5) lowerband
// target price: (fixed) stoploss inverse x 3 times profit
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());
    }

    // 2nd filtering: 1d MACD (3, 7, 30) cross
    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?;
    let server_epoch = get_server_epoch().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.len() >= 30
                    && (macd_vec[macd_vec.len() - 1].macd_value
                        - macd_vec[macd_vec.len() - 1].signal_value)
                        .is_sign_negative()
                    && (macd_vec[macd_vec.len() - 2].macd_value
                        - macd_vec[macd_vec.len() - 2].signal_value)
                        .is_sign_negative()
                    && (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;

    // 1d StochRSI (RSI_len: 30, StochRSI_len: 30, K: 3, D: 3) K_prev < 10, K_prev < K_current
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let stoch_rsis = stoch_rsi(30, 30, 3, 3, &alldata.rt_price_1d_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if 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 stoch_rsi_vec.len() > 10
                && search_result.is_some_and(|a| {
                    stoch_rsi_vec[a - 3].k < 20.0
                        && stoch_rsi_vec[a - 2].k < 15.0
                        && stoch_rsi_vec[a - 1].k < 10.0
                        && stoch_rsi_vec[a - 1].k < stoch_rsi_vec[a].k
                        && stoch_rsi_vec[a].k < stoch_rsi_vec[a].d
                        && !stoch_rsi_vec[a].d.is_subnormal()
                        && stoch_rsi_vec[a].d > 0.00000001
                })
            {
            } 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: supertrend(ATR period 30, multiplier: 2.0, 1d close price) UP area
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let server_epoch = get_server_epoch().await;
    let supertrend_1d_map =
        supertrend(30, 2.0, true, &alldata.rt_price_1d_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if let (Some(supertrend_vec), Some(rt_price_vec)) = (
            supertrend_1d_map.get(symbol),
            alldata.rt_price_1d_vec.get(symbol),
        ) {
            if supertrend_vec.last().unwrap().close_time == rt_price_vec.last().unwrap().close_time
                && rt_price_vec.last().unwrap().close_time > server_epoch
            {
                if supertrend_vec.last().unwrap().area == SuperTrendArea::UP {
                } 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: supertrend(ATR period 14, multiplier: 1.2, 1d close price)
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let server_epoch = get_server_epoch().await;
    let supertrend_1d_map =
        supertrend(14, 1.2, true, &alldata.rt_price_1d_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if let (Some(supertrend_vec), Some(rt_price_vec)) = (
            supertrend_1d_map.get(symbol),
            alldata.rt_price_1d_vec.get(symbol),
        ) {
            if supertrend_vec.last().unwrap().close_time == rt_price_vec.last().unwrap().close_time
                && rt_price_vec.last().unwrap().close_time > server_epoch
            {
                // input stoploss, target_price
                let band_value: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(
                    supertrend_vec.last().unwrap().band_value,
                )
                .unwrap();
                if supertrend_vec.last().unwrap().area == SuperTrendArea::DOWN
                    && supertrend_vec.last().unwrap().band_value
                        > values.current_price.to_f64().unwrap()
                {
                    values.stoploss = decimal_sub(
                        values.current_price,
                        decimal_sub(band_value, values.current_price),
                    );
                    values.target_price = decimal_add(
                        decimal_mul(
                            decimal_sub(values.current_price, values.stoploss),
                            dec!(2.0),
                        ),
                        values.current_price,
                    );
                } else if supertrend_vec.last().unwrap().area == SuperTrendArea::UP
                    && supertrend_vec.last().unwrap().band_value
                        < values.current_price.to_f64().unwrap()
                {
                    values.stoploss = band_value;
                    values.target_price = decimal_add(
                        decimal_mul(
                            decimal_sub(values.current_price, values.stoploss),
                            dec!(2.0),
                        ),
                        values.current_price,
                    );
                } 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;

    // limit buy price: 3 * abs(이전 3 개 중 최대값 제거 한 opclo 값 평균 - 현재 open 값) + 현재 open 값 > current_price
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let server_epoch = get_server_epoch().await;
    for (symbol, values) in &mut filtered_data {
        if let Some(rt_price_vec) = alldata.rt_price_1d_vec.get(symbol) {
            if rt_price_vec.last().unwrap().close_time > server_epoch && rt_price_vec.len() >= 6 {
                let mut opclo_vec: Vec<f64> = Vec::new();
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 2].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 3].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 4].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 5].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 6].opclo_price);
                let max_idx = opclo_vec.iter().position(|&x| {
                    x == *opclo_vec
                        .iter()
                        .max_by(|&a, &b| a.partial_cmp(b).unwrap())
                        .unwrap()
                });
                opclo_vec.remove(max_idx.unwrap());

                let mut mean = 0.0;
                for element in &opclo_vec {
                    mean += element;
                }
                mean /= opclo_vec.len() as f64;
                let current_price = rt_price_vec.last().unwrap().close_price;
                let difference = (mean - rt_price_vec.last().unwrap().open_price).abs();

                if current_price < rt_price_vec.last().unwrap().open_price + (3.0 * difference) {
                } 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(6, &filtered_data).await?;
    insert_pre_suggested_coins(6, 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(6).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;
        let mut filtered_symbols: HashMap<String, FilteredDataValue> = HashMap::new();
        for element in &filled_buy_orders {
            filtered_symbols.insert(element.symbol.clone(), FilteredDataValue::new());
        }
        let supertrend_1d =
            supertrend(14, 1.2, true, &all_data.rt_price_1d_vec, &filtered_symbols).await?;
        for element in filled_buy_orders {
            let mut is_sell = false;
            let opclo_sample_length: usize = 15; // 15 candle samsples
            let mut target_profit_percent = 0.0;
            if let Some(price_1d_vec) = all_data.rt_price_1d_vec.get(&element.symbol) {
                let vec_len = price_1d_vec.len();
                if let Some(candles) =
                    price_1d_vec.get(vec_len - opclo_sample_length - 2..vec_len - 1)
                {
                    let windows = candles.windows(2);
                    let mut sum_amplitude_candles = 0.0;
                    let mut sum_ratio_amp_body = 0.0;
                    let mut average_amplitude = 0.0;

                    for window in windows {
                        sum_amplitude_candles += ((window.last().unwrap().high_price
                            - window.last().unwrap().low_price)
                            * 100.0)
                            / window.first().unwrap().close_price;
                    }
                    let average_amplitude = sum_amplitude_candles / opclo_sample_length as f64; // percent unit
                    let mut amplitude_variance = 0.0;

                    let windows = candles.windows(2);
                    for window in windows {
                        amplitude_variance += ((((window.last().unwrap().high_price
                            - window.last().unwrap().low_price)
                            * 100.0)
                            / window.first().unwrap().close_price)
                            - average_amplitude)
                            .powi(2);
                    }
                    amplitude_variance = amplitude_variance / (opclo_sample_length - 1) as f64;
                    let standard_deviation_amplitude = amplitude_variance.sqrt();
                    target_profit_percent =
                        average_amplitude + (standard_deviation_amplitude * 0.5);
                }
            }

            if element.used_usdt >= dec!(10.0) {
                if let (Some(exchange_info), Some(tradefee), Some(supertrend_vec)) = (
                    exchange_info_map.get(&element.symbol),
                    trade_fee_map.get(&element.symbol),
                    supertrend_1d.get(&element.symbol),
                ) {
                    // update stoploss
                    let band_value: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(
                        supertrend_vec.last().unwrap().band_value,
                    )
                    .unwrap();
                    if supertrend_vec.last().unwrap().area == SuperTrendArea::UP
                        && band_value > element.stoploss
                    {
                        let update_table_name = String::from("buy_ordered_coin_list");
                        let update_value = vec![(String::from("stoploss"), band_value.to_string())];
                        let update_condition = vec![(String::from("id"), element.id.to_string())];
                        update_record3(&update_table_name, &update_value, &update_condition)
                            .await
                            .unwrap();
                    }

                    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.stoploss {
                            is_sell = true;
                        } else if element.current_price >= element.target_price {
                            is_sell = true;
                        } else if (element.pure_profit_percent >= target_profit_percent * 2.5)
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive())
                        {
                            // absolute sell profit percent
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 5
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive()
                                && target_profit_percent * 2.0 <= element.pure_profit_percent)
                        {
                            // scaled selling with time up selling (5 days)
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 6
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive()
                                && target_profit_percent * 1.5 <= element.pure_profit_percent)
                        {
                            // scaled selling with time up selling (6 days)
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 7 {
                            // time up selling
                            is_sell = true;
                        }
                        // 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;
                        // }
                        if is_sell == true {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        }
                    }
                }
            }
        }
    }

    Ok(())
}
