import streamlit as st
import pandas as pd
from .polymarket_elon_tweets import get_market_trades, list_elon_tweet_markets, get_top_holders

@st.cache_data(ttl=120)
def analyze_smart_money_flow(condition_id: str, market_slug: str = "") -> dict:
    """Elon Smart Money Flow Engine — profitability-weighted volume + silent exit detection"""
    trades = get_market_trades(condition_id, limit=500)
    if trades.empty:
        return {"smfi": 0, "signal": "No data", "inflow_yes": 0, "outflow_no": 0}

    # All active Elon markets (for repeat-trader bonus)
    all_elon = list_elon_tweet_markets()
    elon_slugs = set(all_elon["slug"].tolist())

    # Group trades by user
    trades["volume_usd"] = trades["size"] * trades["price"]
    user_stats = trades.groupby("user").agg({
        "volume_usd": "sum",
        "side": lambda x: (x == "buy").sum() / len(x),   # % buys
        "time": ["min", "max"]
    }).reset_index()
    user_stats.columns = ["user", "total_volume", "buy_ratio", "first_trade", "last_trade"]

    # Smart Score = volume + repeat bonus + large trade factor
    user_stats["repeat_bonus"] = user_stats["user"].apply(
        lambda u: len([s for s in elon_slugs if s in market_slug]) * 0.5   # niche repeat bonus
    )
    user_stats["smart_score"] = user_stats["total_volume"] * (1 + user_stats["repeat_bonus"])

    # Weighted flows
    smart_trades = trades.merge(user_stats[["user", "smart_score"]], on="user")
    smart_trades["weighted_volume"] = smart_trades["volume_usd"] * (smart_trades["smart_score"] / smart_trades["smart_score"].sum())

    inflow_yes = smart_trades[(smart_trades["outcome"] == "Yes") & (smart_trades["side"] == "buy")]["weighted_volume"].sum()
    outflow_yes = smart_trades[(smart_trades["outcome"] == "Yes") & (smart_trades["side"] == "sell")]["weighted_volume"].sum()
    inflow_no = smart_trades[(smart_trades["outcome"] == "No") & (smart_trades["side"] == "buy")]["weighted_volume"].sum()
    outflow_no = smart_trades[(smart_trades["outcome"] == "No") & (smart_trades["side"] == "sell")]["weighted_volume"].sum()

    net_smfi = (inflow_yes + inflow_no) - (outflow_yes + outflow_no)
    silent_exit_risk = max(0, (outflow_yes + outflow_no) / (inflow_yes + inflow_no + 1)) * 100

    # Final signal
    if net_smfi > 50000:
        signal = "🚀 STRONG SMART INFLOW"
    elif net_smfi < -30000:
        signal = "⚠️ SILENT SMART EXIT"
    else:
        signal = "Neutral — watching"

    return {
        "smfi": round(net_smfi / 1000, 1),
        "signal": signal,
        "inflow_yes": round(inflow_yes / 1000, 1),
        "outflow_yes": round(outflow_yes / 1000, 1),
        "inflow_no": round(inflow_no / 1000, 1),
        "outflow_no": round(outflow_no / 1000, 1),
        "silent_exit_risk_%": round(silent_exit_risk, 1),
        "top_smart_traders": user_stats.nlargest(5, "smart_score")[["user", "total_volume", "smart_score"]].to_dict("records")
    }
