
"""
day_before_buildup.py — analyzes how prior-day OI buildup predicts gap direction
v1.0.1

For a given target date (e.g. Monday), walks back through option_chain_history
to find the last trading day before it, and reports:
  - Where the biggest OI buildup happened (strike, side, ΔOI)
  - Whether the buildup matched the gap direction (confirmed or trap)
  - Strike walls that acted as magnets

Usage:
    ~/pdmp/venv/bin/python day_before_buildup.py --target 2026-11-02 --symbol NIFTY
    ~/pdmp/venv/bin/python day_before_buildup.py --gap-up-threshold 100
"""
import sqlite3
import argparse
from datetime import datetime, timedelta
import json

DB_PATH = '/home/dinkstrade/pdmp/sentiment_history.db'


def last_trading_day_before(target_date):
    """Walk back from target_date to the most recent WEEKDAY (Mon-Fri)
    with snapshots. Skips Sat/Sun which produce garbage deltas."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    rows = conn.execute("""
        SELECT DISTINCT substr(snapshot_at, 1, 10) AS day
        FROM option_chain_history
        WHERE substr(snapshot_at, 1, 10) < ?
        ORDER BY day DESC
        LIMIT 14
    """, (target_date,)).fetchall()
    conn.close()
    for r in rows:
        day = r['day']
        try:
            dt = datetime.strptime(day, "%Y-%m-%d")
        except Exception:
            continue
        if dt.weekday() >= 5:  # Sat=5, Sun=6
            continue
        return day
    return None


def get_day_snapshot_summary(symbol, date_str):
    """For a date, return first and last snapshot per strike, split by side."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row

    # First and last snapshot per (strike, expiry)
    first_rows = conn.execute("""
        SELECT strike, expiry, call_oi, put_oi, call_ltp, put_ltp, snapshot_at
        FROM option_chain_history
        WHERE symbol = ? AND snapshot_at LIKE ?
          AND snapshot_at = (
            SELECT MIN(snapshot_at) FROM option_chain_history
            WHERE symbol = ? AND strike = option_chain_history.strike
              AND expiry = option_chain_history.expiry
              AND snapshot_at LIKE ?
          )
    """, (symbol, f"{date_str}%", symbol, f"{date_str}%")).fetchall()

    last_rows = conn.execute("""
        SELECT strike, expiry, call_oi, put_oi, call_ltp, put_ltp, snapshot_at
        FROM option_chain_history
        WHERE symbol = ? AND snapshot_at LIKE ?
          AND snapshot_at = (
            SELECT MAX(snapshot_at) FROM option_chain_history
            WHERE symbol = ? AND strike = option_chain_history.strike
              AND expiry = option_chain_history.expiry
              AND snapshot_at LIKE ?
          )
    """, (symbol, f"{date_str}%", symbol, f"{date_str}%")).fetchall()

    conn.close()

    by_key_first = {(r['strike'], r['expiry']): r for r in first_rows}
    by_key_last = {(r['strike'], r['expiry']): r for r in last_rows}

    deltas = []
    for key, last in by_key_last.items():
        first = by_key_first.get(key)
        if not first:
            continue
        call_delta = (last['call_oi'] or 0) - (first['call_oi'] or 0)
        put_delta = (last['put_oi'] or 0) - (first['put_oi'] or 0)
        deltas.append({
            "strike": key[0],
            "expiry": key[1],
            "call_oi_open": first['call_oi'],
            "call_oi_close": last['call_oi'],
            "call_oi_delta": call_delta,
            "put_oi_open": first['put_oi'],
            "put_oi_close": last['put_oi'],
            "put_oi_delta": put_delta,
        })

    return deltas


def analyze(target_date, symbol="NIFTY", gap_threshold=100):
    prior_day = last_trading_day_before(target_date)
    if not prior_day:
        return {"error": f"No snapshot data before {target_date}"}

    deltas = get_day_snapshot_summary(symbol, prior_day)

    # Top build-ups
    top_call_buildup = sorted(deltas, key=lambda d: d['call_oi_delta'], reverse=True)[:5]
    top_put_buildup = sorted(deltas, key=lambda d: d['put_oi_delta'], reverse=True)[:5]

    # Net bias on the prior day
    net_call = sum(d['call_oi_delta'] for d in deltas)
    net_put = sum(d['put_oi_delta'] for d in deltas)
    if net_put > net_call * 1.2:
        prior_bias = "BULLISH (put writers dominated)"
    elif net_call > net_put * 1.2:
        prior_bias = "BEARISH (call writers dominated)"
    else:
        prior_bias = "NEUTRAL"

    # Try to get the gap on target_date
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    target_first = conn.execute("""
        SELECT spot, snapshot_at FROM intraday_levels_history
        WHERE symbol = ? AND snapshot_at LIKE ?
        ORDER BY snapshot_at ASC LIMIT 1
    """, (symbol, f"{target_date}%")).fetchone()
    target_prev_close = conn.execute("""
        SELECT spot FROM intraday_levels_history
        WHERE symbol = ? AND snapshot_at LIKE ?
        ORDER BY snapshot_at DESC LIMIT 1
    """, (symbol, f"{prior_day}%")).fetchone()
    conn.close()

    gap = None
    gap_direction = None
    if target_first and target_prev_close:
        gap = round(target_first['spot'] - target_prev_close['spot'], 2)
        if gap > gap_threshold:
            gap_direction = "GAP UP"
        elif gap < -gap_threshold:
            gap_direction = "GAP DOWN"
        else:
            gap_direction = "FLAT OPEN"

    # Trap analysis: if prior day was BULLISH buildup but gap was UP and then faded,
    # that's a bull trap. We can only detect the gap direction here; fade must be
    # confirmed by the caller against intraday data.
    trap_warning = None
    if gap_direction == "GAP UP" and prior_bias == "BULLISH (put writers dominated)":
        trap_warning = "POTENTIAL BULL TRAP: prior day put-writer buildup, but gap up may have been the trap itself. Check intraday fade."
    elif gap_direction == "GAP DOWN" and prior_bias == "BEARISH (call writers dominated)":
        trap_warning = "POTENTIAL BEAR TRAP: prior day call-writer buildup, but gap down may have been the trap itself."

    return {
        "symbol": symbol,
        "target_date": target_date,
        "prior_trading_day": prior_day,
        "net_call_oi_delta": net_call,
        "net_put_oi_delta": net_put,
        "prior_bias": prior_bias,
        "top_call_buildup": top_call_buildup,
        "top_put_buildup": top_put_buildup,
        "gap_points": gap,
        "gap_direction": gap_direction,
        "trap_warning": trap_warning,
        "generated_at": datetime.now().isoformat(),
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--target', required=True, help='YYYY-MM-DD of the day whose gap you want to explain')
    ap.add_argument('--symbol', default='NIFTY')
    ap.add_argument('--gap-up-threshold', type=int, default=100)
    ap.add_argument('--json', action='store_true')
    args = ap.parse_args()

    res = analyze(args.target, symbol=args.symbol, gap_threshold=args.gap_up_threshold)

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

    if "error" in res:
        print(f"ERROR: {res['error']}")
        return

    print(f"\n=== {res['symbol']} buildup analysis ===")
    print(f"Target day:  {res['target_date']}")
    print(f"Prior day:   {res['prior_trading_day']}")
    print()
    print(f"Net Call OI delta: {res['net_call_oi_delta']:+,}")
    print(f"Net Put OI delta:  {res['net_put_oi_delta']:+,}")
    print(f"Prior bias:  {res['prior_bias']}")
    print()
    print(f"Gap on target day: {res['gap_points']} pts → {res['gap_direction']}")
    if res['trap_warning']:
        print(f"⚠️  {res['trap_warning']}")
    print()
    print("Top 5 CALL buildups (prior day):")
    for t in res['top_call_buildup']:
        print(f"  {int(t['strike'])} {t['expiry']}: +{t['call_oi_delta']:,} OI")
    print()
    print("Top 5 PUT buildups (prior day):")
    for t in res['top_put_buildup']:
        print(f"  {int(t['strike'])} {t['expiry']}: +{t['put_oi_delta']:,} OI")


if __name__ == "__main__":
    main()
