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 (ATM 100-pt strike) ---
    atm_strike = round(spot_mid / 100) * 100
    print(f"[Options] ATM strike (100-pt): {atm_strike}")

    ce, pe = _get_ce_pe(atm_strike, date_str)
    if not ce or not pe:
        print(f"[Options] No CE/PE found for {atm_strike}")
        return

    print(f"  CE: {ce['display_name']} (sec={ce['security_id']})")
    print(f"  PE: {pe['display_name']} (sec={pe['security_id']})")

    for opt_type, sec_row in [('CE', ce), ('PE', pe)]:
        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}', atm_strike, o_high, o_low, o_mid)
                    print(f"[OK] NIFTY {atm_strike} {opt_type} Shadow: {o_mid} (H:{o_high}, L:{o_low})")
                else:
                    print(f"[{opt_type}] Empty OHLC arrays")
            else:
                print(f"[{opt_type}] Dhan returned no data: {opt_resp.get('remarks', 'unknown')}")
        except Exception as e:
            print(f"[{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)
