
"""
magnet_detector.py — O=H (Open=High) trap detector
v1.0.1

Scans option_chain_history for strikes where the current LTP is nearly
identical to the day's opening LTP AND the day's high — meaning the option
opened at its high, never traded higher, and has been pinned there since.
These are "traps": retail bought at the high, market makers are defending
the level, and the underlying tends to gravitate toward it.

Covers NIFTY, BANKNIFTY, SENSEX.

Usage:
    ~/pdmp/venv/bin/python magnet_detector.py
    ~/pdmp/venv/bin/python magnet_detector.py --symbol NIFTY --tolerance 0.05
"""
import sqlite3
import argparse
from datetime import datetime, timedelta
import json
import dhan_data

DB_PATH = '/home/dinkstrade/pdmp/sentiment_history.db'
DEFAULT_TOLERANCE_PCT = 0.5      # 5% of LTP = "near identical"
MIN_TRAPS_TO_ALERT = 2             # need at least this many traps to be meaningful
MAX_DISTANCE_FROM_SPOT_PCT = 5.0   # ignore strikes more than 5% away from spot


def get_today_snapshots(symbol, date_str):
    """Return all snapshots for a symbol on a given date (YYYY-MM-DD)."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    rows = conn.execute("""
        SELECT strike, expiry, call_ltp, put_ltp, call_oi, put_oi,
               call_coi, put_coi, snapshot_at
        FROM option_chain_history
        WHERE symbol = ?
          AND snapshot_at >= ?
          AND snapshot_at < ?
        ORDER BY snapshot_at ASC
    """, (symbol, f"{date_str} 00:00:00", f"{date_str} 23:59:59")).fetchall()
    conn.close()
    return rows


def get_spot(symbol, date_str):
    """Get latest spot. Try intraday_levels_history, then fall back to
    the strike with the highest total OI in option_chain_history (which
    approximates ATM for symbols without intraday_levels_history rows)."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    row = conn.execute("""
        SELECT spot FROM intraday_levels_history
        WHERE symbol = ? AND snapshot_at LIKE ?
        ORDER BY snapshot_at DESC LIMIT 1
    """, (symbol, f"{date_str}%")).fetchone()
    if row and row['spot']:
        conn.close()
        return row['spot']

    # Fallback: strike with highest combined OI approximates ATM
    try:
        best = conn.execute("""
            SELECT strike, SUM(COALESCE(call_oi,0) + COALESCE(put_oi,0)) AS total_oi
            FROM option_chain_history
            WHERE symbol = ? AND snapshot_at LIKE ?
            GROUP BY strike
            ORDER BY total_oi DESC
            LIMIT 1
        """, (symbol, f"{date_str}%")).fetchone()
        conn.close()
        if best and best['strike']:
            return float(best['strike'])
    except Exception:
        conn.close()
    return None


def detect_traps(symbol, date_str, tolerance_pct=DEFAULT_TOLERANCE_PCT):
    """
    Returns a dict with:
      - call_traps: list of strikes where call side is O=H
      - put_traps:  list of strikes where put side is O=H
      - spot: reference spot
      - verdict: one-line summary
    """
    rows = get_today_snapshots(symbol, date_str)
    if not rows:
        return {"symbol": symbol, "date": date_str, "error": "no snapshots", "call_traps": [], "put_traps": []}

    # Group by (strike, expiry)
    # v2.0: Use the first snapshot of the day as the "open" reference.
    # If we want 09:12 AM exactly, we need 1-min data for all strikes, which is too heavy.
    # The first snapshot (09:26) is our proxy for the "open".
    by_strike = {}
    for r in rows:
        # v2.1: Group by EXACT strike, not rounded.
        # Clustering happens later in build_verdict().
        key = (r['strike'], r['expiry'])
        if key not in by_strike:
            by_strike[key] = {"call": [], "put": []}
        if r['call_ltp'] is not None and r['call_ltp'] > 0:
            by_strike[key]["call"].append({
                "ltp": r['call_ltp'], "oi": r['call_oi'], "coi": r['call_coi'],
                "ts": r['snapshot_at']
            })
        if r['put_ltp'] is not None and r['put_ltp'] > 0:
            by_strike[key]["put"].append({
                "ltp": r['put_ltp'], "oi": r['put_oi'], "coi": r['put_coi'],
                "ts": r['snapshot_at']
            })

    spot = get_spot(symbol, date_str)
    if spot is None:
        # fallback: use the ATM-ish strike from the middle of the chain
        strikes = sorted({k[0] for k in by_strike.keys()})
        spot = strikes[len(strikes) // 2] if strikes else None

    max_dist = spot * MAX_DISTANCE_FROM_SPOT_PCT / 100.0 if spot else float('inf')

    call_traps = []
    put_traps = []

    for (strike, expiry), sides in by_strike.items():
        if spot and abs(strike - spot) > max_dist:
            continue

        for side_name, side_data in [("call", sides["call"]), ("put", sides["put"])]:
            # v1.0.1 — Require 3+ snapshots. A single snapshot trivially
            # satisfies O=H=C because there's only one data point.
            if len(side_data) < 2:
                continue
            open_ltp = side_data[0]['ltp']
            day_high = max(s['ltp'] for s in side_data)
            current = side_data[-1]['ltp']

            if day_high <= 0 or open_ltp <= 0:
                continue

            # O=H test: current is within tolerance of BOTH open and high,
            # AND the high itself is within tolerance of open (meaning it never
            # meaningfully traded above the open)
            tol_abs_cur = current * tolerance_pct / 100.0
            tol_abs_high = open_ltp * tolerance_pct / 100.0

            near_open = abs(current - open_ltp) <= tol_abs_cur
            near_high = abs(current - day_high) <= tol_abs_cur
            open_is_high = abs(day_high - open_ltp) <= tol_abs_high

            if near_open and near_high and open_is_high:
                trap = {
                    "strike": float(strike),   # actual exact strike
                    "expiry": expiry,
                    "side": side_name,
                    "open_ltp": round(open_ltp, 2),
                    "high_ltp": round(day_high, 2),
                    "current_ltp": round(current, 2),
                    "oi": side_data[-1]['oi'],
                    "coi": side_data[-1]['coi'],
                    "snapshots": len(side_data),
                    "distance_from_spot": round(strike - spot, 1) if spot else None,
                }
                (call_traps if side_name == "call" else put_traps).append(trap)

    # Sort by proximity to spot (closest first)
    call_traps.sort(key=lambda t: abs(t['distance_from_spot'] or 99999))
    put_traps.sort(key=lambda t: abs(t['distance_from_spot'] or 99999))

    # Verdict
    verdict = build_verdict(symbol, spot, call_traps, put_traps)

    return {
        "symbol": symbol,
        "date": date_str,
        "spot": round(spot, 2) if spot else None,
        "call_traps": call_traps,
        "put_traps": put_traps,
        "verdict": verdict,
        "generated_at": datetime.now().isoformat(),
    }


def _find_cluster(strikes):
    """Finds the center of a wall of strikes (clusters within 100 pts)."""
    if not strikes:
        return None
    strikes = sorted(strikes)
    # Group into clusters where gap between consecutive strikes is <= 100
    clusters = []
    current_cluster = [strikes[0]]
    for s in strikes[1:]:
        if s - current_cluster[-1] <= 100:
            current_cluster.append(s)
        else:
            clusters.append(current_cluster)
            current_cluster = [s]
    clusters.append(current_cluster)
    
    # Find the largest cluster
    largest = max(clusters, key=len)
    if len(largest) < 2: # Need at least 2 to form a wall
        return None
    # Center is the middle strike
    center = largest[len(largest)//2]
    return {"center": center, "count": len(largest), "min": largest[0], "max": largest[-1]}

def build_verdict(symbol, spot, call_traps, put_traps):
    """One-line summary based on COUNT of O=H traps and cluster walls."""
    n_call = len(call_traps)
    n_put = len(put_traps)

    if n_call < MIN_TRAPS_TO_ALERT and n_put < MIN_TRAPS_TO_ALERT:
        return f"{symbol}: No significant O=H clusters detected."

    # Find clusters
    call_strikes = [t['strike'] for t in call_traps]
    put_strikes = [t['strike'] for t in put_traps]
    
    call_wall = _find_cluster(call_strikes)
    put_wall = _find_cluster(put_strikes)

    parts = []
    if put_wall:
        parts.append(f"Put O=H WALL ({put_wall['count']} traps) at {int(put_wall['min'])}-{int(put_wall['max'])} (Center: {int(put_wall['center'])})")
    if call_wall:
        parts.append(f"Call O=H WALL ({call_wall['count']} traps) at {int(call_wall['min'])}-{int(call_wall['max'])} (Center: {int(call_wall['center'])})")

    # Determine probability bias
    if n_put > n_call * 1.5:
        bias = f"STRONG BEARISH PULL ({n_put} vs {n_call} traps). High probability market tests Put wall."
    elif n_call > n_put * 1.5:
        bias = f"STRONG BULLISH PULL ({n_call} vs {n_put} traps). High probability market tests Call wall."
    elif n_put > n_call:
        bias = f"BEARISH PULL ({n_put} vs {n_call} traps)."
    elif n_call > n_put:
        bias = f"BULLISH PULL ({n_call} vs {n_put} traps)."
    else:
        bias = f"BALANCED ({n_call} vs {n_put} traps). Market may travel between both walls."

    return f"{symbol} @ {int(spot) if spot else '?'}: {bias} " + " | ".join(parts)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--symbol', default=None, help='NIFTY, BANKNIFTY, SENSEX, or omit for all three')
    ap.add_argument('--date', default=None, help='YYYY-MM-DD (default: today)')
    ap.add_argument('--tolerance', type=float, default=DEFAULT_TOLERANCE_PCT)
    ap.add_argument('--json', action='store_true')
    args = ap.parse_args()

    date_str = args.date or datetime.now().strftime("%Y-%m-%d")
    symbols = [args.symbol] if args.symbol else ["NIFTY", "BANKNIFTY", "SENSEX"]

    results = []
    for sym in symbols:
        res = detect_traps(sym, date_str, tolerance_pct=args.tolerance)
        results.append(res)
        if not args.json:
            print(f"\n=== {sym} ({date_str}) ===")
            print(f"  Spot: {res.get('spot')}")
            print(f"  Call traps: {len(res.get('call_traps', []))}")
            print(f"  Put traps:  {len(res.get('put_traps', []))}")
            print(f"  Verdict: {res.get('verdict')}")
            for t in res.get('call_traps', [])[:3]:
                print(f"    CALL {int(t['strike'])} {t['expiry']}: O={t['open_ltp']} H={t['high_ltp']} C={t['current_ltp']} OI={t['oi']}")
            for t in res.get('put_traps', [])[:3]:
                print(f"    PUT  {int(t['strike'])} {t['expiry']}: O={t['open_ltp']} H={t['high_ltp']} C={t['current_ltp']} OI={t['oi']}")

    if args.json:
        print(json.dumps(results, indent=2))

    return results


if __name__ == "__main__":
    main()
