#!/usr/bin/env python
import json
import sqlite3
from trade_targets import compute_targets_sl
import pandas as pd
import yfinance as yf
import math
from datetime import datetime, timezone, timedelta

IST = timezone(timedelta(hours=5, minutes=30))
DB_PATH = '/home/dinkstrade/pdmp/sentiment_history.db'
CACHE_FILE = '/home/dinkstrade/pdmp/atr_cache.json'

def init_db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS confluence_signals (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            scan_time TEXT,
            symbol TEXT,
            trend_1h INTEGER,
            trend_15m INTEGER,
            trend_3m INTEGER,
            status TEXT,
            message TEXT,
            strike REAL,
            entry_prem REAL,
            t1 REAL,
            t2 REAL,
            t3 REAL,
            sl REAL
        )
    ''')
    # Add columns if they don't exist (for existing table)
    cols = [r[1] for r in c.execute("PRAGMA table_info(confluence_signals)").fetchall()]
    for col in ['strike', 'entry_prem', 't1', 't2', 't3', 'sl']:
        if col not in cols:
            c.execute(f"ALTER TABLE confluence_signals ADD COLUMN {col} REAL")
    conn.commit()
    conn.close()

def get_atr(symbol):
    try:
        with open(CACHE_FILE, 'r') as f:
            cache = json.load(f)
            return float(cache.get(symbol, {}).get('atr', 0))
    except:
        return 0

def get_real_premium(strike, opt_type, symbol='NIFTY'):
    try:
        conn = sqlite3.connect('/home/dinkstrade/pdmp/raw_vault.db')
        c = conn.cursor()
        col = "call_ltp" if opt_type == "CALL" else "put_ltp"
        c.execute(f"""
            SELECT {col} FROM vault_option_chain
            WHERE strike = ? AND symbol = ? AND {col} IS NOT NULL AND {col} > 0
            ORDER BY snapshot_at DESC LIMIT 1
        """, (strike, symbol))
        res = c.fetchone()
        conn.close()
        return res[0] if res else None
    except Exception:
        return None

def check_supertrend(symbol, interval, atr_val):
    tickers = {'NIFTY': '^NSEI', 'BANKNIFTY': '^NSEBANK', 'SENSEX': '^BSESN'}
    ticker = tickers.get(symbol)
    if not ticker or atr_val <= 0: return None

    try:
        df = yf.download(ticker, period="5d", interval=interval, progress=False)
        if df.empty or len(df) < 5: return None
        
        brick = atr_val
        close = df['Close'].values.flatten()
        
        rClose = float(close[0])
        trend = 1
        
        for c_raw in close[1:]:
            c = float(c_raw)
            if trend == 1:
                if c >= rClose + brick:
                    rClose = rClose + (int((c - rClose) / brick) * brick)
                elif c <= rClose - 2 * brick:
                    rClose = rClose - (int((rClose - c) / brick) * brick)
                    trend = -1
            else:
                if c <= rClose - brick:
                    rClose = rClose - (int((rClose - c) / brick) * brick)
                elif c >= rClose + 2 * brick:
                    rClose = rClose + (int((c - rClose) / brick) * brick)
                    trend = 1
        return trend, float(close[-1])
    except Exception as e:
        print(f"Error on {symbol} {interval}: {e}")
        return None, None

def run_scan():
    init_db()
    now_dt = datetime.now(IST)

    import holiday_guard
    live, why = holiday_guard.is_market_live('confluence_engine')
    if not live:
        return

    now = now_dt.strftime('%Y-%m-%d %H:%M:%S')
    symbols = ['NIFTY', 'BANKNIFTY', 'SENSEX']
    
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    
    # Clear old signals for today
    # v2026-11-11: Removed DELETE — preserve history, rely on dedup insert

    # v2026-11-12: NIFTY Leader Proximity Check for BANKNIFTY/SENSEX
    nifty_block_buy = False
    nifty_block_sell = False

    for sym in symbols:
        atr = get_atr(sym)
        if atr == 0: continue

        # Before processing BANKNIFTY/SENSEX, check NIFTY's proximity to hard walls
        if sym in ('BANKNIFTY', 'SENSEX'):
            _n_row = c.execute("SELECT spot, resistance, resistance_conviction, support, support_conviction FROM intraday_levels_history WHERE symbol='NIFTY' ORDER BY snapshot_at DESC LIMIT 1").fetchone()
            if _n_row:
                _n_spot = _n_row[0]
                _n_res = _n_row[1]
                _n_res_conv = _n_row[2] or 0
                _n_sup = _n_row[3]
                _n_sup_conv = _n_row[4] or 0

                if _n_res and _n_res_conv >= 90 and (_n_res - _n_spot) <= 40:
                    nifty_block_buy = True
                if _n_sup and _n_sup_conv >= 90 and (_n_spot - _n_sup) <= 40:
                    nifty_block_sell = True
            
            if nifty_block_buy or nifty_block_sell:
                status = "WAITING"
                reason = "resistance" if nifty_block_buy else "support"
                msg = f"⚠️ NIFTY is within 40 pts of {reason} wall with 90%+ conviction. Do not trade {sym} into a correlated barrier."
                _last = c.execute("SELECT status, scan_time FROM confluence_signals WHERE symbol=? ORDER BY id DESC LIMIT 1", (sym,)).fetchone()
                _skip = False
                if _last:
                    try:
                        _last_dt = datetime.strptime(_last[1], '%Y-%m-%d %H:%M:%S')
                        _now_dt_parsed = datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
                        if _last[0] == status and (_now_dt_parsed - _last_dt).total_seconds() < 900:
                            _skip = True
                    except Exception:
                        pass
                if not _skip:
                    c.execute("INSERT INTO confluence_signals (scan_time, symbol, trend_1h, trend_15m, trend_3m, status, message) VALUES (?, ?, NULL, NULL, NULL, ?, ?)", (now, sym, status, msg))
                continue

        # --- v1.41.1: OI Wall Filter ---
        # Read latest conviction from intraday_levels_history
        res_conv = 0
        sup_conv = 0
        try:
            _rc = c.execute("""SELECT resistance_conviction, support_conviction
                               FROM intraday_levels_history
                               WHERE symbol = ?
                               ORDER BY snapshot_at DESC LIMIT 1""", (sym,)).fetchone()
            if _rc:
                res_conv = float(_rc[0] or 0)
                sup_conv = float(_rc[1] or 0)
        except Exception as _e:
            print(f"[Confluence] OI conv fetch failed for {sym}: {_e}")
        
        # --- v2026-11-12: Expiry Day Gate ---
        _exp_today = False
        try:
            _vc = sqlite3.connect('/home/dinkstrade/pdmp/raw_vault.db')
            _today_str = now_dt.strftime('%Y-%m-%d')
            _exp_row = _vc.execute("SELECT MIN(expiry) FROM vault_option_chain WHERE symbol=? AND expiry >= ?", (sym, _today_str)).fetchone()
            _vc.close()
            if _exp_row and _exp_row[0] == _today_str:
                _exp_today = True
        except Exception as _ee:
            print(f"[Confluence] Expiry check failed for {sym}: {_ee}")

        if _exp_today:
            status = "EXPIRY_THETA_GATE"
            msg = "⏳ Expiry Day detected. Theta decay will crush premiums. Stand aside."
            _last = c.execute("SELECT status, scan_time FROM confluence_signals WHERE symbol=? ORDER BY id DESC LIMIT 1", (sym,)).fetchone()
            _skip = False
            if _last:
                try:
                    _last_dt = datetime.strptime(_last[1], '%Y-%m-%d %H:%M:%S')
                    _now_dt_parsed = datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
                    if _last[0] == status and (_now_dt_parsed - _last_dt).total_seconds() < 900:
                        _skip = True
                except Exception:
                    pass
            if not _skip:
                c.execute('''INSERT INTO confluence_signals (scan_time, symbol, trend_1h, trend_15m, trend_3m, status, message) VALUES (?, ?, NULL, NULL, NULL, ?, ?)''', (now, sym, status, msg))
            continue

        t_1h, spot_1h = check_supertrend(sym, '1h', atr)
        t_15m, _ = check_supertrend(sym, '15m', atr)
        t_5m, spot_5m = check_supertrend(sym, '5m', atr)
        
        if t_1h is not None and t_15m is not None and t_5m is not None:
            status = "WAITING"
            msg = "Timeframes not aligned."
            
            strike, entry, t1, t2, t3, sl = None, None, None, None, None, None
            
            if t_1h == 1 and t_15m == 1 and t_5m == 1:
                # v2026-11-12: Proximity Block (90% conviction AND within 40 pts)
                _res_level = None
                _res_row = c.execute("SELECT resistance FROM intraday_levels_history WHERE symbol=? ORDER BY snapshot_at DESC LIMIT 1", (sym,)).fetchone()
                if _res_row and _res_row[0]:
                    _res_level = _res_row[0]
                
                _block_buy = False
                if res_conv >= 90 and _res_level and spot_5m:
                    if (_res_level - spot_5m) <= 40:
                        _block_buy = True
                
                if _block_buy:
                    status = "WAITING"
                    msg = f"⚠️ Bullish confluence, but Resistance Conviction {res_conv:.0f}% blocks BUY. Stand aside."
                else:
                    status = "BULLISH_CONFLUENCE"
                    msg = "🚀 Macro Bullish. BUY setup active."
                
                    # Execution Logic
                    if spot_5m:
                        atm = math.ceil(spot_5m / 50) * 50
                        strike = atm - 100  # ITM Strike for Bullish
                        entry = get_real_premium(strike, "CALL", sym)
                        if entry:
                            tgts = compute_targets_sl(entry)
                            t1, t2, t3, sl = tgts["t1"], tgts["t2"], tgts["t3"], tgts["sl"]
                        
            elif t_1h == -1 and t_15m == -1 and t_5m == -1:
                # v2026-11-12: Proximity Block (90% conviction AND within 40 pts)
                _sup_level = None
                _sup_row = c.execute("SELECT support FROM intraday_levels_history WHERE symbol=? ORDER BY snapshot_at DESC LIMIT 1", (sym,)).fetchone()
                if _sup_row and _sup_row[0]:
                    _sup_level = _sup_row[0]
                
                _block_sell = False
                if sup_conv >= 90 and _sup_level and spot_5m:
                    if (spot_5m - _sup_level) <= 40:
                        _block_sell = True
                
                if _block_sell:
                    status = "WAITING"
                    msg = f"⚠️ Bearish confluence, but Support Conviction {sup_conv:.0f}% blocks SELL. Stand aside."
                else:
                    status = "BEARISH_CONFLUENCE"
                    msg = "🩸 Macro Bearish. SELL setup active."
                
                    if spot_5m:
                        atm = math.ceil(spot_5m / 50) * 50
                        strike = atm + 100  # ITM Strike for Bearish
                        entry = get_real_premium(strike, "PUT", sym)
                        if entry:
                            tgts = compute_targets_sl(entry)
                            t1, t2, t3, sl = tgts["t1"], tgts["t2"], tgts["t3"], tgts["sl"]
                

            # v2026-11-11: Dedup — skip if same status in last 15 min
            _last = c.execute("SELECT status, scan_time FROM confluence_signals WHERE symbol=? ORDER BY id DESC LIMIT 1", (sym,)).fetchone()
            _skip = False
            if _last:
                try:
                    from datetime import datetime as _dt
                    _last_dt = _dt.strptime(_last[1], '%Y-%m-%d %H:%M:%S')
                    _now_dt = _dt.strptime(now, '%Y-%m-%d %H:%M:%S')
                    if _last[0] == status and (_now_dt - _last_dt).total_seconds() < 900:
                        _skip = True
                except Exception:
                    pass
            if not _skip:
                c.execute('''
                    INSERT INTO confluence_signals 
                    (scan_time, symbol, trend_1h, trend_15m, trend_3m, status, message, strike, entry_prem, t1, t2, t3, sl)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ''', (now, sym, t_1h, t_15m, t_5m, status, msg, strike, entry, t1, t2, t3, sl))
            
    conn.commit()
    conn.close()
    print(f"[{now}] Confluence scan complete.")

if __name__ == '__main__':
    run_scan()