import os
import sqlite3
from datetime import datetime, timedelta
import pytz
from dotenv import load_dotenv
load_dotenv('/home/dinkstrade/pdmp/.env', override=True)
from dhanhq import dhanhq, DhanContext

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


def _get_dhan_client():
    token = os.getenv("DHAN_TOKEN", "")
    if not token:
        return None
    return dhanhq(DhanContext(CLIENT_ID, token))


def _save_shadow(date_str, symbol, shadow_type, strike, high, low, midpoint):
    conn = sqlite3.connect(DB_PATH)
    conn.execute(
        "INSERT OR REPLACE INTO shadow_levels "
        "(date, symbol, type, strike, high, low, midpoint) "
        "VALUES (?, ?, ?, ?, ?, ?, ?)",
        (date_str, symbol, shadow_type, 0 if strike is None else strike, high, low, midpoint)
    )
    conn.commit()
    conn.close()


def _get_ce_pe(strike, after_date):
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    ce = conn.execute(
        "SELECT security_id, display_name FROM dhan_instruments "
        "WHERE strike=? AND option_type='CE' AND expiry > ? "
        "ORDER BY expiry ASC LIMIT 1",
        (strike, after_date)
    ).fetchone()
    pe = conn.execute(
        "SELECT security_id, display_name FROM dhan_instruments "
        "WHERE strike=? AND option_type='PE' AND expiry > ? "
        "ORDER BY expiry ASC LIMIT 1",
        (strike, after_date)
    ).fetchone()
    conn.close()
    return ce, pe


def calculate_shadow_levels(date_str=None):
    if not date_str:
        now = datetime.now(IST)
        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")

    print(f"[Shadow] Calculating for {date_str}...")
    dhan = _get_dhan_client()
    if not dhan:
        print("[Shadow] Dhan client failed. Check token.")
        return

    from_date = f"{date_str} 15:10:00"
    to_date = f"{date_str} 15:40:00"

    # --- 1. Spot Shadow ---
    spot_mid = None
    try:
        spot_resp = dhan.intraday_minute_data(
            security_id="13", exchange_segment="IDX_I", instrument_type="INDEX",
            from_date=from_date, to_date=to_date, interval=1
        )
        if spot_resp.get('status') == 'success' and spot_resp.get('data'):
            highs = spot_resp['data'].get('high', [])
            lows = spot_resp['data'].get('low', [])
            if highs and lows:
                spot_high = max(highs)
                spot_low = min(lows)
                spot_mid = round((spot_high + spot_low) / 2, 2)
                _save_shadow(date_str, 'NIFTY', 'SPOT', None, spot_high, spot_low, spot_mid)
                print(f"[OK] NIFTY Spot Shadow: {spot_mid} (H:{spot_high}, L:{spot_low})")
    except Exception as e:
        print(f"[Spot] Error: {e}")
        return

    if not spot_mid:
        print("[Shadow] Cannot determine spot midpoint — aborting options fetch")
        return

    # --- 2. Options Shadow (Institutional Grid) ---
    atm_strike = round(spot_mid / 100) * 100
    print(f"[Options] ATM strike (100-pt): {atm_strike}")

    # Define the target offsets (0 is ATM). 
    # You asked to ignore 23350, 23250 (50-point strikes), but since we are moving to 100-pt intervals, 
    # those don't exist. You also said ignore "23350", which in a 100-pt grid implies the 3rd step.
    # Offsets: 0 (ATM), +100, +200, SKIP +300, +400, +500, +600...
    # Let's explicitly list them to avoid confusion.
    
    # Based on "ignore 23150, 23250, 23350": 
    # 23000, 23100, 23200, 23300(SKIP), 23400, 23500(SKIP), 23600...
    # Since we skip every odd 100? No, let's just make a robust set.
    
    target_strikes = [
        atm_strike - 200,
        atm_strike - 100,
        atm_strike,         # ATM
        atm_strike + 100,
        atm_strike + 200,
        # skip +300 (e.g., 23300)
        atm_strike + 400,
        # skip +500 (e.g., 23500)
        atm_strike + 600,
    ]
    
    print(f"[Options] Fetching shadows for {len(target_strikes)} strikes on both CE and PE...")

    for strike in target_strikes:
        ce, pe = _get_ce_pe(strike, date_str)
        
        for opt_type, sec_row in [('CE', ce), ('PE', pe)]:
            if not sec_row:
                print(f"  ⚠️ No {opt_type} found for strike {strike}")
                continue

            try:
                opt_resp = dhan.intraday_minute_data(
                    security_id=sec_row['security_id'],
                    exchange_segment="NSE_FNO",
                    instrument_type="OPTIDX",
                    from_date=from_date, to_date=to_date, interval=1
                )
                if opt_resp.get('status') == 'success' and opt_resp.get('data'):
                    o_highs = opt_resp['data'].get('high', [])
                    o_lows = opt_resp['data'].get('low', [])
                    if o_highs and o_lows:
                        o_high = max(o_highs)
                        o_low = min(o_lows)
                        o_mid = round((o_high + o_low) / 2, 2)
                        _save_shadow(date_str, 'NIFTY', f'OPT_{opt_type}', strike, o_high, o_low, o_mid)
                        print(f"  ✅ {strike} {opt_type} Shadow: {o_mid}")
                    else:
                        print(f"  ⚠️ {strike} {opt_type} empty OHLC arrays")
                else:
                    print(f"  ⚠️ {strike} {opt_type} no data: {opt_resp.get('remarks', 'unknown')}")
            except Exception as e:
                print(f"  ❌ {strike} {opt_type} error: {e}")


if __name__ == "__main__":
    import sys
    date_arg = sys.argv[1] if len(sys.argv) > 1 else None
    calculate_shadow_levels(date_arg)
