import yfinance as yf

def check_1h_wick_alerts():
    """v1.46.0: Checks the last 2 candles on the 1H timeframe for wick formations."""
    import yfinance as yf
    from datetime import datetime
    import pytz
    IST = pytz.timezone('Asia/Kolkata')
    
    try:
        df = yf.Ticker("^NSEI").history(period="5d", interval="1h")
        if len(df) < 3:
            return
            
        pivot_candle = df.iloc[-2]
        current_candle = df.iloc[-1]
        
        pivot_low = pivot_candle['Low']
        pivot_high = pivot_candle['High']
        current_close = current_candle['Close']
        
        prev_low = df.iloc[-3]['Low']
        prev_high = df.iloc[-3]['High']
        
        # --- 1H BULL WICK ---
        if pivot_low < prev_low:
            msg = f"Potential 1H BULL Zone forming at {int(pivot_low)}. Watch for confirmation."
            _log_alert("zone_forming_1h", "IMPORTANT", msg)
            
            if current_close > pivot_high:
                msg = f"1H BULL Zone CONFIRMED at {int(pivot_low)}. High conviction Long setup."
                _log_alert("zone_confirmed_1h", "MAJOR", msg)
            elif current_close < pivot_low:
                msg = f"1H BULL Zone FAILED at {int(pivot_low)}. Ignore."
                _log_alert("zone_failed_1h", "SIGNAL", msg)

        # --- 1H BEAR WICK ---
        if pivot_high > prev_high:
            msg = f"Potential 1H BEAR Zone forming at {int(pivot_high)}. Watch for confirmation."
            _log_alert("zone_forming_1h", "IMPORTANT", msg)
            
            if current_close < pivot_low:
                msg = f"1H BEAR Zone CONFIRMED at {int(pivot_high)}. High conviction Short setup."
                _log_alert("zone_confirmed_1h", "MAJOR", msg)
            elif current_close > pivot_high:
                msg = f"1H BEAR Zone FAILED at {int(pivot_high)}. Ignore."
                _log_alert("zone_failed_1h", "SIGNAL", msg)
                
    except Exception as e:
        print(f"[1H Wick Alert Error] {e}")

def check_wick_alerts():
    """v1.45.0: Checks the last 2 candles for wick formations and confirms/invalidates zones."""
    import yfinance as yf
    from datetime import datetime
    import pytz
    IST = pytz.timezone('Asia/Kolkata')
    
    try:
        df = yf.Ticker("^NSEI").history(period="1d", interval="15m")
        if len(df) < 3:
            return
            
        # Get the last 3 candles (Candle -2 is the potential pivot, Candle -1 is the current)
        pivot_candle = df.iloc[-2]
        current_candle = df.iloc[-1]
        
        pivot_low = pivot_candle['Low']
        pivot_high = pivot_candle['High']
        pivot_close = pivot_candle['Close']
        pivot_open = pivot_candle['Open']
        
        current_low = current_candle['Low']
        current_high = current_candle['High']
        current_close = current_candle['Close']
        
        # --- BULL ZONE LOGIC ---
        # 1. Pivot candle must have a lower low than the candle before it
        prev_low = df.iloc[-3]['Low']
        if pivot_low < prev_low:
            # Alert 1: Potential Zone Forming (fired on the pivot wick)
            msg = f"Potential 15m BULL Zone forming at {int(pivot_low)}. Watch for confirmation."
            _log_alert("zone_forming", "IMPORTANT", msg)
            
            # 2. Check the current candle for confirmation or invalidation
            if current_close > pivot_high:
                msg = f"15m BULL Zone CONFIRMED at {int(pivot_low)}. Look for Longs."
                _log_alert("zone_confirmed", "MAJOR", msg)
            elif current_close < pivot_low:
                msg = f"15m BULL Zone FAILED at {int(pivot_low)}. Ignore."
                _log_alert("zone_failed", "SIGNAL", msg)
                
        # --- BEAR ZONE LOGIC ---
        prev_high = df.iloc[-3]['High']
        if pivot_high > prev_high:
            # Alert 1: Potential Zone Forming (fired on the pivot wick)
            msg = f"Potential 15m BEAR Zone forming at {int(pivot_high)}. Watch for confirmation."
            _log_alert("zone_forming", "IMPORTANT", msg)
            
            # 2. Check the current candle for confirmation or invalidation
            if current_close < pivot_low:
                msg = f"15m BEAR Zone CONFIRMED at {int(pivot_high)}. Look for Shorts."
                _log_alert("zone_confirmed", "MAJOR", msg)
            elif current_close > pivot_high:
                msg = f"15m BEAR Zone FAILED at {int(pivot_high)}. Ignore."
                _log_alert("zone_failed", "SIGNAL", msg)
                
    except Exception as e:
        print(f"[Wick Alert Error] {e}")

def _log_alert(event_type, level, message):
    import sys
    sys.path.insert(0, '/home/dinkstrade/pdmp')
    from main import log_event
    log_event(event_type, level, "⚠️", message)
    print(f"[SCREAM] {message}")


"""mtf_scanner.py — Multi-timeframe zone scanner for NIFTY Spot."""
import sqlite3
import yfinance as yf
import pandas as pd
from datetime import datetime, timedelta
import pytz

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

# Pivot config (matches Pine Script: 2 left, 2 right bars)
LEFT = 2
RIGHT = 2

TIMEFRAME_MAP = {
    "15m": {"interval": "15m", "period": "5d"},
    "1H":  {"interval": "1h",  "period": "1mo"},
    "4H":  {"interval": "1h",  "period": "3mo"},  # Resample from 1h
    "D":   {"interval": "1d",  "period": "1y"},
    "W":   {"interval": "1wk", "period": "5y"},
    "M":   {"interval": "1mo", "period": "10y"},
}

def _get_data(interval, period):
    """Fetch OHLCV via yfinance. For 4H, resample from 1h."""
    try:
        t = yf.Ticker("^NSEI")
        df = t.history(period=period, interval=interval)
        if df.empty:
            return None
        return df
    except Exception as e:
        print(f"[MTF] yfinance error: {e}")
        return None

def _find_pivots(df, left=2, right=2):
    """Return list of (type, top, bottom, timestamp) pivots."""
    pivots = []
    if df is None or len(df) < left + right + 1:
        return pivots
    
    n = len(df)
    for i in range(left, n - right):
        high = df['High'].iloc[i]
        low = df['Low'].iloc[i]
        
        is_pivot_high = True
        for j in range(i - left, i):
            if df['High'].iloc[j] >= high:
                is_pivot_high = False; break
        if is_pivot_high:
            for j in range(i + 1, i + right + 1):
                if df['High'].iloc[j] >= high:
                    is_pivot_high = False; break
        
        is_pivot_low = True
        for j in range(i - left, i):
            if df['Low'].iloc[j] <= low:
                is_pivot_low = False; break
        if is_pivot_low:
            for j in range(i + 1, i + right + 1):
                if df['Low'].iloc[j] <= low:
                    is_pivot_low = False; break
        
        ts = df.index[i]
        if hasattr(ts, 'tz_localize'):
            try: ts = ts.tz_localize(IST)
            except: pass
        
        # Bear zone from pivot high (candle body + wick)
        if is_pivot_high:
            o = df['Open'].iloc[i]
            c = df['Close'].iloc[i]
            body_high = max(o, c)
            box_top = high
            box_bottom = min(high, body_high)
            pivots.append({"type": "BEAR", "top": round(box_top, 2), "bottom": round(box_bottom, 2), "ts": ts})
        
        # Bull zone from pivot low
        if is_pivot_low:
            o = df['Open'].iloc[i]
            c = df['Close'].iloc[i]
            body_low = min(o, c)
            box_top = max(low, body_low)
            box_bottom = low
            pivots.append({"type": "BULL", "top": round(box_top, 2), "bottom": round(box_bottom, 2), "ts": ts})
    
    return pivots

def scan_all():
    check_wick_alerts()
    check_1h_wick_alerts()
    now = datetime.now(IST).strftime('%Y-%m-%d %H:%M:%S')
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    
    total = 0
    for tf, config in TIMEFRAME_MAP.items():
        df = _get_data(config['interval'], config['period'])
        if df is None:
            print(f"[MTF] {tf}: no data"); continue
        
        if tf == "4H":
            # Resample 1h to 4h
            df = df.resample('4h').agg({'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last', 'Volume': 'sum'}).dropna()
        
        pivots = _find_pivots(df)
        if not pivots:
            print(f"[MTF] {tf}: no pivots"); continue
        
        # Deactivate old zones for this TF
        c.execute("UPDATE mtf_zones SET is_active=0 WHERE timeframe=?", (tf,))
        
        # Insert fresh pivots (last 15 per TF)
        for p in pivots[-15:]:
            try:
                c.execute("""
                    INSERT INTO mtf_zones (timeframe, zone_type, top, bottom, created_at, is_active, last_updated)
                    VALUES (?, ?, ?, ?, ?, 1, ?)
                """, (tf, p['type'], p['top'], p['bottom'], str(p['ts']), now))
                total += 1
            except Exception as e:
                print(f"[MTF] {tf} insert error: {e}")
        
        print(f"[MTF] {tf}: {len(pivots)} pivots found, {min(15, len(pivots))} saved")
    
    conn.commit()
    conn.close()
    print(f"\n[MTF] Total: {total} zones written at {now}")
    return total

if __name__ == "__main__":
    scan_all()
