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
except ImportError:
    build_trade_call = None


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


def _is_bullish_trigger(t):
    """Classify a trigger as bullish for master synthesis."""
    tt = t['type']
    if "support" 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['data'].get('new') == "BULLISH": return True
    return False


def _is_bearish_trigger(t):
    """Classify a trigger as bearish for master synthesis."""
    tt = t['type']
    if "resistance" 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['data'].get('new') == "BEARISH": 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."""
    if not bars_30m or len(bars_30m) < 5:
        return False, "Not enough 30m bars"
    
    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]
    prev_ema = ema_series[-2]
    
    # Check if the price touched the 5 EMA in the last 2 candles
    last_bar = bars_30m[-1]
    prev_bar = bars_30m[-2]
    
    touched_up = last_bar['low'] <= current_ema or prev_bar['low'] <= prev_ema
    touched_down = last_bar['high'] >= current_ema or prev_bar['high'] >= prev_ema
    
    slope_up = current_ema > prev_ema
    slope_down = current_ema < prev_ema
    
    if direction == "LONG":
        if touched_up and slope_up:
            return True, f"Touched 5 EMA and riding up ({current_ema:.0f})"
        if current_close > current_ema * 1.02:  # Overextended by 2%
            return False, f"Overextended from 5 EMA ({current_ema:.0f})"
    elif direction == "SHORT":
        if touched_down and slope_down:
            return True, f"Touched 5 EMA and riding down ({current_ema:.0f})"
        if current_close < current_ema * 0.98:
            return False, f"Overextended from 5 EMA ({current_ema:.0f})"
    
    return False, "Not touching 5 EMA"

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 50.0,
        "res_conv": curr['resistance_conviction'] if 'resistance_conviction' in curr.keys() else 50.0,
    }
    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 50.0,
        "res_conv": prev['resistance_conviction'] if 'resistance_conviction' in prev.keys() else 50.0,
    }

    # --- v1.30.5: STAND ASIDE OVERRIDE ---
    # If the trade call engine says "stand aside", Dinks speaks it immediately
    if build_trade_call:
        try:
            tc = build_trade_call("NIFTY")
            if tc.get("reason") == "stand_aside":
                msg = tc.get("message", "Bias is mixed, but do not take this trade. Stand aside.")
                
                # We insert this directly into the history to override normal trigger flow
                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(), "stand_aside_override", "{}", state['spot'],
                     "MAJOR", "FLAT", state['sup_conv'], state['res_conv'],
                     state['pcr'], vix, crude, footprint, msg),
                )
                conn.commit()
                print(f"🛑 DINKS STAND ASIDE: {msg}")
                # We can optionally return early here so it doesn't also print 5 other triggers
                # return 
        except Exception as e:
            print(f"[Dinks] Stand Aside check error: {e}")

    # --- 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:
        orb_bars = [b for b in bars if "T09:15" 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("⚠️ Could not find the 09:15 bar to calculate true ORB.")

    # --- v1.32.0: EMA 5 TOUCH & RIDE FILTER ---
    bars_30m = data_feed.get_nifty_30m_bars()
    ema5_status = None
    if bars_30m:
        # We need to determine the direction based on the triggers
        # For now, we'll check both and apply as a filter
        long_status, long_msg = check_ema5_ride(bars_30m, "LONG")
        short_status, short_msg = check_ema5_ride(bars_30m, "SHORT")
        print(f"[Dinks v2] 30m EMA5: Long={long_msg}, Short={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")

        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()
    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'],
    }

    # --- 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)]

    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": {}})

    if len(bulls) >= len(bears) and bulls:
        direction = "BULLISH"
        contrib_types = [t['type'] for t in bulls[:3]]
        target = int(state['spot'] + 150)
        stop = int(state['spot'] - 100)
        bias = "LONG"
    elif bears:
        direction = "BEARISH"
        contrib_types = [t['type'] for t in bears[:3]]
        target = int(state['spot'] - 150)
        stop = int(state['spot'] + 100)
        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.")
                direction = "NEUTRAL"
                bias = "FLAT"
    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
    )

    last = conn.execute(
        "SELECT sentence, fired_at FROM dinks_history WHERE trigger_type='master_verdict' ORDER BY id DESC LIMIT 1"
    ).fetchone()

    should_write = False
    if not last:
        should_write = True
    elif last['sentence'] != master_sentence:
        should_write = True
    else:
        try:
            from datetime import datetime as _dt
            last_dt = _dt.fromisoformat(last['fired_at'])
            if (now - last_dt).total_seconds() >= 900:
                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)
