import time
import os
from dotenv import load_dotenv
load_dotenv()
from datetime import datetime, timedelta
from dhanhq import dhanhq, DhanContext

CLIENT_ID = "1000731429"
ACCESS_TOKEN = os.getenv("DHAN_TOKEN", "")

DHAN_CLIENT = None

def get_client():
    global DHAN_CLIENT
    if DHAN_CLIENT is not None:
        return DHAN_CLIENT
    DHAN_CLIENT = dhanhq(DhanContext(CLIENT_ID, ACCESS_TOKEN))
    return DHAN_CLIENT

def get_intraday_volume_data(symbol="NIFTY", days_back=1):
    """Fetches 1-min data to compute VWAP. Walks back to most recent trading day."""
    dhan = get_client()
    probe = datetime.now() - timedelta(days=days_back)
    while probe.weekday() >= 5:  # Skip Sat/Sun
        probe -= timedelta(days=1)
    target_date = probe.strftime("%Y-%m-%d")
    from_date = f"{target_date} 09:15:00"
    to_date = f"{target_date} 15:40:00"
    
    # 13 is NIFTY IDX_I
    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
    )
    return resp

def compute_vwap(symbol="NIFTY"):
    """Calculates VWAP from yesterday's data (since market is closed now)."""
    resp = get_intraday_volume_data(symbol, days_back=1)
    if resp.get('status') != 'success':
        return None
    
    data = resp.get('data', {})
    highs = data.get('high', [])
    lows = data.get('low', [])
    closes = data.get('close', [])
    volumes = data.get('volume', [])
    
    if not volumes or len(volumes) == 0:
        return None
        
    cum_pv = 0
    cum_v = 0
    for h, l, c, v in zip(highs, lows, closes, volumes):
        typical_price = (h + l + c) / 3
        cum_pv += typical_price * v
        cum_v += v
        
    if cum_v == 0: return None
    return round(cum_pv / cum_v, 2)

def get_dhan_option_chain(symbol="NIFTY"):
    """Fetches full option chain with a 3-try retry loop."""
    import time
    for attempt in range(1, 4):
        try:
            result = _get_dhan_option_chain_inner(symbol)
            # If the result contains data, return it
            if result and result.get("status") == "success" and result.get("spot"):
                return result
            # If it returned an error, log it and retry
            if result.get("error"):
                print(f"[Dhan Retry {attempt}/3] Error: {result.get('error')}")
                time.sleep(1)
                continue
            # If we get here, it succeeded but might be empty
            return result
        except Exception as e:
            print(f"[Dhan Retry {attempt}/3] Exception: {e}")
            time.sleep(1)
    
    print(f"[Dhan] All retries failed for {symbol}")
    return {"error": "All retries failed"}

import sys
def _get_dhan_option_chain_inner(symbol="NIFTY"):
    dhan = get_client()
    time.sleep(1) # Rate limit safety
    
    # Helper for safe dict access
    def safe_get(d, key, default=None):
        if isinstance(d, dict): return d.get(key, default)
        return default

    # Get Expiry
    exp_resp = dhan.expiry_list(under_security_id=13, under_exchange_segment="IDX_I")
    if not isinstance(exp_resp, dict):
        return {"error": f"Dhan returned non-dict: {str(exp_resp)[:100]}"}
        
    expiry_list = safe_get(safe_get(exp_resp, 'data', {}), 'data', [])
    
    if expiry_list:
        expiry = expiry_list[0]
    else:
        expiry = "2026-11-05"
        print(f"[Dhan Data] API returned empty expiry, using fallback: {expiry}")
    time.sleep(1.5)  # Safe rate limit
    
    # Get Chain
    chain_resp = dhan.option_chain(under_security_id=13, under_exchange_segment="IDX_I", expiry=expiry)
    if not isinstance(chain_resp, dict):
         return {"error": f"Dhan returned non-dict: {str(chain_resp)[:100]}"}
         
    data_block = safe_get(safe_get(chain_resp, 'data', {}), 'data', {})
    oc = safe_get(data_block, 'oc', {})
    
    if not oc: return {"error": "Chain empty"}
    
    # Convert Dhan dict to legacy rows format
    rows = []
    for strike_str, sides in oc.items():
        strike = float(strike_str)
        ce = sides.get('ce', {})
        pe = sides.get('pe', {})
        
        rows.append({
            "strike": strike,
            "call_oi": ce.get('oi', 0),
            "call_coi": ce.get('oi', 0) - ce.get('previous_oi', 0),
            "call_ltp": ce.get('last_price', 0.0),
            "call_iv": ce.get('implied_volatility', 0.0),
            "call_vol": ce.get('volume', 0),
            "call_bid": ce.get('top_bid_price', 0.0),
            "call_ask": ce.get('top_ask_price', 0.0),
            
            "put_oi": pe.get('oi', 0),
            "put_coi": pe.get('oi', 0) - pe.get('previous_oi', 0),
            "put_ltp": pe.get('last_price', 0.0),
            "put_iv": pe.get('implied_volatility', 0.0),
            "put_vol": pe.get('volume', 0),
            "put_bid": pe.get('top_bid_price', 0.0),
            "put_ask": pe.get('top_ask_price', 0.0),
        })
    
    spot = data_block.get('last_price', 0)
    
    # Calculate summary fields from rows
    total_call_oi = sum(int(r.get('call_oi') or 0) for r in rows)
    total_put_oi = sum(int(r.get('put_oi') or 0) for r in rows)
    pcr = round(total_put_oi / total_call_oi, 3) if total_call_oi else 0
    
    # Find ATM
    atm = round(spot / 50) * 50
    
    # Support = highest Put OI below spot
    below = [r for r in rows if float(r['strike']) <= spot]
    support_row = max(below, key=lambda r: int(r.get('put_oi') or 0)) if below else None
    
    # Resistance = highest Call OI above spot
    above = [r for r in rows if float(r['strike']) >= spot]
    resistance_row = max(above, key=lambda r: int(r.get('call_oi') or 0)) if above else None
    
    # ATM neighborhood
    by_strike = {float(r['strike']): r for r in rows}
    atm_neighborhood = []
    for offset in [-2, -1, 0, 1, 2]:
        s = atm + offset * 50
        row = by_strike.get(s)
        if not row:
            continue
        atm_neighborhood.append({
            "strike": s,
            "call_oi": int(row.get('call_oi') or 0),
            "call_coi": int(row.get('call_coi') or 0),
            "put_oi": int(row.get('put_oi') or 0),
            "put_coi": int(row.get('put_coi') or 0),
            "call_ltp": float(row.get('call_ltp') or 0.0),
            "put_ltp": float(row.get('put_ltp') or 0.0),
            "call_iv": float(row.get('call_iv') or 0.0),
            "put_iv": float(row.get('put_iv') or 0.0),
            "call_vol": int(row.get('call_vol') or 0),
            "put_vol": int(row.get('put_vol') or 0),
        })
    
    # Calculate top 5 support and resistance levels for the dashboard
    lo, hi = spot * 0.985, spot * 1.015
    support_candidates = [r for r in rows if lo <= float(r['strike']) <= spot]
    resistance_candidates = [r for r in rows if spot <= float(r['strike']) <= hi]

    top_supports = sorted(support_candidates, key=lambda x: -int(x.get('put_oi') or 0))[:10]
    top_resistances = sorted(resistance_candidates, key=lambda x: -int(x.get('call_oi') or 0))[:10]

    top5_support = [
        {"strike": float(r['strike']), "oi": int(r.get('put_oi') or 0), "coi": int(r.get('put_coi') or 0)}
        for r in top_supports
    ]
    top5_resistance = [
        {"strike": float(r['strike']), "oi": int(r.get('call_oi') or 0), "coi": int(r.get('call_coi') or 0)}
        for r in top_resistances
    ]

    return {
        "status": "success",
        "symbol": symbol,
        "spot": spot,
        "expiry": expiry,
        "pcr": pcr,
        "atm": atm,
        "max_pain": atm,
        "total_call_oi": total_call_oi,
        "total_put_oi": total_put_oi,
        "support": {
            "level": float(support_row['strike']) if support_row else None,
            "put_oi": int(support_row['put_oi']) if support_row else 0,
            "put_coi": int(support_row.get('put_coi') or 0) if support_row else 0,
        },
        "resistance": {
            "level": float(resistance_row['strike']) if resistance_row else None,
            "call_oi": int(resistance_row['call_oi']) if resistance_row else 0,
            "call_coi": int(resistance_row.get('call_coi') or 0) if resistance_row else 0,
        },
        "atm_neighborhood": atm_neighborhood,
        "top5_support": top5_support,
        "top5_resistance": top5_resistance,
        "rows": rows
    }

if __name__ == '__main__':
    print("=== VWAP TEST ===")
    vwap = compute_vwap()
    print(f"VWAP (Yesterday): {vwap}")
    
    print("\n=== OPTION CHAIN TEST ===")
    chain = get_dhan_option_chain()
    print(f"Status: {chain.get('status')}")
    print(f"Spot: {chain.get('spot')}")
    print(f"Expiry: {chain.get('expiry')}")
    print(f"Rows: {len(chain.get('rows', []))}")
    if chain.get('rows'):
        print(f"Sample Row: {chain['rows'][0]}")
