import numpy as np


# =====================================================================
#  MF STATS (Buy/Sell Ratio Extractor)
# =====================================================================
def calc_mf_stats(mf_raw):
    """
    Extracts Money Flow stats safely.
    Works with the structure from your logs:
    {'1': {'buy':..,'sell':..}, '5':.., '15':..}
    """
    if mf_raw is None:
        return {"buy": 0, "sell": 0, "buy_ratio": 0.5}

    try:
        buy = 0
        sell = 0

        for tf_data in mf_raw.values():
            buy += tf_data.get("buy", 0)
            sell += tf_data.get("sell", 0)

        total = buy + sell
        buy_ratio = buy / total if total > 0 else 0.5

        return {
            "buy": buy,
            "sell": sell,
            "buy_ratio": buy_ratio
        }

    except Exception:
        return {"buy": 0, "sell": 0, "buy_ratio": 0.5}



# =====================================================================
#  TREND SCORE — Boosted BUY_RATIO + WHALE
# =====================================================================
def calc_trend_score(
    smooth_ratio,
    buy_ratio,
    cvd_delta,
    whale_usd,
    f_mempool,
    f_fee,
    f_block
):
    """
    Calculates 10–90 trend score.
    Tuned using real-trade analysis.
    """

    if smooth_ratio is None or buy_ratio is None:
        return 50.0

    # CVD (scaled)
    cvd_term = max(-15, min(15, (cvd_delta / 20) * 15))

    # WHALE (boosted 25%)
    whale_term = max(-12.5, min(12.5, (whale_usd / 1_000_000) * 6.3))

    # BUY RATIO (strongest metric)
    buy_ratio_term = abs(buy_ratio - 0.5) * 90

    # Base score
    trend_base = (
        smooth_ratio * 25 +
        buy_ratio_term +
        cvd_term +
        whale_term
    )

    # On-chain multipliers
    trend_onchain = (
        (f_mempool * 10) +
        (f_fee * 4) +
        (f_block * 6)
    )

    final_score = trend_base + trend_onchain
    return max(10, min(90, final_score))
