import sqlite3
import json
from datetime import datetime, timedelta
import pytz
import data_feed
import trigger_detectors
import sentence_builder
# v1.30.5: Import trade call builder to sync 'Stand Aside' state
try:
    from main import build_trade_call, get_crude_impact, collect_flash_alerts


except ImportError:
    build_trade_call = None



def _get_recent_flashes():
    """Fetches the most recent OI surge events directly from the DB for the last 15 minutes."""
    try:
        conn = sqlite3.connect(DB_PATH)
        c = conn.cursor()
        now = datetime.now(IST)
        cutoff = (now - timedelta(minutes=15)).isoformat()
        
        # Query for the loudest events in the last 15 mins
        rows = c.execute("""
            SELECT message, level FROM event_history 
            WHERE event_at >= ? AND event_type IN ('atm_put_surge', 'atm_call_surge', 'support_shift', 'resistance_shift')
            ORDER BY event_at DESC LIMIT 3
        """, (cutoff,)).fetchall()
        conn.close()
        
        if not rows:
            return "None"
        
        summary = []
        for r in rows:
            summary.append(f"[{r[1]}] {r[0]}")
        return " | ".join(summary)
    except Exception as e:
        print(f"[Dinks] Direct flash fetch error: {e}")
        return "None"

IST = pytz.timezone('Asia/Kolkata')
DB_PATH = '/home/dinkstrade/pdmp/sentiment_history.db'


def _is_bullish_trigger(t):
    tt = t['type']
    # v1.37.0: Strict mapping
    if tt == "BULLISH_OI_BIAS": return True
    if "support_conviction_building" in tt: return True
    if "support_conviction_hardened" in tt: return True
    if "put_wall" in tt: return True
    if "atm_put" in tt: return True
    if tt == "orb_breakout_up": return True
    if tt == "oi_bias_flip" and t.get('data', {}).get('new') == "BULLISH": return True
    # Support shift UP is bullish
    if tt == "support_shift" and t.get('data', {}).get('new', 0) > t.get('data', {}).get('old', 0): return True
    return False


def _is_bearish_trigger(t):
    tt = t['type']
    # v1.37.0: Strict mapping
    if tt == "BEARISH_OI_BIAS": return True
    if "support_conviction_fade" in tt: return True
    if "resistance_conviction_building" in tt: return True
    if "resistance_conviction_hardened" in tt: return True
    if "call_wall" in tt: return True
    if "atm_call" in tt: return True
    if tt == "orb_breakout_down": return True
    if tt == "oi_bias_flip" and t.get('data', {}).get('new') == "BEARISH": return True
    # Support shift DOWN is bearish
    if tt == "support_shift" and t.get('data', {}).get('new', 0) < t.get('data', {}).get('old', 0): return True
    # Resistance shift UP is bearish
    if tt == "resistance_shift" and t.get('data', {}).get('new', 0) > t.get('data', {}).get('old', 0): return True
    return False



def get_nearest_mtf_zones(spot):
    """Returns the nearest resistance and support from active MTF zones."""
    try:
        conn = sqlite3.connect(DB_PATH)
        conn.row_factory = sqlite3.Row
        res_row = conn.execute(
            "SELECT timeframe, bottom FROM mtf_zones WHERE is_active=1 AND zone_type='BEAR' AND bottom > ? ORDER BY bottom ASC LIMIT 1",
            (spot,)
        ).fetchone()
        sup_row = conn.execute(
            "SELECT timeframe, top FROM mtf_zones WHERE is_active=1 AND zone_type='BULL' AND top < ? ORDER BY top DESC LIMIT 1",
            (spot,)
        ).fetchone()
        conn.close()
        res_text = f"{res_row['timeframe']} at {int(res_row['bottom'])}" if res_row else "None"
        sup_text = f"{sup_row['timeframe']} at {int(sup_row['top'])}" if sup_row else "None"
        return {"resistance": res_text, "support": sup_text}
    except Exception as e:
        print(f"[MTF Query] Error: {e}")
        return {"resistance": "Unknown", "support": "Unknown"}



def get_shadow_levels(date_str=None):
    """Returns the most recent shadow levels: spot, CE, PE."""
    from datetime import datetime as _dt
    if not date_str:
        now = _dt.now(IST)
        # Weekend: look back to Friday
        if now.weekday() == 5:
            date_str = (now - timedelta(days=1)).strftime("%Y-%m-%d")
        elif now.weekday() == 6:
            date_str = (now - timedelta(days=2)).strftime("%Y-%m-%d")
        else:
            date_str = now.strftime("%Y-%m-%d")
    try:
        conn = sqlite3.connect(DB_PATH)
        conn.row_factory = sqlite3.Row
        rows = conn.execute(
            "SELECT type, strike, midpoint FROM shadow_levels WHERE date = ?",
            (date_str,)
        ).fetchall()
        conn.close()
        out = {"spot": None, "ce": None, "pe": None, "ce_strike": None, "pe_strike": None}
        for r in rows:
            if r["type"] == "SPOT":
                out["spot"] = r["midpoint"]
            elif r["type"] == "OPT_CE":
                out["ce"] = r["midpoint"]
                out["ce_strike"] = r["strike"]
            elif r["type"] == "OPT_PE":
                out["pe"] = r["midpoint"]
                out["pe_strike"] = r["strike"]
        return out
    except Exception as e:
        print(f"[Shadow Query] Error: {e}")
        return {"spot": None, "ce": None, "pe": None, "ce_strike": None, "pe_strike": None}




def check_ema5_ride(bars_30m, direction):
    """Returns (bool, str) — True if price is riding the 5 EMA, or status if overextended."""
    if not bars_30m or len(bars_30m) < 3:
        return False, "Not enough 30m bars to compute EMA5"
    
    closes = [b['close'] for b in bars_30m]
    # Calculate 5 EMA
    ema = closes[0]
    multiplier = 2 / (5 + 1)
    ema_series = [ema]
    for close in closes[1:]:
        ema = (close - ema) * multiplier + ema
        ema_series.append(ema)
    
    current_close = closes[-1]
    current_ema = ema_series[-1]
    
    # Calculate distance in points and percentage
    distance_pts = abs(current_close - current_ema)
    distance_pct = (distance_pts / current_ema) * 100
    
    if direction == "LONG":
        if current_close > current_ema:
            if distance_pct > 0.5: # Overextended (e.g. > 100 points on Nifty)
                return False, f"🚨 OVEREXTENDED: Price is {distance_pts:.0f} pts above 5 EMA ({current_ema:.0f}). Do not chase."
            else:
                return True, f"Price is riding just above 5 EMA ({current_ema:.0f})"
    elif direction == "SHORT":
        if current_close < current_ema:
            if distance_pct > 0.5:
                return False, f"🚨 OVEREXTENDED: Price is {distance_pts:.0f} pts below 5 EMA ({current_ema:.0f}). Do not chase."
            else:
                return True, f"Price is riding just below 5 EMA ({current_ema:.0f})"
    
    return False, f"Not touching 5 EMA ({current_ema:.0f})"


def get_nearby_zones(spot, radius_pts=60):
    """Fetch active MTF zones within radius_pts of Spot."""
    try:
        conn = sqlite3.connect(DB_PATH)
        conn.row_factory = sqlite3.Row
        rows = conn.execute("""
            SELECT timeframe, zone_type, top, bottom FROM mtf_zones
            WHERE is_active = 1 
              AND top >= ? AND bottom <= ?
            ORDER BY timeframe, zone_type
        """, (spot - radius_pts, spot + radius_pts)).fetchall()
        conn.close()
        
        zones = []
        for r in rows:
            zones.append({
                "tf": r['timeframe'],
                "type": r['zone_type'],
                "top": r['top'],
                "bottom": r['bottom'],
                "dist": round(min(abs(spot - r['top']), abs(spot - r['bottom'])), 1)
            })
        return zones
    except Exception as e:
        print(f"[Zones] Query error: {e}")
        return []


def get_close_momentum_context():
    """Calculates late-session price and OI changes (15:09 to 15:42)."""
    try:
        # 1. Price Delta
        i_conn = sqlite3.connect(DB_PATH)
        i_conn.row_factory = sqlite3.Row
        # Dynamically find the most recent 15:xx (or late session) data
        last_date = i_conn.execute("SELECT MAX(date(snapshot_at)) FROM intraday_levels_history WHERE symbol='NIFTY' AND date(snapshot_at) < date('now')").fetchone()[0]
        if not last_date:
            return {'price_delta': 0, 'oi_drop': 0}
        p_rows = i_conn.execute(
            "SELECT snapshot_at, spot FROM intraday_levels_history WHERE symbol='NIFTY' AND snapshot_at LIKE ? ORDER BY snapshot_at ASC", (f'{last_date} 15:%',)
        ).fetchall()
        i_conn.close()
        
        price_delta = 0
        if len(p_rows) >= 2:
            # Find first > 15:08 and last < 15:45
            start_spot = next((r['spot'] for r in p_rows if '15:09' in r['snapshot_at'] or '15:12' in r['snapshot_at']), None)
            end_spot = p_rows[-1]['spot'] if p_rows else None
            if start_spot and end_spot:
                price_delta = end_spot - start_spot

        # 2. OI Delta (Vault)
        v_conn = sqlite3.connect('/home/dinkstrade/pdmp/raw_vault.db')
        # Get exact closest timestamps
        times = [r[0] for r in v_conn.execute("SELECT DISTINCT snapshot_at FROM vault_option_chain WHERE symbol='NIFTY' AND snapshot_at >= ? AND snapshot_at <= ? ORDER BY snapshot_at ASC", (f'{last_date} 15:00', f'{last_date} 15:45')).fetchall()]
        v_conn.close()
        
        oi_drop = 0
        if len(times) >= 2:
            t_start, t_end = times[0], times[-1]
            v_conn = sqlite3.connect('/home/dinkstrade/pdmp/raw_vault.db')
            oi_start = v_conn.execute("SELECT SUM(call_oi) + SUM(put_oi) FROM vault_option_chain WHERE symbol='NIFTY' AND snapshot_at=?", (t_start,)).fetchone()[0] or 0
            oi_end = v_conn.execute("SELECT SUM(call_oi) + SUM(put_oi) FROM vault_option_chain WHERE symbol='NIFTY' AND snapshot_at=?", (t_end,)).fetchone()[0] or 0
            v_conn.close()
            oi_drop = oi_start - oi_end

        return {"price_delta": round(price_delta, 2), "oi_drop": oi_drop}
    except Exception as e:
        print(f"[Close Momentum] Error: {e}")
        return {"price_delta": 0, "oi_drop": 0}

def run(force=False):
    now = datetime.now(IST)
    if now.weekday() >= 5 and not force:
        print("Weekend: Skipping Dinks scan. Use --force to test.")
        return

    if not force:
        m = now.hour * 60 + now.minute
        # Updated to 09:00 - 16:00
        if m < (9 * 60) or m > (16 * 60):
            return

    print(f"[Dinks v2] Running at {now.strftime('%H:%M:%S')}")

    # --- Fetch fresh data ---
    bar_data = data_feed.get_nifty_bars(15)
    bars = bar_data.get('data', [])
    vix = data_feed.get_vix()
    crude = data_feed.get_crude()
    footprint = data_feed.get_footprint_delta()
    vwap = data_feed.get_vwap()
    print(f"[Dinks v2] bars={len(bars)} src={bar_data.get('source')} "
          f"vix={vix} crude={crude} footprint={footprint} vwap={vwap}")

    # --- Read current + previous state ---
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    rows = conn.execute(
        "SELECT * FROM intraday_levels_history WHERE symbol='NIFTY' "
        "ORDER BY snapshot_at DESC LIMIT 2"
    ).fetchall()
    if len(rows) < 2:
        print("Not enough intraday_levels_history rows to compare.")
        conn.close()
        return

    curr, prev = rows[0], rows[1]

    state = {
        "spot": curr['spot'] or 0,
        "support": curr['support'],
        "resistance": curr['resistance'],
        "pcr": curr['pcr'],
        "oi_bias": curr['net_bias_label'],
        "oi_score": curr['net_bias_score'],
        "sup_conv": curr['support_conviction'] if 'support_conviction' in curr.keys() else None,  # P0.3: do not fabricate conviction
        "res_conv": curr['resistance_conviction'] if 'resistance_conviction' in curr.keys() else None,  # P0.3: do not fabricate conviction
    }
    prev_state = {
        "support": prev['support'],
        "resistance": prev['resistance'],
        "oi_bias": prev['net_bias_label'],
        "oi_score": prev['net_bias_score'],
        "sup_conv": prev['support_conviction'] if 'support_conviction' in prev.keys() else None,  # P0.3: do not fabricate conviction
        "res_conv": prev['resistance_conviction'] if 'resistance_conviction' in prev.keys() else None,  # P0.3: do not fabricate conviction
    }


    # --- v1.44.0: Spot Indicators (per Pine Script spec) ---
    # 200 EMA High = 2-min bars, source high
    # 200 EMA Low  = 2-min bars, source low
    # Band color   = red (close < low) / green (close > high) / yellow (inside band)
    # 5 EMA        = 30-min bars, source close
    # 20 EMA       = 5-min bars, source close
    # Gap 50%      = (prev close + today open) / 2
    import yfinance as yf
    try:
        nifty_ticker = yf.Ticker("^NSEI")

        df_2m = nifty_ticker.history(period="5d", interval="2m")
        if not df_2m.empty and len(df_2m) >= 200:
            ema200_high = float(df_2m['High'].ewm(span=200, adjust=False).mean().iloc[-1])
            ema200_low  = float(df_2m['Low'].ewm(span=200, adjust=False).mean().iloc[-1])
            last_close_2m = float(df_2m['Close'].iloc[-1])
            if last_close_2m < ema200_low:
                ema_band_color = "red"
                ema_band_note = f"BELOW 200 EMA band (bearish) — low {ema200_low:.1f}"
            elif last_close_2m > ema200_high:
                ema_band_color = "green"
                ema_band_note = f"ABOVE 200 EMA band (bullish) — high {ema200_high:.1f}"
            else:
                ema_band_color = "yellow"
                ema_band_note = f"INSIDE 200 EMA band (neutral) — {ema200_low:.1f} to {ema200_high:.1f}"
        else:
            ema200_high = ema200_low = None
            ema_band_color = "unknown"
            ema_band_note = "Insufficient 2-min bars for 200 EMA"

        df_30m = nifty_ticker.history(period="60d", interval="30m")
        ema5_30m = float(df_30m['Close'].ewm(span=5, adjust=False).mean().iloc[-1]) if len(df_30m) >= 5 else None

        df_5m = nifty_ticker.history(period="5d", interval="5m")
        ema20_5m = float(df_5m['Close'].ewm(span=20, adjust=False).mean().iloc[-1]) if len(df_5m) >= 20 else None

        df_1d = nifty_ticker.history(period="10d", interval="1d")
        if not df_1d.empty and len(df_1d) >= 2:
            prev_close = float(df_1d['Close'].iloc[-2])
            today_open = float(df_1d['Open'].iloc[-1])
            gap_50 = round((prev_close + today_open) / 2, 2)
            today_high = float(df_1d['High'].iloc[-1])
            today_low  = float(df_1d['Low'].iloc[-1])
        else:
            gap_50 = today_high = today_low = prev_close = None

        spot_indicators = {
            "ema200_high": round(ema200_high, 2) if ema200_high else None,
            "ema200_low":  round(ema200_low, 2)  if ema200_low  else None,
            "ema_band_color": ema_band_color,
            "ema_band_note": ema_band_note,
            "ema5_30m": round(ema5_30m, 2) if ema5_30m else None,
            "ema20_5m": round(ema20_5m, 2) if ema20_5m else None,
            "gap_50": gap_50,
            "today_high": today_high,
            "today_low": today_low,
            "prev_close": prev_close,
        }
        print(f"[Dinks v2] Spot: {ema_band_note} | 5EMA(30m)={ema5_30m} | 20EMA(5m)={ema20_5m} | Gap50={gap_50}")
    except Exception as e:
        print(f"[Dinks v2] Error fetching Spot indicators: {e}")
        spot_indicators = {}

    # v1.40.0: Fetch nearby MTF zones
    nearby_zones = get_nearby_zones(state['spot'], radius_pts=60)
    if nearby_zones:
        print(f"[Dinks v2] {len(nearby_zones)} zone(s) near spot {state['spot']}")
        for z in nearby_zones:
            print(f"  {z['tf']} {z['type']}: {z['bottom']}-{z['top']} (dist {z['dist']} pts)")
    
    # --- v1.30.5: STAND ASIDE OVERRIDE (Modified) ---
    # If the trade call engine says "stand aside", we DO NOT return early.
    # We let Dinks generate the sentence via LLM, but flag it as a stand-aside context.
    stand_aside_reason = None
    if build_trade_call:
        try:
            tc = build_trade_call("NIFTY")
            if tc.get("reason") == "stand_aside":
                stand_aside_reason = tc.get("message", "Market is range-locked.")
        except Exception as e:
            print(f"[Dinks] Stand Aside check error: {e}")

    # P0.3: Bail if conviction columns are missing (do not fabricate 50%)
    if state.get("sup_conv") is None or state.get("res_conv") is None:
        print("[Dinks] FATAL: conviction columns missing from intraday_levels_history. Aborting.")
        conn.close()
        return

    # --- Detect triggers ---
    triggers = []

    triggers.extend(trigger_detectors.detect_sr_shift(
        state['support'], prev_state['support'],
        state['resistance'], prev_state['resistance'],
    ))

    triggers.extend(trigger_detectors.detect_conviction(
        state['sup_conv'], prev_state['sup_conv'],
        state['res_conv'], prev_state['res_conv'],
        curr_sup_strike=state['support'],
        curr_res_strike=state['resistance'],
    ))

    triggers.extend(trigger_detectors.detect_oi(
        state['oi_bias'], prev_state['oi_bias'],
        state['oi_score'], prev_state['oi_score'],
    ))

    triggers.extend(trigger_detectors.detect_wall_shifts(
        curr['top_call_oi_strike'], prev['top_call_oi_strike'],
        curr['top_put_oi_strike'], prev['top_put_oi_strike']
    ))

    triggers.extend(trigger_detectors.detect_atm_surges(
        curr['atm_0_put_coi'], prev['atm_0_put_coi'],
        curr['atm_0_call_coi'], prev['atm_0_call_coi'],
        curr['atm_strike']
    ))

    if bars:
        today_str = now.strftime('%Y-%m-%d')
        orb_bars = [b for b in bars if "T09:15" in b['time'] and today_str in b['time']]
        if orb_bars:
            orb_high = orb_bars[0]['high']
            orb_low = orb_bars[0]['low']
            triggers.extend(trigger_detectors.detect_orb(bars, orb_high, orb_low))
        else:
            print(f"⚠️ Could not find today's ({today_str}) 09:15 bar to calculate true ORB.")

    # --- v1.32.0: EMA 5 TOUCH & RIDE FILTER ---
    bars_30m = data_feed.get_nifty_30m_bars()
    ema5_long_msg = "Not checked"
    ema5_short_msg = "Not checked"
    if bars_30m:
        long_status, ema5_long_msg = check_ema5_ride(bars_30m, "LONG")
        short_status, ema5_short_msg = check_ema5_ride(bars_30m, "SHORT")
        print(f"[Dinks v2] 30m EMA5: Long={ema5_long_msg}, Short={ema5_short_msg}")

    # --- Build sentences and write rows (state-aware) ---
    fired = 0
    fired_keys = set()
    fires_this_tick = []

    for t in triggers:
        trigger_key = t['type']

        # v1.30.6: Stand Aside always fires, bypassing the state gate
        if trigger_key == "stand_aside_override":
            pass
        else:
            row = conn.execute(
                "SELECT is_active FROM dinks_state WHERE trigger_key = ?",
                (trigger_key,)
            ).fetchone()
            already_active = bool(row and row['is_active'] == 1)

            if already_active:
                fired_keys.add(trigger_key)
                continue

        mtf = get_nearest_mtf_zones(state['spot'])
        shadow = get_shadow_levels()
        ctx = {
            "pcr": state['pcr'],
            "vix": vix,
            "support": state['support'],
            "resistance": state['resistance'],
            "oi_bias": state['oi_bias'],
            "vwap": vwap,
            "mtf_resistance": mtf['resistance'],
            "mtf_support": mtf['support'],
            "shadow_spot": shadow['spot'],
            "shadow_ce": shadow['ce'],
            "shadow_pe": shadow['pe'],
            "shadow_ce_strike": shadow['ce_strike'],
            "shadow_pe_strike": shadow['pe_strike']
        }
        sentence = sentence_builder.build_sentence(t, ctx, state['spot'])

        bias = "LONG" if "support" in t['type'] else (
               "SHORT" if "resistance" in t['type'] else "FLAT")

        # v1.32.5: Confidence Gate
        # Before writing to the drawer, check if the resulting trade call is high confidence.
        confidence_ok = True
        if build_trade_call:
            try:
                tc = build_trade_call("NIFTY")
                # If the trade call says available=False or confidence < 60, skip this trigger
                if not tc.get("available") and tc.get("confidence") is not None and tc.get("confidence") < 60:
                    print(f"[Dinks] Suppressing trigger {t['type']} (low confidence: {tc.get('confidence')}%)")
                    confidence_ok = False
            except Exception as e:
                pass

        if not confidence_ok:
            continue

        conn.execute(
            """INSERT INTO dinks_history
               (fired_at, trigger_type, trigger_payload_json, spot, tier, bias,
                conviction_support, conviction_resistance, pcr, vix,
                crude_change_pct, footprint_delta, sentence)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
            (now.isoformat(), t['type'], json.dumps(t['data']), state['spot'],
             t['tier'], bias, state['sup_conv'], state['res_conv'],
             state['pcr'], vix, crude, footprint, sentence),
        )

        conn.execute(
            """INSERT OR REPLACE INTO dinks_state
               (trigger_key, last_fired_at, is_active, state_payload)
               VALUES (?, ?, 1, ?)""",
            (trigger_key, now.isoformat(), json.dumps(t['data'])),
        )

        fires_this_tick.append(t)
        fired_keys.add(trigger_key)
        fired += 1
        print(f"🔔 FIRED: [{t['tier']}] {sentence}")

    # --- v1.31.1: Build ctx ONCE before the always-on verdict ---
    # (Previously ctx was built per-trigger inside the loop; now it's built once
    #  so build_master_sentence can use it even when no triggers fired.)
    mtf = get_nearest_mtf_zones(state['spot'])
    shadow = get_shadow_levels()
    # v1.32.0: Fetch macro context for the Genie
    try:
        macro_data = get_crude_impact()
        crude_trend = macro_data.get("primary_trend", "flat")
        crude_change = macro_data.get("wti", {}).get("change_pct", 0.0)
    except Exception as e:
        print(f"[Dinks] Macro fetch error: {e}")
        crude_trend = "unknown"
        crude_change = 0.0

    # --- v1.41.0: Heavyweight Momentum + Overnight Gap Context ---
    heavyweight_moves = {}
    overnight_gap = 0.0
    try:
        import yfinance as _yf
        for _sym, _name in [("RELIANCE.NS", "Reliance"), ("HDFCBANK.NS", "HDFC Bank"), ("ICICIBANK.NS", "ICICI Bank")]:
            try:
                _h = _yf.Ticker(_sym).history(period="2d")
                if len(_h) >= 2:
                    import pandas as pd
                    _last = _h['Close'].iloc[-1]
                    _prev = _h['Close'].iloc[-2]
                    if pd.notna(_last) and pd.notna(_prev) and _prev > 0:
                        _chg = ((_last - _prev) / _prev) * 100
                        heavyweight_moves[_name] = round(_chg, 2)
            except Exception:
                pass
        # Overnight gap: today's open vs yesterday's close on Nifty
        _n = _yf.Ticker("^NSEI").history(period="2d")
        if len(_n) >= 2:
            overnight_gap = round(((float(_n['Open'].iloc[-1]) - float(_n['Close'].iloc[-2])) / float(_n['Close'].iloc[-2])) * 100, 2)
    except Exception as _e:
        print(f"[Dinks] Heavyweight fetch error: {_e}")

    ctx = {
        "pcr": state['pcr'],
        "vix": vix,
        "support": state['support'],
        "support_oi_total": curr['support_oi'],
        "resistance": state['resistance'],
        "resistance_oi_total": curr['resistance_oi'],
        "max_pain": curr['max_pain'],
        "atm": curr['atm'],
        "oi_bias": state['oi_bias'],
        "vwap": vwap,
        "crude_trend": crude_trend,
        "crude_change": crude_change,
        "mtf_resistance": mtf['resistance'],
        "mtf_support": mtf['support'],
        "shadow_spot": shadow['spot'],
        "shadow_ce": shadow['ce'],
        "shadow_pe": shadow['pe'],
        "shadow_ce_strike": shadow['ce_strike'],
        "shadow_pe_strike": shadow['pe_strike'],
        "nearby_zones": nearby_zones,
        "spot_indicators": spot_indicators,
        "heavyweight_moves": heavyweight_moves,
        "overnight_gap_pct": overnight_gap,
        "close_momentum": get_close_momentum_context(),
    }

    # --- v1.31.0: ALWAYS-ON VERDICT (change-gated + 15-min refresh) ---
    bulls = [t for t in fires_this_tick if _is_bullish_trigger(t)]
    bears = [t for t in fires_this_tick if _is_bearish_trigger(t)]

    # v1.38.0: If no new triggers, check the last 15 mins of dinks_history for a recent bias
    if not bulls and not bears:
        cutoff_15m = (now - timedelta(minutes=15)).isoformat()
        recent_triggers = conn.execute(
            "SELECT trigger_type FROM dinks_history WHERE fired_at >= ? AND trigger_type NOT IN ('master_verdict', 'stand_aside_override')",
            (cutoff_15m,)
        ).fetchall()
        
        for r in recent_triggers:
            tt = r['trigger_type']
            # We create a dummy trigger dict just for classification
            t_dict = {"type": tt, "data": {}}
            if _is_bullish_trigger(t_dict):
                bulls.append(t_dict)
            elif _is_bearish_trigger(t_dict):
                bears.append(t_dict)

    if not bulls and not bears:
        if state['oi_bias'] == "BULLISH":
            bulls.append({"type": "BULLISH_OI_BIAS", "data": {}})
        elif state['oi_bias'] == "BEARISH":
            bears.append({"type": "BEARISH_OI_BIAS", "data": {}})

    # v1.37.1: Tie-breaker logic. If bulls exist and no bears, it's BULLISH.
    if bulls and not bears:
        direction = "BULLISH"
        contrib_types = [t['type'] for t in bulls[:3]]
        target = int(state['spot'] + 80)
        stop = int(state['spot'] - 40)
        bias = "LONG"
    elif bears and not bulls:
        direction = "BEARISH"
        contrib_types = [t['type'] for t in bears[:3]]
        target = int(state['spot'] - 80)
        stop = int(state['spot'] + 40)
        bias = "SHORT"
    elif len(bulls) > len(bears):
        direction = "BULLISH"
        contrib_types = [t['type'] for t in bulls[:3]]
        target = int(state['spot'] + 80)
        stop = int(state['spot'] - 40)
        bias = "LONG"
    elif len(bears) > len(bulls):
        direction = "BEARISH"
        contrib_types = [t['type'] for t in bears[:3]]
        target = int(state['spot'] - 80)
        stop = int(state['spot'] + 40)
        bias = "SHORT"
    else:
        direction = "NEUTRAL"
        contrib_types = ["balanced_signals"]
        target = state['spot']
        stop = state['spot']
        bias = "FLAT"

    stand_aside_reason = None
    try:
        if build_trade_call:
            tc = build_trade_call("NIFTY")
            if tc.get("reason") == "stand_aside":
                stand_aside_reason = tc.get("message", "Market is range-locked with poor R:R.")
                # v1.36.9: Do NOT force direction to NEUTRAL. Let LLM decide based on context.
    except Exception as e:
        print(f"[Dinks] stand_aside check failed: {e}")

    master_sentence = sentence_builder.build_master_sentence(
        direction, contrib_types, ctx, state['spot'], target, stop,
        stand_aside_reason=stand_aside_reason
    )

    # v1.31.2: Dedup based on state change (direction/stand-aside), NOT exact text match
    # This prevents Groq's slight wording variations from spamming the drawer.
    last_state = conn.execute(
        "SELECT trigger_payload_json, fired_at FROM dinks_history WHERE trigger_type='master_verdict' ORDER BY id DESC LIMIT 1"
    ).fetchone()

    current_state_payload = json.dumps({"direction": direction, "stand_aside": bool(stand_aside_reason)})
    
    should_write = False
    if not last_state:
        should_write = True
    elif last_state['trigger_payload_json'] != current_state_payload:
        should_write = True
    else:
        try:
            from datetime import datetime as _dt
            last_dt = _dt.fromisoformat(last_state['fired_at'])
            # v: force bypasses 30-min dedup only after 15:50 IST
            force_late = force and (now.hour * 60 + now.minute) >= (15 * 60 + 50)
            # Only write the identical verdict again if it's been 30 minutes
            if force_late or (now - last_dt).total_seconds() >= 1800:
                should_write = True
        except Exception:
            should_write = True

    if should_write:
        conn.execute(
            """INSERT INTO dinks_history
               (fired_at, trigger_type, trigger_payload_json, spot, tier, bias,
                conviction_support, conviction_resistance, pcr, vix,
                crude_change_pct, footprint_delta, sentence)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
            (now.isoformat(), "master_verdict",
             json.dumps({"reasons": contrib_types, "direction": direction, "stand_aside": bool(stand_aside_reason)}),
             state['spot'], "IMPORTANT" if not stand_aside_reason else "MAJOR",
             bias, state['sup_conv'], state['res_conv'],
             state['pcr'], vix, crude, footprint, master_sentence),
        )
        print(f"👑 VERDICT: {master_sentence}")
    else:
        print(f"👑 VERDICT (unchanged, silent): {master_sentence[:80]}...")

    # --- Clear state for triggers that are no longer firing ---
    all_tracked = [r['trigger_key'] for r in conn.execute(
        "SELECT trigger_key FROM dinks_state WHERE is_active = 1"
    ).fetchall()]
    cleared = []
    for tk in all_tracked:
        if tk not in fired_keys:
            conn.execute(
                "UPDATE dinks_state SET is_active = 0 WHERE trigger_key = ?",
                (tk,)
            )
            cleared.append(tk)

    conn.commit()
    conn.close()

    if fired > 0:
        print(f"✅ {fired} event(s) written to dinks_history")
    if cleared:
        print(f"🔄 Reset: {len(cleared)} trigger(s) no longer active: {', '.join(cleared)}")
    if fired == 0 and not cleared:
        print("(no changes)")


if __name__ == "__main__":
    import sys
    run(force="--force" in sys.argv)
