# ============================================================
# PDMP Unified Trading Platform — main.py
# Version: v1.11.0
# Date: 2026-10-14
# ------------------------------------------------------------
# Change log:
#   v1.4.0 - Add: OI conviction engine (support & resistance)
#            Add: oi_bias_flip, oi_surge, call/put wall-shift alerts
#            Add: support/resistance conviction building/fading/break alerts
#            Add: VIX persisted in intraday_levels_history + vix_shift alert
#            Change: SUPPORT_RESISTANCE_SHIFT_MIN 25 -> 50
#            Change: get_previous_intraday_levels() now same-day only
#            Change: intraday_levels_history extended with 11 OI columns
#                    (ALTER TABLE — old rows keep NULLs, no data loss)
#            Change: /api/option-chain now returns a `conviction` block
#   v1.3.0 - Add: PCR surge alerting (>=30% delta)
#            Add: Zone overlap dedup (>60% threshold)
#            Change: S/R/PCR/MaxPain shift detection now DB-backed
#   v1.2.0 - Add: intraday_levels_history table for S/R shift detection
#   v1.1.0 - Add: /api/market-narrative endpoint
#   v1.0.0 - Unified: Sentiment + Zone Scanner
# ============================================================

import os
import re
import time
import math
import sqlite3
import requests
import subprocess
import threading
import json as json_lib
import feedparser
import urllib.parse
from datetime import datetime, timedelta, timezone
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
import yfinance as yf
from youtube_transcript_api import YouTubeTranscriptApi
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
import pytz

from fno_stocks import get_unique_stocks as get_fno_stocks, MIN_PRICE, MAX_PRICE

VERSION = "v1.30.2"

# --- WATCHDOG STATE ---
LAST_SUCCESSFUL_FETCH = time.time()
LAST_DHAN_CLIENT_RESET = time.time()
DHAN_WATCHDOG_INTERVAL = 60  # check every 60s
DHAN_TIMEOUT_SEC = 180  # 3 minutes

if os.name == "nt":
    VENV_PYTHON = "python"
else:
    VENV_PYTHON = "/home/dinkstrade/pdmp/venv/bin/python"

IST = pytz.timezone("Asia/Kolkata")

# ============================================================
# CONFIGURATION
# ============================================================
NEWS_MAX_AGE_HOURS = 24
FII_DII_SCALE = 500

# Shift thresholds
SUPPORT_RESISTANCE_SHIFT_MIN = 50          # v1.4.0: was 25 — quieter, higher signal
PCR_SHIFT_MIN = 0.05
PCR_SURGE_PCT_MIN = 30.0
VIX_SHIFT_MIN_PCT = 5.0                    # v1.4.0: VIX % change between snapshots
VIX_SURGE_MIN_PCT = 3.0                    # v1.4.0: day-over-day VIX % change
MAXPAIN_SHIFT_MIN = 50

# OI / conviction thresholds (v1.4.0)
OI_SURGE_SCORE_DELTA = 325.0                 # net_bias_score change between snapshots
CONVICTION_BUILD_DELTA = 975.0              # conviction % change to fire building/fading
CONVICTION_BREAK_THRESHOLD = 30.0          # conviction below this = weak
CONVICTION_BREAK_PRICE_PROXIMITY = 20.0    # price within N pts of level to fire break alert
CONVICTION_STRONG = 70.0
CONVICTION_MODERATE = 40.0

# Weights used by compute_conviction()
CONVICTION_W_ABSOLUTE = 0.6
CONVICTION_W_FRESHNESS = 0.4
CONVICTION_W_TREND = 0.2
CONVICTION_W_SUM = CONVICTION_W_ABSOLUTE + CONVICTION_W_FRESHNESS + CONVICTION_W_TREND

ATR_SIGNAL_MULT = 0.25
ATR_IMPORTANT_MULT = 0.50
ATR_MAJOR_MULT = 0.85

TIER1_IMPORTANT_FLOOR = 0.5
TIER1_MAJOR_FLOOR = 0.9

ACTION_DASHBOARD_MAX_EVENTS = 25

PIVOT_LEFT = 2
PIVOT_RIGHT = 2
ZONE_LENGTH_BARS = 25
ZONE_MAX_AGE_HOURS = 72

SENTIMENT_DB_PATH = "sentiment_history.db"
ZONES_DB_PATH = "zones_15m.db"

# ============================================================
# MACRO EVENT CONFIGURATION (v1.5.0)
# ============================================================
MACRO_SUPPRESS_PRE_MIN = 5
MACRO_SUPPRESS_POST_MIN = 15
MACRO_DOWNGRADE = {"MAJOR": "IMPORTANT", "IMPORTANT": "SIGNAL", "SIGNAL": "SIGNAL"}
MACRO_UPCOMING_DAYS = 7
MACRO_COVERAGE_WARN_DAYS = 30

# ============================================================
# NEWS PIPELINE CONFIG (v1.6.0)
# ============================================================
NEWS_REFRESH_MINUTES = 30
NEWS_LOOKBACK_HOURS = 24
NEWS_MAX_PER_SYMBOL = 10
NEWS_FETCH_DELAY_SEC = 0.3
NEWS_INITIAL_UNIVERSE_LIMIT = 30

# Lexicon weights
NEWS_POSITIVE_WORDS = [
    "surge", "surges", "rally", "rallies", "jump", "jumps", "gain", "gains",
    "rise", "rises", "soar", "soars", "climb", "climbs", "spike", "spikes",
    "beat", "beats", "record", "high", "highs", "strong", "outperform",
    "bullish", "upgrade", "upgrades", "boost", "boosts", "profit", "profits",
    "buy", "buys", "positives", "expansion", "wins", "win", "approval",
    "breakout", "rebound", "recovery", "upside", "momentum"
]
NEWS_NEGATIVE_WORDS = [
    "fall", "falls", "crash", "crashes", "plunge", "plunges", "drop", "drops",
    "decline", "declines", "slump", "slumps", "weak", "weakness", "loss", "losses",
    "down", "bearish", "downgrade", "downgrades", "sell", "sells", "miss", "misses",
    "cut", "cuts", "penalty", "fine", "fines", "probe", "investigation",
    "fraud", "scam", "default", "delisting", "warning", "warn", "crisis",
    "slashed", "slashes", "concern", "concerns", "pressure", "breaks"
]

# v1.6.1: keyword filter — headlines must contain at least one of these
# to be stored as "news" (filters out quote/ticker pages).
# ============================================================
# GOOGLE TRENDS CONFIG (v1.7.0)
# ============================================================
TRENDS_REFRESH_HOURS = 6
TRENDS_TIMEFRAME = "now 7-d"
TRENDS_GEO = "IN"
TRENDS_HL = "en-IN"
TRENDS_TZ = 330
TRENDS_MAX_KEYWORDS_PER_REQUEST = 5
TRENDS_REQUEST_DELAY_SEC = 8
# ============================================================
# ATM-NEIGHBORHOOD OI TRACKING (v1.8.0)
# ============================================================
ATM_NEIGHBORHOOD_SIZE = 2          # +-2 strikes around ATM
ATM_SURGE_THRESHOLD_PCT = 30.0     # COI change % to flag as surge
ATM_SURGE_MIN_ABS = 25000          # minimum absolute COI to qualify

# ============================================================
# FLASH ALERT CONFIG (v1.8.3)
# ============================================================
FLASH_LOOKBACK_MIN = 15          # minutes — recent events only
FLASH_MAX_EVENTS = 8             # cap per poll
FLASH_MAGNITUDE_TIERS = [
    (500, "CRITICAL"),
    (250, "MAJOR"),
    (100, "IMPORTANT"),
    (50,  "SIGNAL"),
]

# Flash-eligible event types
FLASH_TYPES = {
    "support_shift", "resistance_shift",
    "atm_call_surge", "atm_put_surge",
    "pcr_surge", "oi_bias_flip",
    "support_conviction_building", "resistance_conviction_building",
    "support_break_imminent", "resistance_break_imminent",
    "vix_surge", "vix_drop",
}

# ============================================================
# NARRATIVE / DAY DIRECTION CONFIG (v1.9.0)
# ============================================================
NARRATIVE_WINDOW_MIN = 15             # minutes to look back for deltas
NARRATIVE_COI_SIGNIFICANT = 3250000     # min absolute COI to be "significant"
NARRATIVE_CONVICTION_STRONG = 80.0    # conviction % for "hardened"
NARRATIVE_CONVICTION_WEAK = 40.0

# Day Direction thresholds
DIRECTION_MIN_HOLD_MIN = 20           # min hold time for direction call
DIRECTION_CONVICTION_DOMINANCE = 15.0 # conviction gap for "clear direction"
DIRECTION_STRONG_DOMINANCE = 30.0     # for "strong" call

# Trade Call
TRADE_CALL_MAX_ACTIVE = 1             # only show highest-confidence call
TRADE_CALL_MIN_CONFIDENCE = 0.0
TRADE_CALL_ATR_MULT_STOP = 0.5        # stop = entry -/+ 0.5 * ATR

# ============================================================
# BLOCK 4D CONFIG (v1.10.0)
# ============================================================
# Range-locked detection
RANGE_LOCKED_CONVICTION = 90.0        # both sides above this = range-locked
RANGE_LOCKED_MIN_WIDTH = 150          # min pts between support/resistance

# Correlation matrix
CORRELATION_LOOKBACK_DAYS = 30
# ============================================================
# BLOCK 6 CONFIG (v1.11.0)
# ============================================================
EVENT_HISTORY_MAX_AGE_HOURS = 168
EVENT_HISTORY_DEDUP_WINDOW_SEC = 300   # v1.11.1: was 60, matched poll interval — amplified noise


# ============================================================
# v1.22.0 — ZONE ACCURACY TRACKER
# ============================================================
ZONE_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "zones_15m.db")

def log_zone_to_tracker(symbol, zone_type, entry_spot, stop_spot, target_spot, zone_id=None):
    """Log a new zone signal to the accuracy tracker with priority score."""
    try:
        conn = sqlite3.connect(ZONE_DB_PATH)
        c = conn.cursor()
        now_ist_str = datetime.now(IST).isoformat()

        # v1.16.0: compute priority score at insert time
        priority_score = None
        priority_class = None
        try:
            from zone_priority import compute_priority_score, classify
            sector = None
            try:
                from fno_stocks import FNO_STOCKS
                clean = symbol.replace('.NS', '').upper()
                for s in FNO_STOCKS:
                    if s.get('symbol', '').replace('.NS', '').upper() == clean:
                        sector = s.get('sector')
                        break
            except Exception:
                pass
            zone_dict = {'zone_type': zone_type, 'created_at': now_ist_str, 'entry_spot': entry_spot}
            priority_score, _ = compute_priority_score(zone_dict, sector, spot_price=None)
            priority_class = classify(priority_score)
        except Exception as e:
            print(f"[Zone Priority] scoring error: {e}")

        c.execute("""
            INSERT INTO zone_accuracy 
            (zone_id, symbol, zone_type, entry_spot, stop_spot, target_spot, status, created_at, priority_score, priority_class)
            VALUES (?, ?, ?, ?, ?, ?, 'OPEN', ?, ?, ?)
        """, (zone_id, symbol, zone_type, entry_spot, stop_spot, target_spot, now_ist_str, priority_score, priority_class))
        conn.commit()
        conn.close()
        print(f"[Zone Tracker] Logged {zone_type} for {symbol} @ {entry_spot} | priority={priority_class}({priority_score})")
    except Exception as e:
        print(f"[Zone Tracker] Error: {e}")

FLASH_TOAST_LEVELS = {"MAJOR", "CRITICAL"}
FLASH_AMPLIFIER_LEVELS = {"CRITICAL"}

CORRELATION_SYMBOLS = {
    "NIFTY":    "^NSEI",
    "BANKNIFTY":"^NSEBANK",
    "CRUDE":    "CL=F",
    "GOLD":     "GC=F",
    "SILVER":   "SI=F",
    "BTC":      "BTC-USD",
}


TRENDS_SYMBOL_MAP = [
    ("HDFCBANK.NS",   "HDFC Bank"),
    ("RELIANCE.NS",   "Reliance Industries"),
    ("ICICIBANK.NS",  "ICICI Bank"),
    ("INFY.NS",       "Infosys"),
    ("TCS.NS",        "TCS"),
    ("ITC.NS",        "ITC"),
    ("LT.NS",         "Larsen & Toubro"),
    ("SBIN.NS",       "State Bank of India"),
    ("BHARTIARTL.NS", "Bharti Airtel"),
    ("AXISBANK.NS",   "Axis Bank"),
    ("KOTAKBANK.NS",  "Kotak Mahindra Bank"),
    ("HINDUNILVR.NS", "Hindustan Unilever"),
    ("BAJFINANCE.NS", "Bajaj Finance"),
    ("MARUTI.NS",     "Maruti Suzuki"),
    ("ASIANPAINT.NS", "Asian Paints"),
    ("M&M.NS",        "Mahindra & Mahindra"),
    ("SUNPHARMA.NS",  "Sun Pharma"),
    ("HCLTECH.NS",    "HCL Technologies"),
    ("TITAN.NS",      "Titan"),
    ("ULTRACEMCO.NS", "UltraTech Cement"),
    ("NIFTY",         "Nifty 50"),
    ("BANKNIFTY",     "Bank Nifty"),
]

NEWS_SIGNAL_KEYWORDS = [
    "earnings", "results", "profit", "revenue", "income", "pat", "ebitda",
    "quarterly", "q1", "q2", "q3", "q4", "fy2", "fy25", "fy26", "fy27",
    "order", "wins", "win", "secures", "bagged", "contract",
    "approves", "approved", "approval", "board",
    "acquisition", "acquires", "merger", "merges", "stake", "deal",
    "partnership", "partners", "tie-up", "tieup", "collaboration",
    "launches", "launch", "expansion", "expands", "commissions",
    "dividend", "buyback", "bonus", "split", "rights",
    "hikes", "cuts", "reduces", "slashes", "raises",
    "guidance", "forecast", "outlook", "upgrade", "downgrade",
    "target", "rating", "initiates", "coverage",
    "regulatory", "probe", "penalty", "fine", "tax", "sebi", "rbi", "cbi",
    "ceo", "cfo", "md", "chairman", "board", "appoints", "resigns",
    "ipo", "listing", "delisting", "insolvency", "bankruptcy",
    "stock", "share", "shares"  # last-resort fallback
]
MACRO_IMPORTANCE_DEFAULT = "MEDIUM"

# Time format validation for POST /api/macro-events
import re as _re_macro
_TIME_RE = _re_macro.compile(r"^([01]\d|2[0-3]):[0-5]\d$")


# ============================================================
# NaN / Inf sanitizer
# ============================================================
def _clean(value):
    if isinstance(value, float):
        if math.isnan(value) or math.isinf(value):
            return None
        return value
    if isinstance(value, dict):
        return {k: _clean(v) for k, v in value.items()}
    if isinstance(value, list):
        return [_clean(v) for v in value]
    return value

# ============================================================
# NIFTY & SENSEX CONSTITUENTS
# ============================================================
NIFTY50_CONSTITUENTS = [
    {"symbol": "HDFCBANK.NS",   "name": "HDFC Bank",         "weight": 9.2, "sector": "Banks"},
    {"symbol": "RELIANCE.NS",   "name": "Reliance",          "weight": 8.1, "sector": "Energy"},
    {"symbol": "ICICIBANK.NS",  "name": "ICICI Bank",        "weight": 7.9, "sector": "Banks"},
    {"symbol": "INFY.NS",       "name": "Infosys",           "weight": 5.8, "sector": "IT"},
    {"symbol": "TCS.NS",        "name": "TCS",               "weight": 4.2, "sector": "IT"},
    {"symbol": "ITC.NS",        "name": "ITC",               "weight": 3.8, "sector": "FMCG"},
    {"symbol": "LT.NS",         "name": "L&T",               "weight": 3.5, "sector": "Infra"},
    {"symbol": "SBIN.NS",       "name": "SBI",               "weight": 3.0, "sector": "Banks"},
    {"symbol": "BHARTIARTL.NS", "name": "Bharti Airtel",     "weight": 2.9, "sector": "Telecom"},
    {"symbol": "AXISBANK.NS",   "name": "Axis Bank",         "weight": 2.7, "sector": "Banks"},
    {"symbol": "KOTAKBANK.NS",  "name": "Kotak Mahindra",    "weight": 2.6, "sector": "Banks"},
    {"symbol": "HINDUNILVR.NS", "name": "HUL",               "weight": 2.5, "sector": "FMCG"},
    {"symbol": "BAJFINANCE.NS", "name": "Bajaj Finance",     "weight": 2.4, "sector": "NBFC"},
    {"symbol": "MARUTI.NS",     "name": "Maruti Suzuki",     "weight": 2.2, "sector": "Auto"},
    {"symbol": "ASIANPAINT.NS", "name": "Asian Paints",      "weight": 2.0, "sector": "Paints"},
    {"symbol": "M&M.NS",        "name": "M&M",               "weight": 1.8, "sector": "Auto"},
    {"symbol": "SUNPHARMA.NS",  "name": "Sun Pharma",        "weight": 1.7, "sector": "Pharma"},
    {"symbol": "HCLTECH.NS",    "name": "HCL Tech",          "weight": 1.6, "sector": "IT"},
    {"symbol": "TITAN.NS",      "name": "Titan",             "weight": 1.5, "sector": "Consumer"},
    {"symbol": "ULTRACEMCO.NS", "name": "UltraTech Cement",  "weight": 1.4, "sector": "Cement"},
    {"symbol": "WIPRO.NS",      "name": "Wipro",             "weight": 1.3, "sector": "IT"},
    {"symbol": "ADANIENT.NS",   "name": "Adani Enterprises", "weight": 1.3, "sector": "Conglomerate"},
    {"symbol": "NTPC.NS",       "name": "NTPC",              "weight": 1.2, "sector": "Power"},
    {"symbol": "BAJAJ-AUTO.NS", "name": "Bajaj Auto",        "weight": 1.2, "sector": "Auto"},
    {"symbol": "POWERGRID.NS",  "name": "Power Grid",        "weight": 1.2, "sector": "Power"},
]

SENSEX30_CONSTITUENTS = [
    {"symbol": "HDFCBANK.NS",   "name": "HDFC Bank",         "weight": 13.5, "sector": "Banks"},
    {"symbol": "RELIANCE.NS",   "name": "Reliance",          "weight": 12.0, "sector": "Energy"},
    {"symbol": "ICICIBANK.NS",  "name": "ICICI Bank",        "weight": 9.0,  "sector": "Banks"},
    {"symbol": "INFY.NS",       "name": "Infosys",           "weight": 6.7,  "sector": "IT"},
    {"symbol": "TCS.NS",        "name": "TCS",               "weight": 5.2,  "sector": "IT"},
    {"symbol": "ITC.NS",        "name": "ITC",               "weight": 4.8,  "sector": "FMCG"},
    {"symbol": "LT.NS",         "name": "L&T",               "weight": 4.5,  "sector": "Infra"},
    {"symbol": "SBIN.NS",       "name": "SBI",               "weight": 3.7,  "sector": "Banks"},
    {"symbol": "BHARTIARTL.NS", "name": "Bharti Airtel",     "weight": 3.5,  "sector": "Telecom"},
    {"symbol": "AXISBANK.NS",   "name": "Axis Bank",         "weight": 3.3,  "sector": "Banks"},
    {"symbol": "KOTAKBANK.NS",  "name": "Kotak Mahindra",    "weight": 3.2,  "sector": "Banks"},
    {"symbol": "HINDUNILVR.NS", "name": "HUL",               "weight": 3.1,  "sector": "FMCG"},
    {"symbol": "BAJFINANCE.NS", "name": "Bajaj Finance",     "weight": 2.9,  "sector": "NBFC"},
    {"symbol": "MARUTI.NS",     "name": "Maruti Suzuki",     "weight": 2.7,  "sector": "Auto"},
    {"symbol": "ASIANPAINT.NS", "name": "Asian Paints",      "weight": 2.4,  "sector": "Paints"},
    {"symbol": "M&M.NS",        "name": "M&M",               "weight": 2.2,  "sector": "Auto"},
    {"symbol": "SUNPHARMA.NS",  "name": "Sun Pharma",        "weight": 2.1,  "sector": "Pharma"},
    {"symbol": "HCLTECH.NS",    "name": "HCL Tech",          "weight": 1.9,  "sector": "IT"},
    {"symbol": "TITAN.NS",      "name": "Titan",             "weight": 1.8,  "sector": "Consumer"},
    {"symbol": "ULTRACEMCO.NS", "name": "UltraTech Cement",  "weight": 1.7,  "sector": "Cement"},
    {"symbol": "WIPRO.NS",      "name": "Wipro",             "weight": 1.6,  "sector": "IT"},
    {"symbol": "ADANIENT.NS",   "name": "Adani Enterprises", "weight": 1.5,  "sector": "Conglomerate"},
    {"symbol": "NTPC.NS",       "name": "NTPC",              "weight": 1.4,  "sector": "Power"},
    {"symbol": "HEROMOTOCO.NS", "name": "Hero MotoCorp",     "weight": 1.4,  "sector": "Auto"},
    {"symbol": "POWERGRID.NS",  "name": "Power Grid",        "weight": 1.4,  "sector": "Power"},
    {"symbol": "BAJAJFINSV.NS", "name": "Bajaj Finserv",     "weight": 1.7,  "sector": "NBFC"},
    {"symbol": "INDUSINDBK.NS", "name": "IndusInd Bank",     "weight": 1.3,  "sector": "Banks"},
    {"symbol": "NESTLEIND.NS",  "name": "Nestle India",      "weight": 1.2,  "sector": "FMCG"},
    {"symbol": "TECHM.NS",      "name": "Tech Mahindra",     "weight": 1.2,  "sector": "IT"},
    {"symbol": "TATASTEEL.NS",  "name": "Tata Steel",        "weight": 1.1,  "sector": "Metals"},
]

TIER1_SYMBOLS = {"HDFCBANK.NS", "RELIANCE.NS", "ICICIBANK.NS"}

SEARCH_QUERIES = {
    "NIFTY":    '"Nifty 50" stock market India',
    "SENSEX":   '"Sensex" OR "BSE Sensex" -defence -bankex -auto -PSU',
    "GOLD":     '"gold rate" OR "gold price" India',
    "SILVER":   '"silver rate" OR "silver price" India',
    "CRUDEOIL": '"Crude Oil" OR "Crude price" OR "Brent crude" India',
    "BITCOIN":  '"Bitcoin price" cryptocurrency'
}
SYMBOLS = list(SEARCH_QUERIES.keys())
FII_DII_SYMBOLS = {"NIFTY", "SENSEX"}

# ============================================================
# APP + CLIENT
# ============================================================
app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Gemini/Groq disabled — using keyword fallback for stability
client = None
gemini_client = None

# ============================================================
# CACHE
# ============================================================
CACHE = {}

def is_market_hours_now():
    now = datetime.now(IST)
    if now.weekday() >= 5:
        return False
    market_open = now.replace(hour=9, minute=15, second=0, microsecond=0)
    market_close = now.replace(hour=15, minute=30, second=0, microsecond=0)
    return market_open <= now <= market_close

def _auto_ttl_for_key(key):
    market_open = is_market_hours_now()
    if key.startswith("option_chain_"):
        return 180 if market_open else 1800
    if key.startswith("constituents_"):
        return 180 if market_open else 1800
    if key == "range":
        return 600 if market_open else 3600
    if key == "fii_dii_score":
        return 900 if market_open else 3600
    if key.startswith("sentiment_"):
        return 900 if market_open else 3600
    if key == "latest_scan":
        return 300 if market_open else 1800
    return 300 if market_open else 1800

def cache_get(key):
    if key in CACHE:
        value, timestamp, ttl = CACHE[key]
        if time.time() - timestamp < ttl:
            return value
        else:
            del CACHE[key]
    return None

def cache_set(key, value, ttl_seconds=None):
    if ttl_seconds is None:
        ttl_seconds = _auto_ttl_for_key(key)
    CACHE[key] = (value, time.time(), ttl_seconds)

def cache_peek(key):
    if key in CACHE:
        return CACHE[key][0]
    return None

# ============================================================
# SENTIMENT DB
# ============================================================
def init_sentiment_db():
    conn = sqlite3.connect(SENTIMENT_DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS daily_sentiment (
            date TEXT NOT NULL,
            symbol TEXT NOT NULL,
            score REAL NOT NULL,
            news_score REAL,
            twitter_score REAL,
            youtube_score REAL,
            fii_dii_score REAL,
            label TEXT,
            PRIMARY KEY (date, symbol)
        )
    """)
    try:
        cursor.execute("ALTER TABLE daily_sentiment ADD COLUMN fii_dii_score REAL")
    except sqlite3.OperationalError:
        pass
    conn.commit()
    conn.close()

def init_intraday_levels_db():
    """
    Base table (v1.2.0) + OI columns added in v1.4.0.
    ALTER TABLE additions are idempotent — safe to run on every boot.
    Existing rows will have NULL for the new columns; the shift/conviction
    logic treats NULLs as "unknown" and skips them.
    """
    conn = sqlite3.connect(SENTIMENT_DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS intraday_levels_history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            snapshot_at TEXT NOT NULL,
            date TEXT NOT NULL,
            symbol TEXT NOT NULL,
            spot REAL,
            support REAL,
            resistance REAL,
            max_pain REAL,
            pcr REAL,
            atm REAL,
            UNIQUE(snapshot_at, symbol)
        )
    """)
    # v1.4.0 — add OI columns (each ALTER is idempotent-safe)
    _new_cols = [
        ("total_call_oi", "REAL"),
        ("total_put_oi", "REAL"),
        ("net_coi", "REAL"),
        ("net_bias_score", "REAL"),
        ("net_bias_label", "TEXT"),
        ("support_oi", "REAL"),
        ("support_coi", "REAL"),
        ("resistance_oi", "REAL"),
        ("resistance_coi", "REAL"),
        ("vix", "REAL"),
        ("top_call_oi_strike", "REAL"),
        ("top_put_oi_strike", "REAL"),
        # v1.8.0: ATM-neighborhood OI ladder (ATM-2 to ATM+2)
        ("atm_m2_call_oi", "REAL"),
        ("atm_m2_call_coi", "REAL"),
        ("atm_m2_put_oi", "REAL"),
        ("atm_m2_put_coi", "REAL"),
        ("atm_m1_call_oi", "REAL"),
        ("atm_m1_call_coi", "REAL"),
        ("atm_m1_put_oi", "REAL"),
        ("atm_m1_put_coi", "REAL"),
        ("atm_0_call_oi", "REAL"),
        ("atm_0_call_coi", "REAL"),
        ("atm_0_put_oi", "REAL"),
        ("atm_0_put_coi", "REAL"),
        ("atm_p1_call_oi", "REAL"),
        ("atm_p1_call_coi", "REAL"),
        ("atm_p1_put_oi", "REAL"),
        ("atm_p1_put_coi", "REAL"),
        ("atm_p2_call_oi", "REAL"),
        ("atm_p2_call_coi", "REAL"),
        ("atm_p2_put_oi", "REAL"),
        ("atm_p2_put_coi", "REAL"),
        ("atm_strike", "REAL"),
        # v3.0.0: premium (LTP) + IV per strike, per side
        ("atm_m2_call_ltp", "REAL"),
        ("atm_m2_put_ltp", "REAL"),
        ("atm_m2_call_iv", "REAL"),
        ("atm_m2_put_iv", "REAL"),
        ("atm_m1_call_ltp", "REAL"),
        ("atm_m1_put_ltp", "REAL"),
        ("atm_m1_call_iv", "REAL"),
        ("atm_m1_put_iv", "REAL"),
        ("atm_0_call_ltp", "REAL"),
        ("atm_0_put_ltp", "REAL"),
        ("atm_0_call_iv", "REAL"),
        ("atm_0_put_iv", "REAL"),
        ("atm_0_call_vol", "REAL"),
        ("atm_0_put_vol", "REAL"),
        ("atm_p1_call_ltp", "REAL"),
        ("atm_p1_put_ltp", "REAL"),
        ("atm_p1_call_iv", "REAL"),
        ("atm_p1_put_iv", "REAL"),
        ("atm_p2_call_ltp", "REAL"),
        ("atm_p2_put_ltp", "REAL"),
        ("atm_p2_call_iv", "REAL"),
        ("atm_p2_put_iv", "REAL"),
    ]
    for col_name, col_type in _new_cols:
        try:
            cursor.execute(f"ALTER TABLE intraday_levels_history ADD COLUMN {col_name} {col_type}")
        except sqlite3.OperationalError:
            pass
    conn.commit()
    conn.close()

    # v1.18.0: full option chain history for execution replay
    try:
        _conn2 = sqlite3.connect(SENTIMENT_DB_PATH)
        _c2 = _conn2.cursor()
        _c2.execute("""
            CREATE TABLE IF NOT EXISTS option_chain_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                snapshot_at TEXT NOT NULL,
                symbol TEXT NOT NULL,
                expiry TEXT NOT NULL,
                strike REAL NOT NULL,
                call_ltp REAL,
                call_bid REAL,
                call_ask REAL,
                call_iv REAL,
                call_oi INTEGER,
                call_coi INTEGER,
                call_vol INTEGER,
                put_ltp REAL,
                put_bid REAL,
                put_ask REAL,
                put_iv REAL,
                put_oi INTEGER,
                put_coi INTEGER,
                put_vol INTEGER
            )
        """)
        _c2.execute("CREATE INDEX IF NOT EXISTS idx_och_time ON option_chain_history(snapshot_at)")
        _c2.execute("CREATE INDEX IF NOT EXISTS idx_och_strike ON option_chain_history(strike)")
        _conn2.commit()
        _conn2.close()
    except Exception as _e:
        print(f"[chain table] create error: {_e}")

def save_intraday_snapshot(symbol: str, data: dict, vix_value: float = None):
    """
    Snapshot the option-chain levels + OI data. Called on every refresh.
    v1.4.0 — persists OI fields; vix_value is optional.
    """
    if not data or data.get("error"):
        return
    try:
        now_ist = datetime.now(IST)
        snapshot_at = now_ist.strftime("%Y-%m-%d %H:%M")
        date_str = now_ist.strftime("%Y-%m-%d")

        oi_buildup = data.get("oi_buildup") or {}
        support = data.get("support") or {}
        resistance = data.get("resistance") or {}
        top_call = data.get("top_call_oi") or {}
        top_put = data.get("top_put_oi") or {}

        # v1.8.0: extract ATM-neighborhood
        atm_neigh = data.get("atm_neighborhood") or []
        by_pos = {}
        atm_strike_val = data.get("atm")
        if atm_neigh and atm_strike_val is not None:
            atm_val = float(atm_strike_val)
            for row in atm_neigh:
                try:
                    s = float(row.get("strike"))
                except (ValueError, TypeError):
                    continue
                if s < atm_val:
                    diff = atm_val - s
                    if diff <= 75: pos = "m1"
                    else: pos = "m2"
                elif s > atm_val:
                    diff = s - atm_val
                    if diff <= 75: pos = "p1"
                    else: pos = "p2"
                else:
                    pos = "0"
                by_pos[pos] = row

        def _atm_field(pos, field):
            r = by_pos.get(pos)
            if not r:
                return None
            v = r.get(field)
            if v is None:
                return None
            try:
                fv = float(v)
                # v3.0.0: treat 0.0 IV as "no value" (exchange couldn't compute)
                if field.endswith("_iv") and fv == 0.0:
                    return None
                return fv
            except (ValueError, TypeError):
                return None

        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("""
            INSERT OR REPLACE INTO intraday_levels_history
            (snapshot_at, date, symbol, spot, support, resistance, max_pain, pcr, atm,
             total_call_oi, total_put_oi, net_coi, net_bias_score, net_bias_label,
             support_oi, support_coi, resistance_oi, resistance_coi, vix,
             top_call_oi_strike, top_put_oi_strike,
             atm_m2_call_oi, atm_m2_call_coi, atm_m2_put_oi, atm_m2_put_coi,
             atm_m1_call_oi, atm_m1_call_coi, atm_m1_put_oi, atm_m1_put_coi,
             atm_0_call_oi, atm_0_call_coi, atm_0_put_oi, atm_0_put_coi,
             atm_p1_call_oi, atm_p1_call_coi, atm_p1_put_oi, atm_p1_put_coi,
             atm_p2_call_oi, atm_p2_call_coi, atm_p2_put_oi, atm_p2_put_coi,
             atm_strike,
             atm_m2_call_ltp, atm_m2_put_ltp, atm_m2_call_iv, atm_m2_put_iv,
             atm_m1_call_ltp, atm_m1_put_ltp, atm_m1_call_iv, atm_m1_put_iv,
             atm_0_call_ltp, atm_0_put_ltp, atm_0_call_iv, atm_0_put_iv, atm_0_call_vol, atm_0_put_vol,
             atm_p1_call_ltp, atm_p1_put_ltp, atm_p1_call_iv, atm_p1_put_iv,
             atm_p2_call_ltp, atm_p2_put_ltp, atm_p2_call_iv, atm_p2_put_iv)
            VALUES (
                :snapshot_at, :date, :symbol, :spot, :support, :resistance,
                :max_pain, :pcr, :atm, :total_call_oi, :total_put_oi, :net_coi,
                :net_bias_score, :net_bias_label, :support_oi, :support_coi,
                :resistance_oi, :resistance_coi, :vix, :top_call_oi_strike,
                :top_put_oi_strike,
                :atm_m2_call_oi, :atm_m2_call_coi, :atm_m2_put_oi, :atm_m2_put_coi,
                :atm_m1_call_oi, :atm_m1_call_coi, :atm_m1_put_oi, :atm_m1_put_coi,
                :atm_0_call_oi, :atm_0_call_coi, :atm_0_put_oi, :atm_0_put_coi,
                :atm_p1_call_oi, :atm_p1_call_coi, :atm_p1_put_oi, :atm_p1_put_coi,
                :atm_p2_call_oi, :atm_p2_call_coi, :atm_p2_put_oi, :atm_p2_put_coi,
                :atm_strike,
                :atm_m2_call_ltp, :atm_m2_put_ltp, :atm_m2_call_iv, :atm_m2_put_iv,
                :atm_m1_call_ltp, :atm_m1_put_ltp, :atm_m1_call_iv, :atm_m1_put_iv,
                :atm_0_call_ltp, :atm_0_put_ltp, :atm_0_call_iv, :atm_0_put_iv, :atm_0_call_vol, :atm_0_put_vol,
                :atm_p1_call_ltp, :atm_p1_put_ltp, :atm_p1_call_iv, :atm_p1_put_iv,
                :atm_p2_call_ltp, :atm_p2_put_ltp, :atm_p2_call_iv, :atm_p2_put_iv
            )
        """, {
            "snapshot_at": snapshot_at,
            "date": date_str,
            "symbol": symbol,
            "spot": data.get("spot"),
            "support": support.get("level"),
            "resistance": resistance.get("level"),
            "max_pain": data.get("max_pain"),
            "pcr": data.get("pcr"),
            "atm": data.get("atm"),
            "total_call_oi": data.get("total_call_oi"),
            "total_put_oi": data.get("total_put_oi"),
            "net_coi": oi_buildup.get("net_coi"),
            "net_bias_score": oi_buildup.get("net_bias_score"),
            "net_bias_label": oi_buildup.get("net_bias_label"),
            "support_oi": support.get("put_oi"),
            "support_coi": support.get("put_coi"),
            "resistance_oi": resistance.get("call_oi"),
            "resistance_coi": resistance.get("call_coi"),
            "vix": vix_value,
            "top_call_oi_strike": top_call.get("strike"),
            "top_put_oi_strike": top_put.get("strike"),
            "atm_m2_call_oi": _atm_field("m2", "call_oi"),
            "atm_m2_call_coi": _atm_field("m2", "call_coi"),
            "atm_m2_put_oi": _atm_field("m2", "put_oi"),
            "atm_m2_put_coi": _atm_field("m2", "put_coi"),
            "atm_m1_call_oi": _atm_field("m1", "call_oi"),
            "atm_m1_call_coi": _atm_field("m1", "call_coi"),
            "atm_m1_put_oi": _atm_field("m1", "put_oi"),
            "atm_m1_put_coi": _atm_field("m1", "put_coi"),
            "atm_0_call_oi": _atm_field("0", "call_oi"),
            "atm_0_call_coi": _atm_field("0", "call_coi"),
            "atm_0_put_oi": _atm_field("0", "put_oi"),
            "atm_0_put_coi": _atm_field("0", "put_coi"),
            "atm_p1_call_oi": _atm_field("p1", "call_oi"),
            "atm_p1_call_coi": _atm_field("p1", "call_coi"),
            "atm_p1_put_oi": _atm_field("p1", "put_oi"),
            "atm_p1_put_coi": _atm_field("p1", "put_coi"),
            "atm_p2_call_oi": _atm_field("p2", "call_oi"),
            "atm_p2_call_coi": _atm_field("p2", "call_coi"),
            "atm_p2_put_oi": _atm_field("p2", "put_oi"),
            "atm_p2_put_coi": _atm_field("p2", "put_coi"),
            # v3.0.0: LTP + IV per slot
            "atm_m2_call_ltp": _atm_field("m2", "call_ltp"),
            "atm_m2_put_ltp":  _atm_field("m2", "put_ltp"),
            "atm_m2_call_iv":  _atm_field("m2", "call_iv"),
            "atm_m2_put_iv":   _atm_field("m2", "put_iv"),
            "atm_m1_call_ltp": _atm_field("m1", "call_ltp"),
            "atm_m1_put_ltp":  _atm_field("m1", "put_ltp"),
            "atm_m1_call_iv":  _atm_field("m1", "call_iv"),
            "atm_m1_put_iv":   _atm_field("m1", "put_iv"),
            "atm_0_call_ltp":  _atm_field("0", "call_ltp"),
            "atm_0_put_ltp":   _atm_field("0", "put_ltp"),
            "atm_0_call_iv":   _atm_field("0", "call_iv"),
            "atm_0_put_iv":    _atm_field("0", "put_iv"),
            "atm_0_call_vol":  _atm_field("0", "call_vol"),
            "atm_0_put_vol":   _atm_field("0", "put_vol"),
            "atm_p1_call_ltp": _atm_field("p1", "call_ltp"),
            "atm_p1_put_ltp":  _atm_field("p1", "put_ltp"),
            "atm_p1_call_iv":  _atm_field("p1", "call_iv"),
            "atm_p1_put_iv":   _atm_field("p1", "put_iv"),
            "atm_p2_call_ltp": _atm_field("p2", "call_ltp"),
            "atm_p2_put_ltp":  _atm_field("p2", "put_ltp"),
            "atm_p2_call_iv":  _atm_field("p2", "call_iv"),
            "atm_p2_put_iv":   _atm_field("p2", "put_iv"),
            "atm_strike": atm_strike_val,
        })
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"[Intraday snapshot] save error for {symbol}: {e}")

def _prev_atm_ladder(symbol="NIFTY"):
    """
    v1.11.1 — Return the most recent ATM ladder from intraday_levels_history
    as a list of 5 dicts: [{strike, call_oi, call_coi, put_oi, put_coi}, ...].
    Used to compute delta in OI at a shifted level vs prior snapshot.
    Returns [] if nothing is available.
    """
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        today_str = datetime.now(IST).strftime("%Y-%m-%d")
        c.execute("""
            SELECT atm_strike,
                   atm_m2_call_oi, atm_m2_call_coi, atm_m2_put_oi, atm_m2_put_coi,
                   atm_m1_call_oi, atm_m1_call_coi, atm_m1_put_oi, atm_m1_put_coi,
                   atm_0_call_oi,  atm_0_call_coi,  atm_0_put_oi,  atm_0_put_coi,
                   atm_p1_call_oi, atm_p1_call_coi, atm_p1_put_oi, atm_p1_put_coi,
                   atm_p2_call_oi, atm_p2_call_coi, atm_p2_put_oi, atm_p2_put_coi
            FROM intraday_levels_history
            WHERE symbol = ? AND date = ?
            ORDER BY snapshot_at DESC LIMIT 1
        """, (symbol, today_str))
        row = c.fetchone()
        conn.close()
        if not row or row[0] is None:
            return []
        atm = float(row[0])
        interval = 50.0  # NIFTY default; fallback only
        slots = [atm - 2*interval, atm - interval, atm, atm + interval, atm + 2*interval]
        keys = [0, 1, 2, 3, 4]
        out = []
        for i in keys:
            base = 1 + i * 4
            out.append({
                "strike": slots[i],
                "call_oi":  row[base + 0],
                "call_coi": row[base + 1],
                "put_oi":   row[base + 2],
                "put_coi":  row[base + 3],
            })
        return out
    except Exception as e:
        print(f"[_prev_atm_ladder] {e}")
        return []


def get_previous_intraday_levels(symbol: str) -> dict:
    """
    v1.4.0 — Same-day filter. Returns the most recent snapshot from TODAY
    strictly before the current minute. Prevents cross-day false positives
    (the 09:02 burst issue).
    """
    try:
        now_ist = datetime.now(IST)
        current_window = now_ist.strftime("%Y-%m-%d %H:%M")
        today_str = now_ist.strftime("%Y-%m-%d")
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("""
            SELECT snapshot_at, spot, support, resistance, max_pain, pcr, atm,
                   total_call_oi, total_put_oi, net_coi, net_bias_score, net_bias_label,
                   support_oi, support_coi, resistance_oi, resistance_coi, vix,
                   top_call_oi_strike, top_put_oi_strike
            FROM intraday_levels_history
            WHERE symbol = ? AND date = ? AND snapshot_at < ?
            ORDER BY snapshot_at DESC
            LIMIT 1
        """, (symbol, today_str, current_window))
        row = c.fetchone()
        conn.close()
        if not row:
            return {}
        return {
            "snapshot_at": row[0],
            "prev_spot": row[1],
            "prev_support": row[2],
            "prev_resistance": row[3],
            "prev_max_pain": row[4],
            "prev_pcr": row[5],
            "prev_atm": row[6],
            "prev_total_call_oi": row[7],
            "prev_total_put_oi": row[8],
            "prev_net_coi": row[9],
            "prev_net_bias_score": row[10],
            "prev_net_bias_label": row[11],
            "prev_support_oi": row[12],
            "prev_support_coi": row[13],
            "prev_resistance_oi": row[14],
            "prev_resistance_coi": row[15],
            "prev_vix": row[16],
            "prev_top_call_oi_strike": row[17],
            "prev_top_put_oi_strike": row[18],
            # v1.11.1: prior ATM ladder so shift context can compute deltas
            "prev_atm_neighborhood": _prev_atm_ladder(symbol),
        }
    except Exception as e:
        print(f"[Intraday snapshot] read error for {symbol}: {e}")
        return {}

def get_level_history(symbol: str, strike: float, zone_type: str, minutes: int = 60) -> list:
    """
    v1.4.0 — Track a specific strike's OI over the last N minutes for today.
    zone_type: 'support' (reads put OI columns) or 'resistance' (reads call OI columns).
    Returns list of dicts with {snapshot_at, oi, coi}. Empty if no history.
    """
    if strike is None:
        return []
    try:
        now_ist = datetime.now(IST)
        cutoff_ist = now_ist - timedelta(minutes=minutes)
        cutoff_str = cutoff_ist.strftime("%Y-%m-%d %H:%M")
        today_str = now_ist.strftime("%Y-%m-%d")
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        if zone_type == "support":
            c.execute("""
                SELECT snapshot_at, support_oi, support_coi
                FROM intraday_levels_history
                WHERE symbol = ? AND date = ? AND snapshot_at >= ?
                  AND support = ?
                ORDER BY snapshot_at ASC
            """, (symbol, today_str, cutoff_str, strike))
        else:
            c.execute("""
                SELECT snapshot_at, resistance_oi, resistance_coi
                FROM intraday_levels_history
                WHERE symbol = ? AND date = ? AND snapshot_at >= ?
                  AND resistance = ?
                ORDER BY snapshot_at ASC
            """, (symbol, today_str, cutoff_str, strike))
        rows = c.fetchall()
        conn.close()
        return [{"snapshot_at": r[0], "oi": r[1], "coi": r[2]} for r in rows]
    except Exception as e:
        print(f"[Level history] read error for {symbol} {strike}: {e}")
        return []

def compute_conviction(symbol: str, strike: float, current_oi: float,
                       current_coi: float, zone_type: str) -> dict:
    """
    v1.4.0 — Conviction score 0..100 for a given S/R strike.

    Components:
      absolute   = current_oi / peak_oi_today          (0..1)
      freshness  = clamp(coi / (current_oi * 0.3), 0, 1)  (0..1)
      trend      = +1 rising / -1 falling / 0 flat     (last 3 snapshots)

    Score = 100 * (0.6*absolute + 0.4*freshness + 0.2*trend) / 1.2
    Label: STRONG / MODERATE / WEAK; FADING overrides when trend < 0.
    """
    out = {
        "score": None, "label": "UNKNOWN", "fading": False,
        "current_oi": current_oi, "peak_oi": current_oi,
        "current_coi": current_coi, "trend": 0, "history_points": 0
    }
    if strike is None or current_oi is None or current_oi <= 0:
        return out

    history = get_level_history(symbol, strike, zone_type, minutes=120)
    oi_series = [h["oi"] for h in history if h["oi"] is not None]

    peak_oi = max(oi_series) if oi_series else current_oi
    if peak_oi <= 0:
        peak_oi = current_oi

    absolute = max(0.0, min(1.0, current_oi / peak_oi))

    if current_coi is not None and current_oi > 0:
        freshness = max(0.0, min(1.0, current_coi / (current_oi * 0.3)))
    else:
        freshness = 0.0

    trend = 0
    if len(oi_series) >= 3:
        last3 = oi_series[-3:]
        if last3[-1] > last3[0]:
            trend = 1
        elif last3[-1] < last3[0]:
            trend = -1

    raw = (CONVICTION_W_ABSOLUTE * absolute
           + CONVICTION_W_FRESHNESS * freshness
           + CONVICTION_W_TREND * trend)
    score = max(0.0, min(100.0, 100.0 * raw / CONVICTION_W_SUM))

    if score >= CONVICTION_STRONG:
        label = "STRONG"
    elif score >= CONVICTION_MODERATE:
        label = "MODERATE"
    else:
        label = "WEAK"

    fading = (trend < 0)
    if fading and label != "WEAK":
        label = f"{label} (FADING)"
    elif fading:
        label = "WEAK (FADING)"

    out.update({
        "score": round(score, 1),
        "label": label,
        "fading": fading,
        "peak_oi": peak_oi,
        "trend": trend,
        "history_points": len(oi_series)
    })
    return out

def save_to_history(symbol: str, result: dict):
    today = datetime.now(IST).strftime("%Y-%m-%d")
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        cursor = conn.cursor()
        cursor.execute("""
            INSERT OR REPLACE INTO daily_sentiment
            (date, symbol, score, news_score, twitter_score, youtube_score, fii_dii_score, label)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            today, symbol,
            result.get("score", 0),
            result.get("news_score", 0),
            result.get("twitter_score", 0),
            result.get("youtube_score", 0),
            result.get("fii_dii_score", 0),
            result.get("label", "NEUTRAL")
        ))
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"Sentiment DB save error for {symbol}: {e}")

def get_history(symbol: str, days: int = 7) -> list:
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        cursor = conn.cursor()
        cursor.execute("""
            SELECT date, score, label FROM daily_sentiment
            WHERE symbol = ?
            ORDER BY date DESC
            LIMIT ?
        """, (symbol, days))
        rows = cursor.fetchall()
        conn.close()
        return [{"date": r[0], "score": r[1], "label": r[2]} for r in reversed(rows)]
    except Exception as e:
        print(f"Sentiment DB read error for {symbol}: {e}")
        return []

init_sentiment_db()
init_intraday_levels_db()

# ============================================================
# MACRO EVENTS DB (v1.5.0)
# ============================================================

# ============================================================
# v1.8.0 — ATM-NEIGHBORHOOD QUERY + DETECTOR
# ============================================================
def get_oi_neighborhood(symbol):
    """
    Return current ATM-neighborhood OI ladder for a symbol,
    plus the previous snapshot for delta comparison.
    """
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        now_ist = datetime.now(IST)
        today_str = now_ist.strftime("%Y-%m-%d")

        c.execute("""
            SELECT snapshot_at, atm_strike,
                   atm_m2_call_oi, atm_m2_call_coi, atm_m2_put_oi, atm_m2_put_coi,
                   atm_m1_call_oi, atm_m1_call_coi, atm_m1_put_oi, atm_m1_put_coi,
                   atm_0_call_oi,  atm_0_call_coi,  atm_0_put_oi,  atm_0_put_coi,
                   atm_p1_call_oi, atm_p1_call_coi, atm_p1_put_oi, atm_p1_put_coi,
                   atm_p2_call_oi, atm_p2_call_coi, atm_p2_put_oi, atm_p2_put_coi
            FROM intraday_levels_history
            WHERE symbol = ? AND date = ?
              AND atm_strike IS NOT NULL
            ORDER BY snapshot_at DESC
            LIMIT 2
        """, (symbol, today_str))
        rows = c.fetchall()
        conn.close()

        if not rows:
            return {"symbol": symbol, "available": False, "reason": "no_snapshot"}

        def _row_to_ladder(r):
            return {
                "snapshot_at": r[0],
                "atm_strike": r[1],
                "ladder": [
                    {"position": "m2", "strike": r[1] - 100, "call_oi": r[2], "call_coi": r[3], "put_oi": r[4], "put_coi": r[5]},
                    {"position": "m1", "strike": r[1] - 50,  "call_oi": r[6], "call_coi": r[7], "put_oi": r[8], "put_coi": r[9]},
                    {"position": "0",  "strike": r[1],       "call_oi": r[10], "call_coi": r[11], "put_oi": r[12], "put_coi": r[13]},
                    {"position": "p1", "strike": r[1] + 50,  "call_oi": r[14], "call_coi": r[15], "put_oi": r[16], "put_coi": r[17]},
                    {"position": "p2", "strike": r[1] + 100, "call_oi": r[18], "call_coi": r[19], "put_oi": r[20], "put_coi": r[21]},
                ]
            }

        current = _row_to_ladder(rows[0])
        previous = _row_to_ladder(rows[1]) if len(rows) >= 2 else None

        return {
            "symbol": symbol,
            "available": True,
            "current": current,
            "previous": previous,
        }
    except Exception as e:
        print(f"[ATM neighborhood] error for {symbol}: {e}")
        return {"symbol": symbol, "available": False, "error": str(e)[:200]}

def detect_oi_surge(symbol):
    """
    v1.8.0 — Detect strikes where COI changed dramatically vs previous snapshot.
    Returns list of surge events with direction and magnitude.
    """
    nb = get_oi_neighborhood(symbol)
    if not nb.get("available") or not nb.get("previous"):
        return []

    surges = []
    cur_ladder = {r["position"]: r for r in nb["current"]["ladder"]}
    prev_ladder = {r["position"]: r for r in nb["previous"]["ladder"]}

    for pos in ("m2", "m1", "0", "p1", "p2"):
        c = cur_ladder.get(pos)
        p = prev_ladder.get(pos)
        if not c or not p:
            continue

        for side, oi_key, coi_key, label in [
            ("call", "call_oi", "call_coi", "CALL"),
            ("put", "put_oi", "put_coi", "PUT"),
        ]:
            cur_coi = c.get(coi_key) or 0
            prev_coi = p.get(coi_key) or 0
            delta = cur_coi - prev_coi
            if abs(delta) < ATM_SURGE_MIN_ABS:
                continue
            base = abs(prev_coi) or 1
            pct = (delta / base) * 100
            if abs(pct) < ATM_SURGE_THRESHOLD_PCT:
                continue
            surges.append({
                "position": pos,
                "strike": c.get("strike"),
                "side": label,
                "delta_coi": delta,
                "pct_change": round(pct, 1),
                "current_coi": cur_coi,
                "prior_coi": prev_coi,
                "current_oi": c.get(oi_key),
            })
    return surges


# ============================================================
# v1.8.3 — Flash alert helpers
# ============================================================
def _magnitude_tier(abs_value):
    """Return tier label based on absolute magnitude."""
    for threshold, label in FLASH_MAGNITUDE_TIERS:
        if abs_value >= threshold:
            return label
    return "SIGNAL"

def _flash_payload(event):
    """
    Wrap an event dict with flash metadata if it qualifies.
    Returns dict with flash=True flag, or None if not flash-worthy.
    """
    etype = event.get("type", "")
    if etype not in FLASH_TYPES:
        return None
    # v1.11.0: only MAJOR/CRITICAL events flash as toast
    level = event.get("level", "SIGNAL")
    if level not in FLASH_TOAST_LEVELS:
        return None
    return {
        "type": etype,
        "level": level,
        "icon": event.get("icon", "⚡"),
        "message": event.get("message", ""),
        "suggested_action": event.get("suggested_action"),
        "ts": datetime.now(IST).isoformat(),
        "macro_context": event.get("macro_context"),
        # v1.11.1: preserve the shift-context metadata that was attached
        # to the source event. _flash_payload used to rebuild the dict
        # from scratch and silently drop it.
        "metadata": event.get("metadata"),
    }

def collect_flash_alerts():
    """
    v1.8.3 — Return list of flash-worthy events from the last N minutes.
    v1.11.1 — HARD GATE: no flash alerts outside market hours (kills 05:00 AM spam).
    """
    # v1.31.3: Removed market hours gate. Alerts run 24/7 based on latest data.
    cache_key = "flash_alerts_recent"
    cached = cache_get(cache_key)
    if cached is not None:
        return cached

    try:
        events = generate_action_events()
        flashes = []
        for ev in events:
            payload = _flash_payload(ev)
            if payload:
                flashes.append(payload)
        # Cap
        flashes = flashes[:FLASH_MAX_EVENTS]
        # Cache for a short window so repeated frontend polls don't burn CPU
        cache_set(cache_key, flashes, ttl_seconds=60)
        return flashes
    except Exception as e:
        print(f"[Flash] collect error: {e}")
        return []


# ============================================================
# v1.9.0 — Narrative data loaders
# ============================================================
def get_recent_snapshots(symbol="NIFTY", minutes=None, limit=10):
    """Fetch recent snapshots from today for delta computation."""
    if minutes is None:
        minutes = NARRATIVE_WINDOW_MIN
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        now_ist = datetime.now(IST)
        today_str = now_ist.strftime("%Y-%m-%d")
        cutoff = (now_ist - timedelta(minutes=minutes)).strftime("%Y-%m-%d %H:%M")

        c.execute("""
            SELECT snapshot_at, spot, support, resistance, pcr,
                   support_oi, support_coi, resistance_oi, resistance_coi,
                   net_bias_score, net_bias_label,
                   atm_strike, atm_0_put_oi, atm_0_call_oi,
                   atm_0_put_coi, atm_0_call_coi,
                   atm_m1_put_coi, atm_m1_call_coi,
                   atm_p1_put_coi, atm_p1_call_coi
            FROM intraday_levels_history
            WHERE symbol = ? AND date = ? AND snapshot_at >= ?
            ORDER BY snapshot_at ASC
            LIMIT ?
        """, (symbol, today_str, cutoff, limit))
        rows = c.fetchall()
        conn.close()
        return [{
            "snapshot_at": r[0], "spot": r[1],
            "support": r[2], "resistance": r[3], "pcr": r[4],
            "support_oi": r[5], "support_coi": r[6],
            "resistance_oi": r[7], "resistance_coi": r[8],
            "net_bias_score": r[9], "net_bias_label": r[10],
            "atm_strike": r[11],
            "atm_0_put_oi": r[12], "atm_0_call_oi": r[13],
            "atm_0_put_coi": r[14], "atm_0_call_coi": r[15],
            "atm_m1_put_coi": r[16], "atm_m1_call_coi": r[17],
            "atm_p1_put_coi": r[18], "atm_p1_call_coi": r[19],
        } for r in rows]
    except Exception as e:
        print(f"[Narrative] snapshot read error: {e}")
        return []

def get_rolling_coi_delta(symbol="NIFTY", side="put", minutes=None):
    """
    Compute how much COI was added on one side over the lookback window.
    side: 'put' (support) or 'call' (resistance).
    Returns dict: {delta, latest_oi, earliest_oi, snapshots_used}
    """
    snaps = get_recent_snapshots(symbol, minutes=minutes)
    if len(snaps) < 2:
        return {"delta": 0, "latest_oi": None, "earliest_oi": None, "snapshots_used": len(snaps)}
    if side == "put":
        oi_key, coi_key = "support_oi", "support_coi"
    else:
        oi_key, coi_key = "resistance_oi", "resistance_coi"
    earliest = snaps[0]
    latest = snaps[-1]
    # Latest COI is cumulative for the day at that strike
    # We compare against the strike's COI at the earliest snapshot
    earliest_coi = earliest.get(coi_key) or 0
    latest_coi = latest.get(coi_key) or 0
    delta = latest_coi - earliest_coi
    return {
        "delta": delta,
        "latest_oi": latest.get(oi_key),
        "earliest_oi": earliest.get(oi_key),
        "snapshots_used": len(snaps),
        "window_min": minutes or NARRATIVE_WINDOW_MIN,
    }

def get_latest_conviction(symbol="NIFTY"):
    """Compute current support + resistance conviction from latest option chain."""
    try:
        oc = fetch_option_chain_levels(symbol)
        conv = oc.get("conviction") or {}
        # v1.11.2: also expose top-level OI/COI so commentary can cite them
        top_sup = oc.get("support") or {}
        top_res = oc.get("resistance") or {}

        # v1.15.0 FIX: If conviction block missing (API shape changed), compute inline
        if not conv or not conv.get("support") or not conv.get("resistance"):
            spot_val = oc.get("spot") or 0
            sup_lvl = top_sup.get("level") or 0
            res_lvl = top_res.get("level") or 0
            sup_oi = top_sup.get("put_oi") or 0
            res_oi = top_res.get("call_oi") or 0
            sup_coi = top_sup.get("put_coi") or 0
            res_coi = top_res.get("call_coi") or 0

            # Compute support conviction: how far above the support level are we,
            # plus how much put OI exists (with COI as a bull booster)
            if spot_val > 0 and sup_lvl > 0:
                distance_pct = ((spot_val - sup_lvl) / sup_lvl) * 100
                proximity_score = max(0, min(50, 50 - abs(distance_pct) * 20))
                oi_score = min(50, (sup_oi / 300000) * 50)
                coi_bonus = 15 if sup_coi > 100000 else (8 if sup_coi > 50000 else 0)
                sup_score = min(100, proximity_score + oi_score + coi_bonus)
            else:
                sup_score = 0

            # Compute resistance conviction
            if spot_val > 0 and res_lvl > 0:
                distance_pct = ((res_lvl - spot_val) / res_lvl) * 100
                proximity_score = max(0, min(50, 50 - abs(distance_pct) * 20))
                oi_score = min(50, (res_oi / 300000) * 50)
                coi_bonus = 15 if res_coi > 100000 else (8 if res_coi > 50000 else 0)
                res_score = min(100, proximity_score + oi_score + coi_bonus)
            else:
                res_score = 0

            conv = {
                "support": {"score": sup_score, "level": sup_lvl},
                "resistance": {"score": res_score, "level": res_lvl},
            }

        return {
            "support": conv.get("support", {}),
            "resistance": conv.get("resistance", {}),
            "spot": oc.get("spot"),
            "support_level": top_sup.get("level"),
            "resistance_level": top_res.get("level"),
            "support_oi": top_sup.get("put_oi"),
            "support_coi": top_sup.get("put_coi"),
            "resistance_oi": top_res.get("call_oi"),
            "resistance_coi": top_res.get("call_coi"),
            "atm": oc.get("atm"),
            "pcr": oc.get("pcr"),
        }
    except Exception as e:
        print(f"[Narrative] conviction fetch error: {e}")
        return {}


# ============================================================
# v1.9.0 — Dynamic commentary + Day Direction
# ============================================================
def build_dynamic_commentary(symbol="NIFTY"):
    """
    Generate the human-readable commentary sentence.
    Example: "Support at 22300 level. Support hardened with +1,20,485
              new put writers in the last 15 minutes. There is a
              chance of market going up."
    Returns dict: {sentence, direction, parts}
    """
    try:
        # v1.15.0: Market hours gate
        if not is_market_hours_now():
            return {"available": False, "reason": "market_closed"}

        data = get_latest_conviction(symbol)
        if not data:
            return {"sentence": "Market structure data unavailable.",
                    "direction": "NEUTRAL", "parts": []}

        sup_level = data.get("support_level")
        res_level = data.get("resistance_level")
        sup_conv = data.get("support", {}).get("score")
        res_conv = data.get("resistance", {}).get("score")

        put_delta = get_rolling_coi_delta(symbol, "put")
        call_delta = get_rolling_coi_delta(symbol, "call")

        parts = []
        direction = "NEUTRAL"

        # --- Support side ---
        # v1.11.2: pull strike-level OI + today COI for enriched narrative
        # (these live at data top-level, not inside the conviction dict)
        sup_oi = data.get("support_oi") or 0
        sup_coi_today = data.get("support_coi") or 0
        res_oi = data.get("resistance_oi") or 0
        res_coi_today = data.get("resistance_coi") or 0

        def _action_suffix(conv, side, level):
            """Actionable advice tuned to conviction tier."""
            if conv is None:
                return "Watch this level for confirmation before committing."
            if conv >= 85:
                if side == "support":
                    return (f"Watch for further OI additions at {int(level)} — "
                            f"if put writers keep building, look for bullish trades only "
                            f"(buy dips, avoid shorts). If put OI starts unwinding, support may crack.")
                else:
                    return (f"Watch for OI additions at {int(level)} — "
                            f"if call writers defend aggressively, expect a stall and avoid longs. "
                            f"If call OI starts unwinding, a breakout above is likely.")
            if conv >= 70:
                if side == "support":
                    return (f"Watch for further OI additions at {int(level)} — "
                            f"if put writers keep building, favour bullish setups on dips.")
                else:
                    return (f"Watch for OI additions at {int(level)} — "
                            f"if call writers defend, expect resistance to hold; "
                            f"if they pull back, a breakout may follow.")
            if conv >= 60:
                return f"Level at {int(level)} is forming — wait for confirmation before committing."
            return f"Level at {int(level)} is untested — trade with tighter stops."

        # v1.12.0: Max Pain Pin & PCR Squeeze Check
        spot = data.get("spot") or 0
        max_pain = data.get("max_pain") or 0
        pcr = data.get("pcr") or 0
        
        if spot and max_pain:
            dist_pct = abs(spot - max_pain) / spot * 100
            if dist_pct < 0.15:
                parts.append(f"⚠️ PIN RISK: Nifty is pinned near Max Pain ({int(max_pain)}). Expect range-bound chop as sellers defend.")
                direction = "NEUTRAL"
            elif pcr > 1.3:
                parts.append(f"🚀 SQUEEZE ALERT: PCR is high ({pcr:.2f}). Heavy put writing detected.")
                direction = "BULLISH"
            elif pcr < 0.6:
                parts.append(f"🩸 SQUEEZE ALERT: PCR is low ({pcr:.2f}). Heavy call writing detected.")
                direction = "BEARISH"

        if sup_level is not None:
            put_d = put_delta.get("delta") or 0
            if put_d >= NARRATIVE_COI_SIGNIFICANT and (sup_conv or 0) >= NARRATIVE_CONVICTION_STRONG:
                # Hardened branch
                parts.append(
                    f"Support at {int(sup_level)} hardened — "
                    f"+{int(put_d):,} new put writers in the last "
                    f"{put_delta.get('window_min', NARRATIVE_WINDOW_MIN)} minutes. "
                    f"Bias is bullish while this holds."
                )
                direction = "BULLISH"
            elif put_d <= -NARRATIVE_COI_SIGNIFICANT:
                parts.append(
                    f"Support at {int(sup_level)} weakened — "
                    f"{int(abs(put_d)):,} put writers pulled back in the last "
                    f"{put_delta.get('window_min', NARRATIVE_WINDOW_MIN)} minutes. "
                    f"Watch for a breakdown."
                )
                direction = "BEARISH"
            elif sup_conv is not None:
                # Enriched sentence (this is the path that fires when
                # there is no fresh rolling delta but conviction is high)
                state = "strong" if sup_conv >= NARRATIVE_CONVICTION_STRONG else (
                        "moderate" if sup_conv >= NARRATIVE_CONVICTION_WEAK else "weak")
                sup_oi_str = f"{int(sup_oi):,}" if sup_oi else "—"
                sup_coi_str = f"+{int(sup_coi_today):,}" if sup_coi_today >= 0 else f"{int(sup_coi_today):,}"
                parts.append(
                    f"Support at {int(sup_level)} is {state} ({sup_conv:.0f}%). "
                    f"Put writers are defending this level — "
                    f"{sup_oi_str} put OI ({sup_coi_str} COI today). "
                    f"Bias is bullish while this holds. "
                    f"{_action_suffix(sup_conv, 'support', sup_level)}"
                )
                if sup_conv >= NARRATIVE_CONVICTION_STRONG:
                    direction = "BULLISH"

        # --- Resistance side ---
        if res_level is not None:
            call_d = call_delta.get("delta") or 0
            if call_d >= NARRATIVE_COI_SIGNIFICANT and (res_conv or 0) >= NARRATIVE_CONVICTION_STRONG:
                parts.append(
                    f"Resistance at {int(res_level)} hardened with "
                    f"+{int(call_d):,} new call writers — upside capped."
                )
                if direction == "NEUTRAL":
                    direction = "BEARISH"
            elif call_d <= -NARRATIVE_COI_SIGNIFICANT:
                parts.append(
                    f"Resistance at {int(res_level)} weakened — "
                    f"{int(abs(call_d)):,} call writers pulled back — breakout potential."
                )
                if direction == "NEUTRAL":
                    direction = "BULLISH"
            elif res_conv is not None:
                # Enriched mirror sentence
                state = "strong" if res_conv >= NARRATIVE_CONVICTION_STRONG else (
                        "moderate" if res_conv >= NARRATIVE_CONVICTION_WEAK else "weak")
                res_oi_str = f"{int(res_oi):,}" if res_oi else "—"
                res_coi_str = f"+{int(res_coi_today):,}" if res_coi_today >= 0 else f"{int(res_coi_today):,}"
                parts.append(
                    f"Resistance at {int(res_level)} is {state} ({res_conv:.0f}%). "
                    f"Call writers hold {res_oi_str} call OI ({res_coi_str} COI today). "
                    f"{_action_suffix(res_conv, 'resistance', res_level)}"
                )

        # --- v1.9.1: defer to day_direction if it has a clear call ---
        day_dir = build_day_direction(symbol)
        if day_dir.get("available") and day_dir.get("direction") in ("BULLISH", "BEARISH"):
            direction = day_dir["direction"]

        # --- v1.10.0: range-locked check ---
        rl = detect_range_locked(symbol)
        range_locked_note = None
        if rl.get("locked"):
            range_locked_note = (
                f"Range-locked: both put and call writers are fully committed "
                f"({rl['support']:.0f}–{rl['resistance']:.0f}). "
                f"Watch for a break on either side."
            )
            parts.append(range_locked_note)
            direction = "NEUTRAL"

        # --- Direction conclusion (v1.11.2: reduced to a short summary line;
        # the substantive narrative is now in the support/resistance sentences) ---
        if direction == "BULLISH":
            parts.append("Bias: BULLISH — favour long setups on dips.")
        elif direction == "BEARISH":
            parts.append("Bias: BEARISH — favour short setups on rallies.")
        else:
            if not range_locked_note:
                parts.append("Bias: NEUTRAL — range-bound action likely.")

        return {
            "sentence": " ".join(parts),
            "direction": direction,
            "parts": parts,
            "support_level": sup_level,
            "resistance_level": res_level,
            "support_conviction": sup_conv,
            "resistance_conviction": res_conv,
            "put_coi_delta": put_delta.get("delta"),
            "call_coi_delta": call_delta.get("delta"),
            "window_min": put_delta.get("window_min"),
            "day_direction_gap": day_dir.get("gap"),
            "day_direction_strength": day_dir.get("strength"),
            "range_locked": rl.get("locked", False),
            "range_locked_note": range_locked_note if rl.get("locked") else None,
        }
    except Exception as e:
        print(f"[Narrative] commentary build error: {e}")
        return {"sentence": "Commentary unavailable.", "direction": "NEUTRAL", "parts": []}

def build_day_direction(symbol="NIFTY"):
    """
    Sustained imbalance → directional call.
    Requires conviction gap and sustained state over DIRECTION_MIN_HOLD_MIN.
    """
    try:
        data = get_latest_conviction(symbol)
        if not data:
            return {"available": False}
        sup_conv = data.get("support", {}).get("score") or 0
        res_conv = data.get("resistance", {}).get("score") or 0
        sup_level = data.get("support_level")
        res_level = data.get("resistance_level")
        spot = data.get("spot")

        gap = sup_conv - res_conv
        abs_gap = abs(gap)

        if abs_gap < DIRECTION_CONVICTION_DOMINANCE:
            return {"available": True, "direction": "NEUTRAL",
                    "message": "No clear directional bias from options.",
                    "gap": round(gap, 1)}

        strength = "strong" if abs_gap >= DIRECTION_STRONG_DOMINANCE else "moderate"

        if gap > 0:
            direction = "BULLISH"
            message = (
                f"{strength.upper()} BULLISH bias — put writers dominating "
                f"({sup_conv:.0f}% vs {res_conv:.0f}%). "
                f"Support at {int(sup_level)} is being defended; "
                f"expect upside toward {int(res_level)}."
            )
        else:
            direction = "BEARISH"
            message = (
                f"{strength.upper()} BEARISH bias — call writers dominating "
                f"({res_conv:.0f}% vs {sup_conv:.0f}%). "
                f"Resistance at {int(res_level)} is capping; "
                f"expect downside toward {int(sup_level)}."
            )
        return {
            "available": True,
            "direction": direction,
            "strength": strength,
            "message": message,
            "gap": round(gap, 1),
            "support_conviction": sup_conv,
            "resistance_conviction": res_conv,
            "support_level": sup_level,
            "resistance_level": res_level,
            "spot": spot,
        }
    except Exception as e:
        print(f"[Narrative] day direction error: {e}")
        return {"available": False, "error": str(e)[:200]}


# ============================================================
# v1.9.0 — Trade Call generator (5-condition gate)
# ============================================================
_LAST_TRADE_CALL = {"key": None, "at": 0}

def _trade_call_is_duplicate(direction, entry, target, stop, spot):
    """v1.30.2 — Return True if this call is effectively identical to the
    last emitted one (target/stop within 20 pts OR direction unchanged within
    60 sec). Prevents the UI re-rendering the same trade card every 10s."""
    import time as _t
    now = _t.time()
    key = f"{direction}:{int(round(target/20)*20)}:{int(round(stop/20)*20)}"
    prev = _LAST_TRADE_CALL
    if prev["key"] is None:
        _LAST_TRADE_CALL.update({"key": key, "at": now})
        return False
    same_direction = prev["key"].split(":")[0] == direction
    same_bucket = prev["key"] == key
    recent = (now - prev["at"]) < 60
    if same_direction and same_bucket and recent:
        return True
    _LAST_TRADE_CALL.update({"key": key, "at": now})
    return False


def build_trade_call(symbol="NIFTY"):
    """
    Generate a trade call when 5 conditions align:
      1. Fresh OI added at support/resistance (delta >= threshold)
      2. Conviction building (>= NARRATIVE_CONVICTION_STRONG)
      3. Direction consistent (conviction + delta agree)
      4. Not in macro suppression window
      5. Confidence >= TRADE_CALL_MIN_CONFIDENCE
    """
    try:
        # v1.31.3: Removed time gate. Analysis runs 24/7 on latest data.
        _now_check = datetime.now(IST)


        data = get_latest_conviction(symbol)
        if not data:
            return {"available": False, "reason": "no_data"}

        # --- Condition 4: macro check ---
        macro_ctx = get_macro_context_now()
        if macro_ctx.get("in_window"):
            return {
                "available": False,
                "reason": "macro_suppression",
                "macro": macro_ctx.get("active_event", {}).get("title")
            }

        sup_level = data.get("support_level")
        res_level = data.get("resistance_level")
        spot = data.get("spot")
        sup_conv = data.get("support", {}).get("score") or 0
        res_conv = data.get("resistance", {}).get("score") or 0
        atm = data.get("atm")

        if not (spot and sup_level and res_level):
            return {"available": False, "reason": "missing_levels"}

        put_delta = get_rolling_coi_delta(symbol, "put").get("delta") or 0
        call_delta = get_rolling_coi_delta(symbol, "call").get("delta") or 0


        # --- Try BULLISH call (put writers defending support) ---
        bull_confidence = 0
        if put_delta >= NARRATIVE_COI_SIGNIFICANT:
            bull_confidence += 25
        if sup_conv >= NARRATIVE_CONVICTION_STRONG:
            bull_confidence += 30
        elif sup_conv >= 60:
            bull_confidence += 15
        if res_conv < 50:
            bull_confidence += 15
        if call_delta < 0:
            bull_confidence += 15
        if spot > (sup_level + res_level) / 2:
            bull_confidence += 15
            
        # v1.13.1: Immediate Breakout Boost (Catches fast rallies)
        # If spot breaks above the resistance level by 15 points, boost confidence heavily
        if spot > (res_level + 15):
            bull_confidence += 25

        # --- Try BEARISH call (call writers capping resistance) ---
        bear_confidence = 0
        if call_delta >= NARRATIVE_COI_SIGNIFICANT:
            bear_confidence += 25
        if res_conv >= NARRATIVE_CONVICTION_STRONG:
            bear_confidence += 30
        elif res_conv >= 60:
            bear_confidence += 15
        if sup_conv < 50:
            bear_confidence += 15
        if put_delta < 0:
            bear_confidence += 15
        if spot < (sup_level + res_level) / 2:
            bear_confidence += 15
            
        # v1.13.1: Immediate Breakout Boost (Catches fast drops like today)
        # If spot breaks below the support level by 15 points, boost confidence heavily
        if spot < (sup_level - 15):
            bear_confidence += 25

        # --- v1.12.1: Cooldown check (no more than 1 trade per hour) ---
        try:
            conn = sqlite3.connect(SENTIMENT_DB_PATH)
            c = conn.cursor()
            cutoff = (datetime.now(IST) - timedelta(minutes=60)).isoformat()
            c.execute("SELECT COUNT(*) FROM trade_call_ab_test WHERE call_time > ?", (cutoff,))
            recent_trades = c.fetchone()[0]
            conn.close()
            
            # If we fired a trade in the last 60 minutes, suppress new ones
            if False and recent_trades > 0:
                return {
                    "available": False,
                    "reason": "cooldown",
                    "message": f"Trade fired in the last 60 min ({recent_trades} logs). Cooldown active."
                }
        except Exception as e:
            print(f"[Trade Call Cooldown Error] {e}")

        # --- v1.14.0: Risk Gates ---
        now_ist = datetime.now(IST)
        # 1. Time Gate: No new trades after 14:30
        if now_ist.hour >= 15 and now_ist.minute > 30:
            return {"available": False, "reason": "time_gate", "message": "Post 14:00 — avoiding late-day gamma traps."}
        
        # 2. Range Gate: No new trades if the day's move is > 1.5%
        try:
            # Fetch today's open from the first snapshot
            conn = sqlite3.connect(SENTIMENT_DB_PATH)
            c = conn.cursor()
            today_str = now_ist.strftime("%Y-%m-%d")
            c.execute("SELECT spot FROM intraday_levels_history WHERE date=? ORDER BY snapshot_at ASC LIMIT 1", (today_str,))
            row = c.fetchone()
            conn.close()
            
            if row and row[0]:
                day_open = row[0]
                day_move_pct = abs((spot - day_open) / day_open) * 100
                if day_move_pct > 1.5:
                    return {"available": False, "reason": "range_gate", "message": f"Day move > 1.5% ({day_move_pct:.2f}%). Trend exhausted, avoiding chop."}
        except Exception as e:
            print(f"[Risk Gate] Move calc error: {e}")

        # --- HARD GATE: Do not trade against strong conviction ---
        if sup_conv >= 80:
            bear_confidence = 0
        if res_conv >= 80:
            bull_confidence = 0

        # --- v1.15.0: Day Momentum bonus ---
        try:
            import sqlite3 as _sql
            _conn = _sql.connect(SENTIMENT_DB_PATH)
            _c = _conn.cursor()
            _today = now_ist.strftime("%Y-%m-%d")
            _c.execute("SELECT spot FROM intraday_levels_history WHERE date=? ORDER BY snapshot_at ASC LIMIT 1", (_today,))
            _row = _c.fetchone()
            _conn.close()
            if _row and _row[0]:
                _day_open = _row[0]
                _move_pct = ((spot - _day_open) / _day_open) * 100
                if _move_pct > 0.3:
                    bull_confidence += 20  # Clear upward trend
                elif _move_pct < -0.3:
                    bear_confidence += 20  # Clear downward trend
        except Exception as _e:
            print(f"[Momentum Bonus] {_e}")

        # --- Pick the higher confidence if it passes threshold ---
        if bull_confidence >= bear_confidence and bull_confidence >= TRADE_CALL_MIN_CONFIDENCE:
            direction = "BUY"
            entry = max(sup_level, spot - 5)  # near current spot
            target = res_level
            stop = sup_level - 50  # v1.15.0: buffer below support (avoid wick stops)
            confidence = bull_confidence
            
            # v1.12.2: Calculate ATR FIRST before using it for target
            try:
                nifty_ticker = yf.Ticker("^NSEI")
                nifty_hist = nifty_ticker.history(period="7d")
                atr_value = None
                if not nifty_hist.empty and len(nifty_hist) >= 5:
                    trs = []
                    for i in range(-5, 0):
                        try:
                            h = float(nifty_hist["High"].iloc[i])
                            l = float(nifty_hist["Low"].iloc[i])
                            c_prev = float(nifty_hist["Close"].iloc[i-1])
                            tr = max(h - l, abs(h - c_prev), abs(l - c_prev))
                            trs.append(tr)
                        except Exception:
                            continue
                    if trs:
                        atr_value = round(sum(trs) / len(trs), 1)
            except Exception:
                atr_value = 200.0  # Default fallback

            # v1.13.0: Multi-Target (T1=0.75%, T2=1.0%, T3=1.5%)
            t1_spot = spot + int(spot * 0.0075)
            t2_spot = spot + int(spot * 0.0100)
            t3_spot = spot + int(spot * 0.0150)
            
            atm_base = math.ceil(spot / 50) * 50
            itm_strike = atm_base - 100
            otm_strike = atm_base + 100
            
            # Find LTP from the live option chain data
            nifty_oc = fetch_option_chain_levels("NIFTY") # <--- Fetch live data for pricing
            itm_ltp = None
            otm_ltp = None
            for slot in nifty_oc.get("atm_neighborhood", []):
                if slot["strike"] == itm_strike: itm_ltp = slot.get("call_ltp")
                if slot["strike"] == otm_strike: otm_ltp = slot.get("call_ltp")
            
            itm_ltp = itm_ltp or 100.0
            otm_ltp = otm_ltp or 50.0
            
            # Find IV for these strikes (fallback to ATM IV if missing)
            atm_iv_slot = next((s for s in nifty_oc.get("atm_neighborhood", []) if s["strike"] == atm_base), {})
            base_iv = (atm_iv_slot.get("call_iv") or 15.0) / 100.0 # Convert to decimal
            
            # Calculate DTE (Days to expiry). Assuming expiry string is like '27-Oct-2026'
            try:
                exp_date = datetime.strptime(nifty_oc.get("expiry"), "%d-%b-%Y").date()
                dte = max(0, (exp_date - datetime.now(IST).date()).days)
            except Exception:
                dte = 2.0 # Default fallback
            
            # Calculate expected premiums at T1, T2, T3
            itm_t1, _ = calculate_premium(t1_spot, itm_strike, base_iv, dte, 'c')
            itm_t2, _ = calculate_premium(t2_spot, itm_strike, base_iv, dte, 'c')
            itm_t3, _ = calculate_premium(t3_spot, itm_strike, base_iv, dte, 'c')
            
            # v1.17.0 FIX: OTM targets must be based on premium multipliers, not fixed spot moves
            # This prevents T1 from falling below entry due to Theta decay on far OTM strikes.
            otm_t1 = round(otm_ltp * 1.30, 1)  # +30% premium
            otm_t2 = round(otm_ltp * 1.60, 1)  # +60% premium
            otm_t3 = round(otm_ltp * 2.00, 1)  # +100% premium (2x)
            
            # Stop loss is 15% premium drop
            itm_sl = round(itm_ltp * 0.85, 1)
            otm_sl = round(otm_ltp * 0.85, 1)

            dual_trades = [
                {"strategy": "ITM", "strike": itm_strike, "entry_price": itm_ltp, 
                 "t1": itm_t1, "t2": itm_t2, "t3": itm_t3, "stop": itm_sl},
                {"strategy": "OTM", "strike": otm_strike, "entry_price": otm_ltp, 
                 "t1": otm_t1, "t2": otm_t2, "t3": otm_t3, "stop": otm_sl}
            ]
            


            # v1.16.0 R:R INVERTED-GATE (bullish)
            _rr = (t1_spot - spot) / max(spot - stop, 1) if stop else 0
            if _rr > 1.8:
                return {"available": False, "reason": "rr_too_high", "rr": round(_rr, 2),
                        "message": f"R:R {_rr:.2f} > 1.8"}

            rationale = (
                f"Put writers defending {int(sup_level)} (+{int(put_delta):,} COI), "
                f"support conviction {sup_conv:.0f}%. "
                f"Bullish bias. Premium targets: ITM T1 ₹{itm_t1:.1f}, OTM T1 ₹{otm_t1:.1f}. Stop: ITM ₹{itm_sl:.1f}."
            )
        elif bear_confidence >= TRADE_CALL_MIN_CONFIDENCE:
            direction = "SELL"
            entry = min(res_level, spot + 5)
            target = sup_level
            stop = res_level + 50  # v1.15.0: buffer above resistance (avoid wick stops)
            confidence = bear_confidence
            
            # v1.12.2: Calculate ATR FIRST
            try:
                nifty_ticker = yf.Ticker("^NSEI")
                nifty_hist = nifty_ticker.history(period="7d")
                atr_value = None
                if not nifty_hist.empty and len(nifty_hist) >= 5:
                    trs = []
                    for i in range(-5, 0):
                        try:
                            h = float(nifty_hist["High"].iloc[i])
                            l = float(nifty_hist["Low"].iloc[i])
                            c_prev = float(nifty_hist["Close"].iloc[i-1])
                            tr = max(h - l, abs(h - c_prev), abs(l - c_prev))
                            trs.append(tr)
                        except Exception:
                            continue
                    if trs:
                        atr_value = round(sum(trs) / len(trs), 1)
            except Exception:
                atr_value = 200.0

            # v1.13.0: Multi-Target (T1=0.75%, T2=1.0%, T3=1.5%)
            t1_spot = spot - int(spot * 0.0075)
            t2_spot = spot - int(spot * 0.0100)
            t3_spot = spot - int(spot * 0.0150)
            
            atm_base = math.floor(spot / 50) * 50
            itm_strike = atm_base + 100
            otm_strike = atm_base - 100
            
            # Find LTP from the live option chain data
            nifty_oc = fetch_option_chain_levels("NIFTY") # <--- Fetch live data for pricing
            itm_ltp = None
            otm_ltp = None
            for slot in nifty_oc.get("atm_neighborhood", []):
                if slot["strike"] == itm_strike: itm_ltp = slot.get("put_ltp")
                if slot["strike"] == otm_strike: otm_ltp = slot.get("put_ltp")
            
            itm_ltp = itm_ltp or 100.0
            otm_ltp = otm_ltp or 50.0
            
            atm_iv_slot = next((s for s in nifty_oc.get("atm_neighborhood", []) if s["strike"] == atm_base), {})
            base_iv = (atm_iv_slot.get("put_iv") or 15.0) / 100.0
            
            try:
                exp_date = datetime.strptime(nifty_oc.get("expiry"), "%d-%b-%Y").date()
                dte = max(0, (exp_date - datetime.now(IST).date()).days)
            except Exception:
                dte = 2.0
            
            itm_t1, _ = calculate_premium(t1_spot, itm_strike, base_iv, dte, 'p')
            itm_t2, _ = calculate_premium(t2_spot, itm_strike, base_iv, dte, 'p')
            itm_t3, _ = calculate_premium(t3_spot, itm_strike, base_iv, dte, 'p')
            
            # v1.17.0 FIX: OTM targets must be based on premium multipliers
            otm_t1 = round(otm_ltp * 1.30, 1)
            otm_t2 = round(otm_ltp * 1.60, 1)
            otm_t3 = round(otm_ltp * 2.00, 1)
            
            itm_sl = round(itm_ltp * 0.85, 1)
            otm_sl = round(otm_ltp * 0.85, 1)

            dual_trades = [
                {"strategy": "ITM", "strike": itm_strike, "entry_price": itm_ltp, 
                 "t1": itm_t1, "t2": itm_t2, "t3": itm_t3, "stop": itm_sl},
                {"strategy": "OTM", "strike": otm_strike, "entry_price": otm_ltp, 
                 "t1": otm_t1, "t2": otm_t2, "t3": otm_t3, "stop": otm_sl}
            ]
            
            # v1.16.0 R:R INVERTED-GATE (bearish)
            _rr = (spot - t1_spot) / max(stop - spot, 1) if stop else 0
            if _rr > 1.8:
                return {"available": False, "reason": "rr_too_high", "rr": round(_rr, 2),
                        "message": f"R:R {_rr:.2f} > 1.8"}

            rationale = (
                f"Call writers capping {int(res_level)} (+{int(call_delta):,} COI), "
                f"resistance conviction {res_conv:.0f}%. "
                f"Bearish bias. Premium targets: ITM T1 ₹{itm_t1:.1f}, OTM T1 ₹{otm_t1:.1f}. Stop: ITM ₹{itm_sl:.1f}."
            )
        else:
            return {
                "available": False,
                "reason": "below_threshold",
                "bull_confidence": bull_confidence,
                "bear_confidence": bear_confidence,
            }

        # --- CONFIDENCE GATE (v1.30.0) ---
        # Hide low-confidence trades from the UI, but save to DB for backtesting
        level = "HIGH" if confidence >= 80 else "MEDIUM" if confidence >= 70 else "LOW"
        
        # If confidence is less than 60, we return a "no trade" signal to the frontend.
        # But we continue the function so it still gets saved to trade_call_ab_test.
        hide_from_ui = confidence < 60

        # v1.30.2 — dedup: skip DB write + UI emission if this call is
        # essentially identical to one from <60s ago
        if _trade_call_is_duplicate(direction, entry, target, stop, spot):
            return {
                "available": False,
                "reason": "duplicate",
                "confidence": confidence,
                "message": f"Duplicate of prior call (same direction, target, stop).",
            }

        # v1.10.0: ATR-based stop override + R:R computation
        atr_value = None
        try:
            nifty_ticker = yf.Ticker("^NSEI")
            nifty_hist = nifty_ticker.history(period="7d")
            if not nifty_hist.empty and len(nifty_hist) >= 5:
                trs = []
                for i in range(-5, 0):
                    try:
                        h = float(nifty_hist["High"].iloc[i])
                        l = float(nifty_hist["Low"].iloc[i])
                        c_prev = float(nifty_hist["Close"].iloc[i-1])
                        tr = max(h - l, abs(h - c_prev), abs(l - c_prev))
                        trs.append(tr)
                    except Exception:
                        continue
                if trs:
                    atr_value = round(sum(trs) / len(trs), 1)
        except Exception as e:
            print(f"[Trade Call] ATR compute error: {e}")

        atr_stop = None
        if atr_value is not None:
            if direction == "BUY":
                atr_stop = int(entry - TRADE_CALL_ATR_MULT_STOP * atr_value)
            else:
                atr_stop = int(entry + TRADE_CALL_ATR_MULT_STOP * atr_value)

        # Compute R:R using the tighter stop
        stop_used = stop
        if atr_stop is not None:
            if direction == "BUY":
                stop_used = max(stop, atr_stop)  # tighter of the two
            else:
                stop_used = min(stop, atr_stop)

        risk = abs(entry - stop_used)
        reward = abs(target - entry)
        rr_ratio = round(reward / risk, 2) if risk > 0 else None

        # --- STAND ASIDE ADVISORY (v1.31.0) ---
        # If market is range-locked AND R:R is terrible, block the trade.
        rl = detect_range_locked(symbol)
        pts_to_target = abs(target - entry)
        
        if rl.get("locked") and (rr_ratio is not None and rr_ratio < 1.0 or pts_to_target < 25):
            print(f"[Trade Call] 🛑 STAND ASIDE ADVISORY triggered. R:R={rr_ratio}, pts_to_target={pts_to_target}")
            return {
                "available": False,
                "reason": "stand_aside",
                "message": f"Bias is {direction} ({'Bullish' if direction=='BUY' else 'Bearish'}), but do not take this trade. Stand aside. The market is range-locked and the risk/reward is poor.",
                "confidence": confidence,
            }

        # --- SAVE TRADE TO DB (for evening accuracy tracking) ---
        print(f"[Trade Call] Attempting DB log: {direction} {symbol}")
        try:
            conn = sqlite3.connect(SENTIMENT_DB_PATH)
            c = conn.cursor()
            now_ist = datetime.now(IST)
            
            cutoff = (now_ist - timedelta(minutes=15)).isoformat()
            c.execute("SELECT COUNT(*) FROM event_history WHERE event_type='trade_call' AND event_at > ? AND message LIKE ?", (cutoff, f"TRADE CALL: {direction} %"))
            recent = c.fetchone()[0]
            
            if recent == 0:
                c.execute('''
                    INSERT INTO trade_call_ab_test 
                    (call_time, direction, strategy_type, strike, entry_spot, target_spot, stop_spot, status, entry_price, target_1, spot_target_1, spot_target_2, spot_target_3) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, 'OPEN', ?, ?, ?, ?, ?)
                ''', (now_ist.isoformat(), direction, "ITM", dual_trades[0]["strike"], spot, target, stop_used, dual_trades[0]["entry_price"], dual_trades[0]["t1"], t1_spot, t2_spot, t3_spot))
                
                c.execute('''
                    INSERT INTO trade_call_ab_test 
                    (call_time, direction, strategy_type, strike, entry_spot, target_spot, stop_spot, status, entry_price, target_1, spot_target_1, spot_target_2, spot_target_3) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, 'OPEN', ?, ?, ?, ?, ?)
                ''', (now_ist.isoformat(), direction, "OTM", dual_trades[1]["strike"], spot, target, stop_used, dual_trades[1]["entry_price"], dual_trades[1]["t1"], t1_spot, t2_spot, t3_spot))

                itm = dual_trades[0]
                otm = dual_trades[1]
                msg = "TRADE CALL: {} {} | ITM {} @ {:.1f} (T1 {:.1f} | T2 {:.1f} | T3 {:.1f} | SL {:.1f}) | OTM {} @ {:.1f} (T1 {:.1f} | T2 {:.1f} | T3 {:.1f} | SL {:.1f})".format(
                    direction, symbol, 
                    itm["strike"], itm["entry_price"], itm["t1"], itm.get("t2", 0), itm.get("t3", 0), itm["stop"],
                    otm["strike"], otm["entry_price"], otm["t1"], otm.get("t2", 0), otm.get("t3", 0), otm["stop"])
                meta = json_lib.dumps({"direction": direction, "itm": itm, "otm": otm})
                c.execute("INSERT INTO event_history (event_at, event_type, level, icon, message, metadata) VALUES (?, 'trade_call', 'MAJOR', 'TARGET', ?, ?)",
                          (now_ist.isoformat(), msg, meta))
                print("[Trade Call] Logged to event_history:", msg[:100])
                
            conn.commit()
            conn.close()
        except Exception as e:
            print(f"[Trade Call DB Log Error] {e}")

        # If the trade is low confidence, return "unavailable" to the UI
        if hide_from_ui:
            return {
                "available": False,
                "reason": "low_confidence",
                "confidence": confidence,
                "message": f"Trade call hidden: confidence {confidence}% < 60% threshold."
            }
            
        return {
            "available": True,
            "direction": direction,
            "instrument": symbol,
            "entry": int(entry),
            "target": int(target),
            "stop": int(stop_used),
            "stop_sr": int(stop),
            "stop_atr": atr_stop,
            "atr": atr_value,
            "rr_ratio": rr_ratio,
            "risk_pts": int(risk),
            "reward_pts": int(reward),
            "spot": spot,
            "confidence": confidence,
            "confidence_label": level,
            "rationale": rationale,
            "dual_trades": dual_trades,
            "components": {
                "put_coi_delta": put_delta,
                "call_coi_delta": call_delta,
                "support_conviction": sup_conv,
                "resistance_conviction": res_conv,
                "support_level": sup_level,
                "resistance_level": res_level,
            }
        }
    except Exception as e:
        print(f"[Trade Call] error: {e}")
        return {"available": False, "error": str(e)[:200]}


# ============================================================
# v1.10.0 — Range-locked commentary variant
# ============================================================
def detect_range_locked(symbol="NIFTY"):
    """
    Returns True when both convictions are high AND S/R band is narrow.
    Used by commentary to add a "range-locked" line.
    """
    try:
        data = get_latest_conviction(symbol)
        if not data:
            return {"locked": False}
        sup_conv = data.get("support", {}).get("score") or 0
        res_conv = data.get("resistance", {}).get("score") or 0
        sup_level = data.get("support_level")
        res_level = data.get("resistance_level")

        if sup_conv < RANGE_LOCKED_CONVICTION or res_conv < RANGE_LOCKED_CONVICTION:
            return {"locked": False}
        if sup_level is None or res_level is None:
            return {"locked": False}

        width = res_level - sup_level
        if width < RANGE_LOCKED_MIN_WIDTH:
            return {"locked": False}

        return {
            "locked": True,
            "support": sup_level,
            "resistance": res_level,
            "width": round(width, 0),
            "support_conviction": sup_conv,
            "resistance_conviction": res_conv,
        }
    except Exception as e:
        print(f"[Range-locked] error: {e}")
        return {"locked": False}

# ============================================================
# v1.10.0 — Cross-asset correlation matrix
# ============================================================
_CORR_CACHE = {"data": None, "ts": 0}

def build_correlation_matrix():
    """
    Compute rolling correlation matrix across NIFTY, BANKNIFTY, CRUDE, GOLD,
    SILVER, BTC. Cached for 30 min.
    """
    import time as _t
    now = _t.time()
    if _CORR_CACHE["data"] is not None and (now - _CORR_CACHE["ts"]) < 1800:
        return _CORR_CACHE["data"]

    try:
        import pandas as pd
    except Exception as e:
        return {"available": False, "error": f"pandas not available: {e}"}

    try:
        tickers = CORRELATION_SYMBOLS
        price_data = {}
        for label, ticker in tickers.items():
            try:
                t = yf.Ticker(ticker)
                h = t.history(period=f"{CORRELATION_LOOKBACK_DAYS}d", interval="1d")
                if not h.empty and "Close" in h:
                    # v1.10.2: normalize index to date-only, strip timezone
                    s = h["Close"].copy()
                    try:
                        # Handle tz-aware index
                        if hasattr(s.index, 'tz') and s.index.tz is not None:
                            s.index = s.index.tz_convert(None)
                        # Strip time component — keep only date
                        s.index = s.index.normalize()
                    except Exception:
                        pass
                    # Deduplicate same-date rows (keep last)
                    s = s[~s.index.duplicated(keep="last")]
                    price_data[label] = s
            except Exception as e:
                print(f"[Correlation] {label} fetch error: {e}")

        if len(price_data) < 3:
            return {"available": False, "error": "insufficient_data"}

        # v1.10.2: use outer join + pairwise correlation (not dropna)
        df = pd.DataFrame(price_data)
        # Sort by date
        df = df.sort_index()
        # Keep rows where at least 2 symbols have data
        df = df.dropna(thresh=2)
        if len(df) < 5:
            return {"available": False, "error": "insufficient_history",
                    "rows": len(df), "columns": list(df.columns)}

        # Daily returns — use pairwise (each column pct-change independently)
        returns = df.pct_change()
        # Compute pairwise correlation (min_periods=3 to avoid noise)
        corr = returns.corr(min_periods=3).round(2)

        # Build dict output
        matrix = {}
        for row_label in corr.index:
            matrix[row_label] = {}
            for col_label in corr.columns:
                matrix[row_label][col_label] = float(corr.loc[row_label, col_label])

        result = {
            "available": True,
            "symbols": list(corr.columns),
            "matrix": matrix,
            "lookback_days": CORRELATION_LOOKBACK_DAYS,
            "generated_at_ist": datetime.now(IST).strftime("%Y-%m-%d %H:%M:%S IST"),
        }
        _CORR_CACHE["data"] = result
        _CORR_CACHE["ts"] = now
        return result
    except Exception as e:
        print(f"[Correlation] error: {e}")
        return {"available": False, "error": str(e)[:200]}


# ============================================================
# v1.10.0 — Range-locked commentary variant
# ============================================================

# ============================================================
# v1.11.0 — Event history
# ============================================================
def init_event_history_db():
    """Create event_history table. Idempotent."""
    conn = sqlite3.connect(SENTIMENT_DB_PATH)
    c = conn.cursor()
    c.execute("""
        CREATE TABLE IF NOT EXISTS event_history (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            event_at    TEXT NOT NULL,
            event_type  TEXT NOT NULL,
            level       TEXT,
            icon        TEXT,
            message     TEXT NOT NULL,
            metadata    TEXT,
            created_at  TEXT DEFAULT CURRENT_TIMESTAMP
        )
    """)
    c.execute("CREATE INDEX IF NOT EXISTS idx_event_history_time ON event_history(event_at DESC)")
    c.execute("CREATE INDEX IF NOT EXISTS idx_event_history_type ON event_history(event_type)")
    conn.commit()
    conn.close()


def log_event(event_type, level, icon, message, metadata=None):
    """Persist an event. Deduplicates within EVENT_HISTORY_DEDUP_WINDOW_SEC."""
    try:
        now_ist = datetime.now(IST)
        event_at = now_ist.isoformat()
        cutoff = (now_ist - timedelta(seconds=EVENT_HISTORY_DEDUP_WINDOW_SEC)).isoformat()

        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("""
            SELECT id FROM event_history
            WHERE event_type = ? AND message = ? AND event_at >= ?
            LIMIT 1
        """, (event_type, message, cutoff))
        if c.fetchone():
            conn.close()
            return False

        meta_json = json_lib.dumps(metadata) if metadata else None
        c.execute("""
            INSERT INTO event_history
            (event_at, event_type, level, icon, message, metadata)
            VALUES (?, ?, ?, ?, ?, ?)
        """, (event_at, event_type, level, icon, message, meta_json))
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"[Event history] write error: {e}")
        return False

def get_event_history(hours=24, event_types=None, limit=500, exclude_types=None):
    """Fetch recent events from history.
    v1.11.1: added exclude_types so the UI can suppress noise
    without enumerating every signal type.
    """
    try:
        now_ist = datetime.now(IST)
        cutoff = (now_ist - timedelta(hours=hours)).isoformat()
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()

        # Build WHERE clause dynamically
        where_parts = ["event_at >= ?"]
        params = [cutoff]

        if event_types:
            placeholders = ",".join("?" * len(event_types))
            where_parts.append(f"event_type IN ({placeholders})")
            params.extend(event_types)

        if exclude_types:
            placeholders = ",".join("?" * len(exclude_types))
            where_parts.append(f"event_type NOT IN ({placeholders})")
            params.extend(exclude_types)

        where_sql = " AND ".join(where_parts)
        params.append(limit)

        c.execute(f"""
            SELECT event_at, event_type, level, icon, message, metadata
            FROM event_history
            WHERE {where_sql}
            ORDER BY event_at DESC
            LIMIT ?
        """, tuple(params))

        rows = c.fetchall()
        conn.close()
        return [{
            "event_at": r[0], "event_type": r[1], "level": r[2],
            "icon": r[3], "message": r[4],
            "metadata": json_lib.loads(r[5]) if r[5] else None,
        } for r in rows]
    except Exception as e:
        print(f"[Event history] read error: {e}")
        return []

def cleanup_event_history():
    """Delete events older than retention window."""
    try:
        cutoff = (datetime.now(IST) - timedelta(hours=EVENT_HISTORY_MAX_AGE_HOURS)).isoformat()
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("DELETE FROM event_history WHERE event_at < ?", (cutoff,))
        deleted = c.rowcount
        conn.commit()
        conn.close()
        if deleted > 0:
            print(f"[Event history] Cleanup: {deleted} old events removed")
        return deleted
    except Exception as e:
        print(f"[Event history] cleanup error: {e}")
        return 0

init_event_history_db()

def init_macro_events_db():
    """Create macro_events table. Idempotent."""
    conn = sqlite3.connect(SENTIMENT_DB_PATH)
    c = conn.cursor()
    c.execute("""
        CREATE TABLE IF NOT EXISTS macro_events (
            id              INTEGER PRIMARY KEY AUTOINCREMENT,
            event_date      TEXT NOT NULL,
            event_time_utc  TEXT,
            event_time_ist  TEXT,
            region          TEXT NOT NULL,
            event_type      TEXT NOT NULL,
            title           TEXT NOT NULL,
            importance      TEXT NOT NULL DEFAULT 'MEDIUM',
            affects         TEXT,
            notes           TEXT,
            created_at      TEXT DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(event_date, event_time_utc, event_type, region)
        )
    """)
    c.execute("CREATE INDEX IF NOT EXISTS idx_macro_date ON macro_events(event_date)")
    conn.commit()
    conn.close()

def get_macro_events_for_date(date_str):
    """Return all events for a given YYYY-MM-DD (IST date)."""
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("""
            SELECT id, event_date, event_time_utc, event_time_ist, region,
                   event_type, title, importance, affects, notes
            FROM macro_events
            WHERE event_date = ?
            ORDER BY COALESCE(event_time_utc, '00:00') ASC
        """, (date_str,))
        rows = c.fetchall()
        conn.close()
        return [{
            "id": r[0], "event_date": r[1], "event_time_utc": r[2],
            "event_time_ist": r[3], "region": r[4], "event_type": r[5],
            "title": r[6], "importance": r[7],
            "affects": json_lib.loads(r[8]) if r[8] else [],
            "notes": r[9]
        } for r in rows]
    except Exception as e:
        print(f"[Macro] read error: {e}")
        return []

def get_macro_context_now():
    """Returns context about whether we are inside a macro event window."""
    out = {"in_window": False, "phase": None, "active_event": None,
           "minutes_offset": 0, "same_day_event": None}
    try:
        now_ist = datetime.now(IST)
        today_str = now_ist.strftime("%Y-%m-%d")
        events_today = get_macro_events_for_date(today_str)
        if not events_today:
            return out

        now_utc = datetime.now(timezone.utc)
        best = None
        best_offset = None
        for ev in events_today:
            ev_utc_str = ev.get("event_time_utc")
            if not ev_utc_str:
                if out["same_day_event"] is None:
                    out["same_day_event"] = ev
                continue
            try:
                hh, mm = ev_utc_str.split(":")
                ev_utc = now_utc.replace(hour=int(hh), minute=int(mm),
                                         second=0, microsecond=0)
            except Exception:
                continue
            delta_min = (now_utc - ev_utc).total_seconds() / 60.0
            if -MACRO_SUPPRESS_PRE_MIN <= delta_min <= MACRO_SUPPRESS_POST_MIN:
                if best is None or abs(delta_min) < abs(best_offset):
                    best = ev
                    best_offset = delta_min
            if out["same_day_event"] is None:
                out["same_day_event"] = ev

        if best is not None:
            out["in_window"] = True
            out["active_event"] = best
            out["minutes_offset"] = int(best_offset)
            if best_offset < 0:
                out["phase"] = "pre"
            elif best_offset <= 2:
                out["phase"] = "live"
            else:
                out["phase"] = "post"
        return out
    except Exception as e:
        print(f"[Macro] context error: {e}")
        return out


def seed_macro_events():
    """Seed recurring macro events. Idempotent."""
    seed = [
        ("2026-02-01", "04:00", "10:00", "IN", "UNION_BUDGET",
         "Union Budget 2026-27", "HIGH", ["NIFTY","BANKNIFTY","GIFTNIFTY"], None),
        ("2026-10-07", "04:30", "10:00", "IN", "RBI_MPC",
         "RBI MPC rate decision #4 (Oct 2026)", "HIGH", ["NIFTY","BANKNIFTY","GIFTNIFTY"], "CONFIRMED"),
        ("2026-11-12", "12:00", "17:30", "IN", "CPI_IN",
         "India CPI inflation (Oct)", "MEDIUM", ["NIFTY","BANKNIFTY"], "VERIFY DATE"),
        ("2026-11-12", "12:00", "17:30", "IN", "IIP_IN",
         "India IIP (Sep)", "MEDIUM", ["NIFTY"], "VERIFY DATE"),
        ("2026-11-05", "19:00", "00:30", "US", "FED_FOMC",
         "Fed FOMC rate decision", "HIGH", ["NIFTY","GIFTNIFTY","BITCOIN"], None),
        ("2026-12-17", "19:00", "00:30", "US", "FED_FOMC",
         "Fed FOMC rate decision", "HIGH", ["NIFTY","GIFTNIFTY","BITCOIN"], "VERIFY DATE"),
        ("2026-11-01", "12:30", "18:00", "US", "NFP_US",
         "US Non-Farm Payrolls", "HIGH", ["NIFTY","GIFTNIFTY"], None),
        ("2026-12-06", "12:30", "18:00", "US", "NFP_US",
         "US Non-Farm Payrolls", "HIGH", ["NIFTY","GIFTNIFTY"], None),
        ("2026-11-13", "13:30", "19:00", "US", "CPI_US",
         "US CPI inflation", "HIGH", ["NIFTY","GIFTNIFTY"], "VERIFY DATE"),
        ("2026-11-20", "11:45", "17:15", "GLOBAL", "ECB_RATE",
         "ECB rate decision", "MEDIUM", ["NIFTY"], "VERIFY DATE"),
        ("2026-12-19", "03:00", "08:30", "GLOBAL", "BOJ_RATE",
         "Bank of Japan rate decision", "MEDIUM", ["NIFTY"], "VERIFY DATE"),
    ]
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        inserted = 0
        for row in seed:
            try:
                c.execute("""
                    INSERT OR IGNORE INTO macro_events
                    (event_date, event_time_utc, event_time_ist, region,
                     event_type, title, importance, affects, notes)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                """, (row[0], row[1], row[2], row[3], row[4],
                      row[5], row[6], json_lib.dumps(row[7]), row[8]))
                if c.rowcount > 0:
                    inserted += 1
            except Exception as ie:
                print(f"[Macro seed] row error: {ie}")
        conn.commit()
        conn.close()
        print(f"[Macro seed] inserted {inserted} new events")
    except Exception as e:
        print(f"[Macro seed] error: {e}")

def refresh_macro_events_daily():
    print(f"[{datetime.now(IST).strftime('%Y-%m-%d %H:%M:%S IST')}] Macro refresh")
    seed_macro_events()


def compute_data_health():
    """v1.5.1 — Coverage health of macro_events table."""
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        now_ist = datetime.now(IST)
        today_str = now_ist.strftime("%Y-%m-%d")

        c.execute("SELECT COUNT(*) FROM macro_events")
        total = c.fetchone()[0]

        c.execute("""
            SELECT event_date FROM macro_events
            WHERE event_date >= ?
            ORDER BY event_date ASC
            LIMIT 1
        """, (today_str,))
        next_row = c.fetchone()
        next_event_date = next_row[0] if next_row else None

        c.execute("""
            SELECT MAX(event_date) FROM macro_events
            WHERE event_date >= ?
        """, (today_str,))
        last_row = c.fetchone()
        last_event_date = last_row[0] if last_row else None
        conn.close()

        coverage_days = 0
        if last_event_date:
            try:
                last_dt = datetime.strptime(last_event_date, "%Y-%m-%d").replace(tzinfo=IST)
                coverage_days = (last_dt - now_ist).days
            except Exception:
                pass

        days_to_next = None
        if next_event_date:
            try:
                next_dt = datetime.strptime(next_event_date, "%Y-%m-%d").replace(tzinfo=IST)
                days_to_next = (next_dt - now_ist).days
            except Exception:
                pass

        if coverage_days < MACRO_COVERAGE_WARN_DAYS:
            recommendation = f"Seed more events — only {coverage_days} days of coverage"
        else:
            recommendation = "Coverage OK"

        return {
            "total_events": total,
            "next_event_date": next_event_date,
            "days_to_next_event": days_to_next,
            "last_event_date": last_event_date,
            "days_of_coverage": coverage_days,
            "warn_threshold_days": MACRO_COVERAGE_WARN_DAYS,
            "recommendation": recommendation
        }
    except Exception as e:
        print(f"[Data health] error: {e}")
        return {
            "total_events": 0,
            "next_event_date": None,
            "days_to_next_event": None,
            "last_event_date": None,
            "days_of_coverage": 0,
            "warn_threshold_days": MACRO_COVERAGE_WARN_DAYS,
            "recommendation": "Data health unavailable"
        }

def build_macro_events_response():
    """Build the /api/macro-events payload."""
    try:
        now_ist = datetime.now(IST)
        today_str = now_ist.strftime("%Y-%m-%d")
        cutoff_str = (now_ist + timedelta(days=MACRO_UPCOMING_DAYS)).strftime("%Y-%m-%d")

        today_events = get_macro_events_for_date(today_str)
        ctx = get_macro_context_now()

        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("""
            SELECT id, event_date, event_time_utc, event_time_ist, region,
                   event_type, title, importance, affects, notes
            FROM macro_events
            WHERE event_date > ? AND event_date <= ?
            ORDER BY event_date ASC, COALESCE(event_time_utc, '00:00') ASC
            LIMIT 50
        """, (today_str, cutoff_str))
        rows = c.fetchall()
        conn.close()
        upcoming = [{
            "id": r[0], "event_date": r[1], "event_time_utc": r[2],
            "event_time_ist": r[3], "region": r[4], "event_type": r[5],
            "title": r[6], "importance": r[7],
            "affects": json_lib.loads(r[8]) if r[8] else [],
            "notes": r[9]
        } for r in rows]

        now_utc = datetime.now(timezone.utc)
        for ev in today_events:
            ev_utc_str = ev.get("event_time_utc")
            if not ev_utc_str:
                ev["status"] = "all_day"
                ev["minutes_to_event"] = None
                continue
            try:
                hh, mm = ev_utc_str.split(":")
                ev_utc = now_utc.replace(hour=int(hh), minute=int(mm),
                                         second=0, microsecond=0)
                delta = int((ev_utc - now_utc).total_seconds() / 60.0)
                ev["minutes_to_event"] = delta
                if delta > 0:
                    ev["status"] = "upcoming"
                elif delta >= -MACRO_SUPPRESS_POST_MIN:
                    ev["status"] = "live"
                else:
                    ev["status"] = "past"
            except Exception:
                ev["status"] = "unknown"
                ev["minutes_to_event"] = None

        # C4: sort today's events by importance (HIGH > MEDIUM > LOW)
        _imp_order = {"HIGH": 0, "MEDIUM": 1, "LOW": 2}
        today_events.sort(
            key=lambda e: (_imp_order.get(e.get("importance", "MEDIUM"), 1),
                           e.get("event_time_utc") or "00:00")
        )

        # C2: past_today — events whose window has closed
        past_today = [e for e in today_events if e.get("status") == "past"]

        # C3: data_health
        health = compute_data_health()

        return {
            "today": today_events,
            "past_today": past_today,
            "upcoming": upcoming,
            "active_window": ctx["in_window"],
            "active_event": ctx["active_event"],
            "phase": ctx["phase"],
            "minutes_offset": ctx["minutes_offset"],
            "same_day_event": ctx["same_day_event"],
            "data_health": health,
            "generated_at_ist": now_ist.strftime("%Y-%m-%d %H:%M:%S IST")
        }
    except Exception as e:
        print(f"[Macro] build error: {e}")
        return {"today": [], "past_today": [], "upcoming": [], "active_window": False,
                "active_event": None, "phase": None, "minutes_offset": 0,
                "same_day_event": None, "data_health": {"recommendation": "unavailable"},
                "error": str(e)[:200]}

init_macro_events_db()
seed_macro_events()

# ============================================================
# FALLBACK KEYWORD SCORER
# ============================================================
BEARISH_WORDS = ['fall', 'falls', 'crash', 'crashes', 'plunge', 'plunges', 'drop', 'drops',
                 'decline', 'declines', 'slump', 'slumps', 'weak', 'loss', 'losses',
                 'down', 'bearish', 'sell-off', 'selloff', 'tumble', 'tumbles', 'slide']
BULLISH_WORDS = ['rise', 'rises', 'surge', 'surges', 'gain', 'gains', 'jump', 'jumps',
                 'rally', 'rallies', 'high', 'record', 'strong', 'up', 'bullish',
                 'soar', 'soars', 'climb', 'climbs', 'recover', 'recovers']

def keyword_score(text: str) -> float:
    text_lower = text.lower()
    bull = sum(text_lower.count(w) for w in BULLISH_WORDS)
    bear = sum(text_lower.count(w) for w in BEARISH_WORDS)
    total = bull + bear
    if total == 0:
        return 0.0
    score = ((bull - bear) / total) * 10
    return round(max(-10, min(10, score)), 1)

# ============================================================
# AI SENTIMENT
# ============================================================
def ai_sentiment(symbol: str, text_block: str) -> float:
    """Uses keyword fallback for stability. AI disabled due to network issues."""
    return keyword_score(text_block)

    prompt = f"""Analyze the sentiment of the following text about {symbol}.
Rate from -10 (very bearish) to +10 (very bullish). Reply with only a number.

Text:
{text_block[:3000]}

Sentiment score:"""

    try:
        response = client.chat.completions.create(
            model="openai/gpt-oss-120b",
            messages=[
                {"role": "user", "content": "Analyze: 'Nifty hits all-time high on strong earnings'"},
                {"role": "assistant", "content": "7"},
                {"role": "user", "content": "Analyze: 'Market crashes on weak global cues'"},
                {"role": "assistant", "content": "-6"},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3,
            max_tokens=50,
            extra_body={"reasoning_effort": "low"}
        )
        raw = response.choices[0].message.content.strip()
        match = re.search(r'-?\d+\.?\d*', raw)
        if match:
            return round(max(-10.0, min(10.0, float(match.group()))), 1)
        else:
            return keyword_score(text_block)
    except Exception as e:
        print(f"[{symbol}] AI error: {e}. Using keyword fallback.")
        return keyword_score(text_block)

# ============================================================
# FRESHNESS
# ============================================================
def is_fresh(entry, max_age_hours: int = NEWS_MAX_AGE_HOURS) -> bool:
    published = getattr(entry, "published_parsed", None)
    if not published:
        return True
    try:
        published_dt = datetime(*published[:6], tzinfo=timezone.utc)
    except Exception:
        return True
    cutoff = datetime.now(timezone.utc) - timedelta(hours=max_age_hours)
    return published_dt >= cutoff

# ============================================================
# FII/DII
# ============================================================
def fetch_fii_dii_score() -> float:
    cache_key = "fii_dii_score"
    cached = cache_get(cache_key)
    if cached is not None:
        return cached

    try:
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
                          "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "Accept": "application/json",
            "Referer": "https://www.nseindia.com/"
        }
        r = requests.get(
            "https://www.nseindia.com/api/fiidiiTradeReact",
            headers=headers,
            timeout=10
        )
        if r.status_code != 200:
            cache_set(cache_key, 0.0)
            return 0.0

        data = r.json()
        if not isinstance(data, list) or len(data) == 0:
            cache_set(cache_key, 0.0)
            return 0.0

        fii_net = None
        dii_net = None
        for row in data:
            category = str(row.get("category", "")).upper()
            net_str = str(row.get("netValue", "0")).replace(",", "").strip()
            try:
                net = float(net_str)
            except ValueError:
                net = 0.0
            if "FII" in category or "FPI" in category:
                fii_net = net
            elif "DII" in category:
                dii_net = net

        if fii_net is None or dii_net is None:
            cache_set(cache_key, 0.0)
            return 0.0

        combined_net = fii_net + dii_net
        score = max(-10.0, min(10.0, combined_net / FII_DII_SCALE))
        score = round(score, 1)
        print(f"[FII/DII] FII net: {fii_net:+.2f} cr | DII net: {dii_net:+.2f} cr | Combined: {combined_net:+.2f} cr | Score: {score}")
        cache_set(cache_key, score)
        return score

    except Exception as e:
        print(f"⚠️ FII/DII fetch error: {e}")
        cache_set(cache_key, 0.0)
        return 0.0

# ============================================================
# OPTION CHAIN
# ============================================================
def fetch_option_chain_levels(symbol: str = "NIFTY", vix_value: float = None) -> dict:
    cache_key = f"option_chain_{symbol}"
    cached = cache_get(cache_key)
    if cached is not None:
        return cached
        
    # v1.30.0: Check if we have a stale cache to fall back on
    stale_key = f"stale_option_chain_{symbol}"
    stale_cached = cache_peek(stale_key)
    
    try:
        helper_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "option_chain_helper.py"
        )
        result = subprocess.run(
            [VENV_PYTHON, helper_path, symbol],
            capture_output=True, text=True, timeout=30
        )
        if result.returncode != 0:
            err = result.stderr.strip() or "unknown error"
            cache_set(cache_key, {"error": err[:200]})
            return {"error": err[:200]}

        data = json_lib.loads(result.stdout.strip())
        
        # v1.30.0: Update heartbeat on successful fetch
        global LAST_SUCCESSFUL_FETCH
        if data and data.get("status") == "success" and data.get("spot"):
            LAST_SUCCESSFUL_FETCH = time.time()
            
        cache_set(cache_key, data)

        # v1.4.0: snapshot for shift + conviction detection (persists OI)
        save_intraday_snapshot(symbol, data, vix_value=vix_value)

        # v1.4.0: attach previous snapshot for frontend shift display
        prev = get_previous_intraday_levels(symbol)
        if prev:
            data.update(prev)

        # v1.4.0: compute conviction for current S/R
        try:
            support = data.get("support") or {}
            resistance = data.get("resistance") or {}
            data["conviction"] = {
                "support": compute_conviction(
                    symbol,
                    support.get("level"),
                    support.get("put_oi"),
                    support.get("put_coi"),
                    "support"
                ),
                "resistance": compute_conviction(
                    symbol,
                    resistance.get("level"),
                    resistance.get("call_oi"),
                    resistance.get("call_coi"),
                    "resistance"
                )
            }
        except Exception as ce:
            print(f"[Conviction] compute error for {symbol}: {ce}")

        # v1.16.3: Trust the helper's top5_support/resistance (helper now filters to ±1.5% itself)

        print(f"[Option Chain] {symbol} spot={data.get('spot')} "
              f"R={data.get('resistance',{}).get('level')} "
              f"S={data.get('support',{}).get('level')} "
              f"PCR={data.get('pcr')}")
        # v1.30.0: Save as stale cache for future fallback
        if data and data.get("status") == "success":
            cache_set(stale_key, data, ttl_seconds=86400)  # 24 hours
            
        return data

    except subprocess.TimeoutExpired:
        cache_set(cache_key, {"error": "timeout"})
        return {"error": "timeout"}
    except Exception as e:
        cache_set(cache_key, {"error": str(e)})
        return {"error": str(e)}

# ============================================================
# HELPERS
# ============================================================
def _safe_float(val, decimals=2):
    try:
        if val is None:
            return None
        f = float(val)
        if math.isnan(f) or math.isinf(f):
            return None
        return round(f, decimals)
    except (ValueError, TypeError):
        return None

def _safe_int(val):
    try:
        if val is None:
            return None
        f = float(val)
        if math.isnan(f) or math.isinf(f):
            return None
        return int(f)
    except (ValueError, TypeError):
        return None

# ============================================================
# CONSTITUENTS
# ============================================================
def fetch_constituents(index: str = "NIFTY") -> dict:
    cache_key = f"constituents_{index}"
    cached = cache_get(cache_key)
    if cached is not None:
        return cached

    try:
        constituents = NIFTY50_CONSTITUENTS if index == "NIFTY" else SENSEX30_CONSTITUENTS
        symbols = [c["symbol"] for c in constituents]

        data = yf.download(
            tickers=" ".join(symbols),
            period="7d",
            interval="1d",
            progress=False,
            group_by="ticker",
            auto_adjust=False,
            threads=True
        )

        results = []
        for c in constituents:
            symbol = c["symbol"]
            try:
                if len(symbols) == 1:
                    ticker_data = data
                else:
                    ticker_data = data[symbol] if symbol in data.columns.get_level_values(0) else None

                if ticker_data is None or ticker_data.empty:
                    results.append({
                        "symbol": symbol, "name": c["name"], "weight": c["weight"],
                        "sector": c["sector"], "price": None, "change_pct": None,
                        "atr": None, "atr_pct": None, "move_vs_atr": None,
                        "volume": None, "day_high": None, "day_low": None,
                        "error": "no_data"
                    })
                    continue

                closes = ticker_data["Close"].dropna()
                highs = ticker_data["High"].dropna() if "High" in ticker_data else None
                lows = ticker_data["Low"].dropna() if "Low" in ticker_data else None

                if len(closes) < 2:
                    results.append({
                        "symbol": symbol, "name": c["name"], "weight": c["weight"],
                        "sector": c["sector"],
                        "price": _safe_float(closes.iloc[-1]) if len(closes) else None,
                        "change_pct": None, "atr": None, "atr_pct": None,
                        "move_vs_atr": None, "volume": None,
                        "day_high": None, "day_low": None,
                        "error": "insufficient_history"
                    })
                    continue

                prev_close = float(closes.iloc[-2])
                current_price = float(closes.iloc[-1])
                change_pct = round(((current_price - prev_close) / prev_close) * 100, 2)

                atr = None
                atr_pct = None
                move_vs_atr = None
                if highs is not None and lows is not None and len(highs) >= 5 and len(lows) >= 5:
                    true_ranges = []
                    for i in range(-5, 0):
                        try:
                            h = float(highs.iloc[i])
                            l = float(lows.iloc[i])
                            tr = h - l
                            if tr > 0:
                                true_ranges.append(tr)
                        except Exception:
                            continue
                    if true_ranges:
                        atr = round(sum(true_ranges) / len(true_ranges), 2)
                        if current_price > 0:
                            atr_pct = round((atr / current_price) * 100, 2)
                            if atr_pct > 0:
                                move_vs_atr = round(abs(change_pct) / atr_pct, 2)

                day_high = _safe_float(highs.iloc[-1]) if highs is not None and not highs.empty else None
                day_low = _safe_float(lows.iloc[-1]) if lows is not None and not lows.empty else None
                volume = _safe_int(ticker_data["Volume"].iloc[-1]) if "Volume" in ticker_data and not ticker_data["Volume"].empty else None

                results.append({
                    "symbol": symbol, "name": c["name"], "weight": c["weight"],
                    "sector": c["sector"],
                    "price": round(current_price, 2),
                    "change_pct": change_pct,
                    "prev_close": round(prev_close, 2),
                    "atr": atr, "atr_pct": atr_pct, "move_vs_atr": move_vs_atr,
                    "day_high": day_high, "day_low": day_low, "volume": volume,
                    "error": None
                })
            except Exception as ex:
                results.append({
                    "symbol": symbol, "name": c["name"], "weight": c["weight"],
                    "sector": c["sector"], "price": None, "change_pct": None,
                    "atr": None, "atr_pct": None, "move_vs_atr": None,
                    "volume": None, "day_high": None, "day_low": None,
                    "error": str(ex)[:80]
                })

        result = {
            "index": index,
            "updated": datetime.now(IST).strftime("%d %b %Y, %I:%M %p IST"),
            "constituents": results,
            "count": len(results)
        }
        cache_set(cache_key, result)
        print(f"[Constituents] {index}: fetched {len(results)} stocks")
        return result

    except Exception as e:
        print(f"⚠️ Constituents fetch error for {index}: {e}")
        err = {"index": index, "error": str(e)[:200], "constituents": []}
        cache_set(cache_key, err)
        return err

# ============================================================
# SECTOR SUMMARY
# ============================================================
def _build_sector_summary(constituents: list) -> dict:
    sector_data = {}
    for c in constituents:
        if c.get("change_pct") is None:
            continue
        s = c["sector"]
        if s not in sector_data:
            sector_data[s] = {"count": 0, "avg_change": 0.0, "total_weight": 0.0,
                              "bulls": 0, "bears": 0, "flats": 0, "stocks": []}
        sector_data[s]["count"] += 1
        sector_data[s]["avg_change"] += c["change_pct"]
        sector_data[s]["total_weight"] += c["weight"]
        if c["change_pct"] > 0:
            sector_data[s]["bulls"] += 1
        elif c["change_pct"] < 0:
            sector_data[s]["bears"] += 1
        else:
            sector_data[s]["flats"] += 1
        sector_data[s]["stocks"].append(c)

    for s, d in sector_data.items():
        if d["count"] > 0:
            d["avg_change"] = round(d["avg_change"] / d["count"], 2)
        if d["stocks"]:
            top = max(d["stocks"], key=lambda x: abs(x["change_pct"]) * x["weight"])
            d["top_mover"] = {"name": top["name"], "change_pct": top["change_pct"]}

    return sector_data

# ============================================================
# MARKET NARRATIVE
# ============================================================
def build_market_narrative(index: str = "NIFTY") -> dict:
    """Compose sector-driven commentary on why the index is moving."""
    constituents = fetch_constituents(index).get("constituents", [])
    if not constituents:
        return {"error": "no constituents"}

    sectors = _build_sector_summary(constituents)

    impacts = []
    for sector, data in sectors.items():
        contribution = round(data["avg_change"] * data["total_weight"] / 100, 3)
        impacts.append({
            "sector": sector,
            "avg_change": data["avg_change"],
            "contribution": contribution,
            "bulls": data["bulls"],
            "bears": data["bears"],
            "top_mover": data.get("top_mover", {}),
        })

    ups = sorted([i for i in impacts if i["contribution"] > 0.01],
                 key=lambda x: -x["contribution"])[:3]
    downs = sorted([i for i in impacts if i["contribution"] < -0.01],
                   key=lambda x: x["contribution"])[:3]

    spot = None
    oc = fetch_option_chain_levels("NIFTY")
    if "spot" in oc:
        spot = oc.get("spot")
    support = (oc.get("support") or {}).get("level")
    resistance = (oc.get("resistance") or {}).get("level")

    range_pts = None
    range_pct = None
    is_coiled = False
    if spot and support and resistance:
        range_pts = round(resistance - support, 0)
        range_pct = round((range_pts / spot) * 100, 2)
        is_coiled = range_pct < 0.5

    if is_coiled:
        summary = (f"Nifty is trading in a tight {int(range_pts)}-point range "
                   f"({range_pct}% band) while sectors diverge underneath.")
    elif range_pts:
        summary = (f"Nifty is trading in a {int(range_pts)}-point range "
                   f"({range_pct}% band).")
    else:
        summary = "Range not available."

    # v1.12.0: Hidden Divergence Check
    divergence_warning = ""
    for sector, data in sectors.items():
        if data["avg_change"] > 0 and data["bears"] > data["bulls"]:
            divergence_warning = f"⚠️ Divergence in {sector}: Sector is green, but {data['bears']} stocks are down vs {data['bulls']} up. Beware of fake breakouts."
            break
        elif data["avg_change"] < 0 and data["bulls"] > data["bears"]:
            divergence_warning = f"⚠️ Divergence in {sector}: Sector is red, but {data['bulls']} stocks are up vs {data['bears']} down. Watch for a short squeeze."
            break

    if ups and downs:
        top_up = ups[0]
        top_down = downs[0]
        if abs(top_up["contribution"]) > abs(top_down["contribution"]):
            watch = (f"Watch {top_up['sector']} momentum — "
                     f"{top_up['top_mover'].get('name', 'leader')} "
                     f"({top_up['top_mover'].get('change_pct', 0):+.2f}%) is pulling the index up. "
                     f"If it continues, expect a test of resistance at {int(resistance)}." 
                     if resistance else "")
        else:
            watch = (f"Watch {top_down['sector']} weakness — "
                     f"{top_down['top_mover'].get('name', 'laggard')} "
                     f"({top_down['top_mover'].get('change_pct', 0):+.2f}%) is dragging. "
                     f"If it deepens, expect a test of support at {int(support)}."
                     if support else "")

    # v1.12.0: Append divergence warning to watch_for
    if divergence_warning:
        watch = watch + " " + divergence_warning
    elif ups:
        watch = f"{ups[0]['sector']} is pulling the index up alone."
    elif downs:
        watch = f"{downs[0]['sector']} is dragging the index down alone."
    else:
        watch = "No clear sector driver today."

    # v1.12.4: Build colored inline summary
    inline_parts = []
    if ups:
        up_text = ", ".join([f"{u['sector']} ({u['top_mover'].get('name', '')} {u['top_mover'].get('change_pct', 0):+.2f}%)" for u in ups])
        inline_parts.append(f"<span style='color:var(--bullish); font-weight:bold;'>📈 Pulling UP:</span> {up_text}.")
    if downs:
        down_text = ", ".join([f"{d['sector']} ({d['top_mover'].get('name', '')} {d['top_mover'].get('change_pct', 0):+.2f}%)" for d in downs])
        inline_parts.append(f"<span style='color:var(--bearish); font-weight:bold;'>📉 Dragging DOWN:</span> {down_text}.")
    
    inline_parts.append(f"<span style='color:var(--fii); font-weight:bold;'>👀 Watch:</span> {watch}")
    inline_summary = " ".join(inline_parts)

    return {
        "index": index,
        "updated": datetime.now(IST).strftime("%d %b %Y, %I:%M %p IST"),
        "summary": summary,
        "inline_summary": inline_summary,
        "ups": ups,
        "downs": downs,
        "watch_for": watch,
        "range_pts": range_pts,
        "range_pct": range_pct,
        "is_coiled": is_coiled,
    }

# ============================================================
# ACTION DASHBOARD
# ============================================================
def _classify_move(stock: dict) -> dict:
    pct = stock.get("change_pct")
    atr_pct = stock.get("atr_pct")
    symbol = stock.get("symbol", "")
    is_tier1 = symbol in TIER1_SYMBOLS

    if pct is None:
        return {"level": None, "suggested_action": None}
    abs_pct = abs(pct)

    if is_tier1:
        if abs_pct >= TIER1_MAJOR_FLOOR:
            return {"level": "MAJOR", "suggested_action": "Extreme move for a heavyweight — momentum may exhaust soon, use caution"}
        if abs_pct >= TIER1_IMPORTANT_FLOOR:
            return {"level": "IMPORTANT", "suggested_action": "Significant heavyweight move — chart may show entry opportunity"}

    if atr_pct is None or atr_pct <= 0:
        if abs_pct >= 5.0: return {"level": "MAJOR", "suggested_action": "Extreme move — use caution"}
        if abs_pct >= 3.0: return {"level": "IMPORTANT", "suggested_action": "Significant move — watch for continuation"}
        if abs_pct >= 1.5: return {"level": "SIGNAL", "suggested_action": "Early mover — open chart, watch for continuation"}
        return {"level": None, "suggested_action": None}

    move_vs_atr = abs_pct / atr_pct
    if move_vs_atr >= ATR_MAJOR_MULT:
        return {"level": "MAJOR", "suggested_action": "Extreme move — momentum may exhaust soon, use caution"}
    if move_vs_atr >= ATR_IMPORTANT_MULT:
        return {"level": "IMPORTANT", "suggested_action": "Significant move — chart may show entry opportunity"}
    if move_vs_atr >= ATR_SIGNAL_MULT:
        return {"level": "SIGNAL", "suggested_action": "Early mover — open chart, watch for continuation"}

    return {"level": None, "suggested_action": None}


# ============================================================
# v1.8.3 — Bridge ATM surges into generate_action_events()
# ============================================================
def _atm_surges_as_events(symbol="NIFTY"):
    """
    Convert detect_oi_surge() output into event dicts compatible
    with the action dashboard / flash system.
    """
    events = []
    try:
        surges = detect_oi_surge(symbol)
        for s in surges:
            side = s.get("side", "")
            pos = s.get("position", "")
            strike = s.get("strike")
            delta = s.get("delta_coi", 0)
            pct = s.get("pct_change", 0)

            if side == "PUT":
                etype = "atm_put_surge"
                level = "MAJOR" if abs(delta) >= 100000 else "IMPORTANT"
                icon = "🛡️"
                direction = "PUT WRITERS SURGING"
                action = f"Support building at {int(strike)} — watch for bounce"
            elif side == "CALL":
                etype = "atm_call_surge"
                level = "MAJOR" if abs(delta) >= 100000 else "IMPORTANT"
                icon = "🚧"
                direction = "CALL WRITERS SURGING"
                action = f"Resistance building at {int(strike)} — watch for cap"
            else:
                continue

            sign = "+" if delta > 0 else ""
            message = (f"{direction} at {int(strike)} "
                       f"({sign}{int(delta):,} COI, {pct:+.0f}% vs prev)")
            events.append({
                "priority": 2 if level == "MAJOR" else 3,
                "icon": icon,
                "type": etype,
                "level": level,
                "message": message,
                "suggested_action": action,
            })
    except Exception as e:
        print(f"[Flash] atm surge bridge error: {e}")
    return events

def _find_oi_at_strike(ladder, strike):
    """Find OI/COI at a strike inside the 5-slot ATM ladder. Returns dict or None."""
    if not ladder or strike is None:
        return None
    for slot in ladder:
        try:
            if abs(float(slot.get("strike")) - float(strike)) < 0.5:
                return slot
        except (TypeError, ValueError):
            continue
    return None


def _mins_since_last_shift(side):
    """Minutes since most recent *_shift event for this side today. None if no prior."""
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        today_str = datetime.now(IST).strftime("%Y-%m-%d")
        etype = f"{side}_shift"
        c.execute("""
            SELECT event_at FROM event_history
            WHERE event_type = ? AND event_at >= ?
            ORDER BY event_at DESC LIMIT 1
        """, (etype, today_str + "T00:00:00"))
        row = c.fetchone()
        conn.close()
        if not row:
            return None
        last = datetime.fromisoformat(row[0])
        if last.tzinfo is None:
            last = IST.localize(last)
        return round((datetime.now(IST) - last).total_seconds() / 60.0, 1)
    except Exception as e:
        print(f"[_mins_since_last_shift] {e}")
        return None


def _build_shift_context(side, new_level, old_level, current_oc, prev_levels, spot):
    """
    v1.11.1 — Record facts around an S/R shift. No verdict, no threshold.
    Attaches: OI/COI at new + old level now and before, deltas, minutes
    since prior shift on same side, spot at moment of shift.
    """
    try:
        curr_ladder = current_oc.get("atm_neighborhood") or []
        prev_ladder = prev_levels.get("prev_atm_neighborhood") or []

        curr_new = _find_oi_at_strike(curr_ladder, new_level) or {}
        curr_old = _find_oi_at_strike(curr_ladder, old_level) or {}
        prev_new = _find_oi_at_strike(prev_ladder, new_level) or {}
        prev_old = _find_oi_at_strike(prev_ladder, old_level) or {}

        oi_key = "put_oi" if side == "support" else "call_oi"
        coi_key = "put_coi" if side == "support" else "call_coi"

        def _to_int(v):
            try:
                return int(v) if v is not None else None
            except (TypeError, ValueError):
                return None

        def _delta(curr, prev):
            if curr is None or prev is None:
                return None
            try:
                return int(curr - prev)
            except (TypeError, ValueError):
                return None

        return {
            "side": side,
            "new_level": _to_int(new_level),
            "old_level": _to_int(old_level),
            "new_level_oi_now":  _to_int(curr_new.get(oi_key)),
            "new_level_oi_prev": _to_int(prev_new.get(oi_key)),
            "new_level_oi_delta": _delta(curr_new.get(oi_key), prev_new.get(oi_key)),
            "new_level_coi_now": _to_int(curr_new.get(coi_key)),
            "old_level_oi_now":  _to_int(curr_old.get(oi_key)),
            "old_level_oi_prev": _to_int(prev_old.get(oi_key)),
            "old_level_oi_delta": _delta(curr_old.get(oi_key), prev_old.get(oi_key)),
            "old_level_coi_now": _to_int(curr_old.get(coi_key)),
            "minutes_since_prior_shift": _mins_since_last_shift(side),
            "spot_at_shift": float(spot) if spot is not None else None,
            "recorded_at": datetime.now(IST).isoformat(),
        }
    except Exception as e:
        print(f"[_build_shift_context] {e}")
        return {"error": str(e)[:200]}



from py_vollib.black_scholes import black_scholes as bs_price
from py_vollib.black_scholes.greeks.analytical import delta as bs_delta

def calculate_premium(spot, strike, iv, dte, option_type):
    """
    Calculate option premium and delta using Black-Scholes.
    option_type: 'c' for call, 'p' for put
    dte: Days to expiry (float)
    iv: Implied Volatility as a decimal (e.g., 0.15 for 15%)
    """
    if dte <= 0 or iv <= 0:
        # Fallback to intrinsic value if expired or no IV
        if option_type == 'c': return max(0, spot - strike), 1.0 if spot > strike else 0.0
        if option_type == 'p': return max(0, strike - spot), -1.0 if spot < strike else 0.0
    
    t = dte / 365.0
    r = 0.05 # Risk-free rate (approx 5% in India)
    try:
        price = bs_price(option_type, spot, strike, t, r, iv)
        d = bs_delta(option_type, spot, strike, t, r, iv)
        return round(price, 1), round(d, 2)
    except Exception:
        return 0.0, 0.0

def generate_action_events() -> list:
    # v1.11.1: hard gate at the source. No action events computed or written
    # outside market hours. Covers ALL callers (flash-alerts, action-dashboard,
    # commentary, etc.) since this function both generates AND persists events.
    if not is_market_hours_now():
        return [{"priority": 99, "icon": "⚪", "type": "info", "level": "INFO", "message": "Market closed. Showing last available data.", "suggested_action": None}]
    events = []
    prev_levels = get_previous_intraday_levels("NIFTY")

    # v1.5.0: fetch macro context once
    macro_ctx = get_macro_context_now()
    macro_active = macro_ctx.get("in_window", False)
    macro_event = macro_ctx.get("active_event")
    macro_phase = macro_ctx.get("phase")
    macro_offset = macro_ctx.get("minutes_offset", 0)

    # v1.5.1: coverage warning
    try:
        _health = compute_data_health()
        if _health.get("days_of_coverage", 999) < MACRO_COVERAGE_WARN_DAYS:
            events.append({
                "priority": 8, "icon": "\U0001F4CA", "type": "coverage_warning",
                "level": "SIGNAL",
                "message": f"Macro data coverage low: {_health.get('days_of_coverage')} days "
                           f"(threshold {MACRO_COVERAGE_WARN_DAYS})",
                "suggested_action": "Add events via POST /api/macro-events"
            })
    except Exception as _e:
        print(f"[Coverage warning] {_e}")

    # ---------- Fetch VIX first (needed for vix_shift alert below) ----------
    current_vix = None
    vix_change_pct = 0.0
    try:
        vix_ticker = yf.Ticker("^INDIAVIX")
        vix_data = vix_ticker.history(period="5d")
        if not vix_data.empty:
            # v1.11.1: yfinance returns stale close values before market open.
            # Only trust the bar if it is from today, OR market is open right now.
            last_bar_date = vix_data.index[-1].date()
            today_ist = datetime.now(IST).date()
            market_open = is_market_hours_now()
            if last_bar_date != today_ist and not market_open:
                print(f"[Action] VIX stale (last bar {last_bar_date}, today {today_ist}, market closed) — skipping")
                current_vix = None
            else:
                current_vix = float(vix_data["Close"].iloc[-1])
                if len(vix_data) >= 2:
                    prev_vix_close = float(vix_data["Close"].iloc[-2])
                    if prev_vix_close:
                        vix_change_pct = round(((current_vix - prev_vix_close) / prev_vix_close) * 100, 2)
    except Exception as e:
        print(f"[Action] VIX error: {e}")

    # ---------- Fetch option chain (with vix_value so it persists) ----------
    nifty_oc = fetch_option_chain_levels("NIFTY", vix_value=current_vix)

    nifty_const = fetch_constituents("NIFTY").get("constituents", [])

    if not nifty_oc or (isinstance(nifty_oc, dict) and nifty_oc.get("error")):
        return [{"priority": 99, "icon": "⚪", "type": "info", "level": "INFO", "message": "OI data unavailable (market closed or fetch error).", "suggested_action": None}]

    # ---------- VIX surge / drop (based on REAL-TIME snapshot change) ----------
    # v1.12.4: Instead of yesterday's close, compare to the last snapshot.
    if current_vix is not None:
        prev_vix_snap = prev_levels.get("prev_vix")
        if prev_vix_snap is not None and prev_vix_snap > 0:
            vix_snap_pct = ((current_vix - prev_vix_snap) / prev_vix_snap) * 100
            
            # Check for cooldown (60 mins) to prevent spam
            is_cooled_down = True
            try:
                conn = sqlite3.connect(SENTIMENT_DB_PATH)
                c = conn.cursor()
                cutoff = (datetime.now(IST) - timedelta(minutes=60)).isoformat()
                c.execute("SELECT COUNT(*) FROM event_history WHERE event_type IN ('vix_surge', 'vix_drop') AND event_at > ?", (cutoff,))
                if c.fetchone()[0] > 0:
                    is_cooled_down = False
                conn.close()
            except Exception:
                pass

            if is_cooled_down and abs(vix_snap_pct) >= 1.5: # 1.5% move in 15 mins is a real surge
                if vix_snap_pct > 0:
                    events.append({"priority": 1, "icon": "⚠️", "type": "vix_surge", "level": "MAJOR",
                                  "message": f"VIX surging intraday (+{vix_snap_pct:.1f}% to {current_vix:.2f}) — premium expansion",
                                  "suggested_action": "Options getting expensive — avoid chasing premium"})
                else:
                    events.append({"priority": 1, "icon": "✅", "type": "vix_drop", "level": "IMPORTANT",
                                  "message": f"VIX cooling down intraday ({vix_snap_pct:.1f}% to {current_vix:.2f}) — premium contraction",
                                  "suggested_action": "Calmer market — options cheaper, potential entry"})

    # ---------- Constituent moves ----------
    for stock in nifty_const:
        pct = stock.get("change_pct")
        if pct is None: continue
        weight = stock.get("weight", 0)
        impact = round(abs(pct) * weight / 100, 3)
        move_vs_atr = stock.get("move_vs_atr")
        direction = "up" if pct > 0 else "down"
        classification = _classify_move(stock)
        level = classification.get("level")
        suggested_action = classification.get("suggested_action")
        if level == "MAJOR": icon, priority = "🚨", 1
        elif level == "IMPORTANT": icon, priority = "🔔", 2
        elif level == "SIGNAL": icon, priority = "🔍", 3
        else: continue

        atr_note = f" • {int(move_vs_atr * 100)}% of 5-day ATR" if move_vs_atr is not None else ""
        impact_note = f" • contributing ~{impact:.3f}% to NIFTY"
        message = f"{level}: {stock['name']} {pct:+.2f}% ({weight}% weight) — {direction}{atr_note}{impact_note}"

        events.append({"priority": priority, "icon": icon, "type": f"{level.lower()}_move",
                      "level": level, "message": message, "suggested_action": suggested_action})

    # ---------- Sector alert ----------
    sector_summary = _build_sector_summary(nifty_const)
    for sector, sdata in sector_summary.items():
        if sdata["count"] >= 3 and abs(sdata["avg_change"]) >= 1.5:
            direction = "weak" if sdata["avg_change"] < 0 else "strong"
            events.append({"priority": 4, "icon": "📊", "type": "sector_alert", "level": "IMPORTANT",
                          "message": f"{sector} sector {direction}: avg {sdata['avg_change']:+.2f}% across {sdata['count']} stocks",
                          "suggested_action": f"Coordinated {sector} move — check sector rotation"})

    # ============================================================
    # v1.4.0: DB-backed shift detection (same-day only)
    # ============================================================

    # --- Support shift ---
    # v1.11.1: attach full context (OI at both levels, deltas, time since prior shift)
    if "support" in nifty_oc and isinstance(nifty_oc.get("support"), dict):
        curr_sup = nifty_oc["support"].get("level")
        prev_sup = prev_levels.get("prev_support")
        if curr_sup is not None and prev_sup is not None:
            diff = curr_sup - prev_sup
            if abs(diff) >= SUPPORT_RESISTANCE_SHIFT_MIN:
                direction = "UP" if diff > 0 else "DOWN"
                ctx = _build_shift_context(
                    side="support",
                    new_level=curr_sup,
                    old_level=prev_sup,
                    current_oc=nifty_oc,
                    prev_levels=prev_levels,
                    spot=nifty_oc.get("spot"),
                )
                events.append({
                    "priority": 4, "icon": "📍", "type": "support_shift", "level": "IMPORTANT",
                    "message": f"NIFTY Support shifted {direction} from {int(prev_sup):,} to {int(curr_sup):,}",
                    "suggested_action": "Adjust stops and targets to new support",
                    "metadata": ctx,
                })

    # --- Resistance shift ---
    # v1.11.1: attach full context
    if "resistance" in nifty_oc and isinstance(nifty_oc.get("resistance"), dict):
        curr_res = nifty_oc["resistance"].get("level")
        prev_res = prev_levels.get("prev_resistance")
        if curr_res is not None and prev_res is not None:
            diff = curr_res - prev_res
            if abs(diff) >= SUPPORT_RESISTANCE_SHIFT_MIN:
                direction = "UP" if diff > 0 else "DOWN"
                ctx = _build_shift_context(
                    side="resistance",
                    new_level=curr_res,
                    old_level=prev_res,
                    current_oc=nifty_oc,
                    prev_levels=prev_levels,
                    spot=nifty_oc.get("spot"),
                )
                events.append({
                    "priority": 4, "icon": "📍", "type": "resistance_shift", "level": "IMPORTANT",
                    "message": f"NIFTY Resistance shifted {direction} from {int(prev_res):,} to {int(curr_res):,}",
                    "suggested_action": "Adjust stops and targets to new resistance",
                    "metadata": ctx,
                })

    # --- PCR shift + PCR surge ---
    curr_pcr = nifty_oc.get("pcr")
    prev_pcr = prev_levels.get("prev_pcr")
    if curr_pcr is not None and prev_pcr is not None and prev_pcr > 0:
        diff = curr_pcr - prev_pcr
        pct_change = (diff / prev_pcr) * 100

        if abs(pct_change) >= PCR_SURGE_PCT_MIN:
            tone = "bullish" if diff > 0 else "bearish"
            events.append({"priority": 2, "icon": "🚀", "type": "pcr_surge", "level": "IMPORTANT",
                          "message": f"PCR SURGE: {prev_pcr:.2f} → {curr_pcr:.2f} ({pct_change:+.1f}%) — {tone} positioning shift",
                          "suggested_action": f"Sharp {tone} buildup — watch for directional move"})
        elif abs(diff) >= PCR_SHIFT_MIN:
            tone = "bullish" if diff > 0 else "bearish"
            events.append({"priority": 5, "icon": "🔄", "type": "pcr_shift", "level": "SIGNAL",
                          "message": f"PCR moved from {prev_pcr:.2f} to {curr_pcr:.2f} — {tone} shift",
                          "suggested_action": f"Positioning is now {tone}"})

    # --- Max Pain shift ---
    curr_maxpain = nifty_oc.get("max_pain")
    prev_maxpain = prev_levels.get("prev_max_pain")
    if curr_maxpain is not None and prev_maxpain is not None:
        diff = curr_maxpain - prev_maxpain
        if abs(diff) >= MAXPAIN_SHIFT_MIN:
            events.append({"priority": 7, "icon": "🎯", "type": "maxpain_shift", "level": "SIGNAL",
                          "message": f"Max Pain shifted from {int(prev_maxpain):,} to {int(curr_maxpain):,}",
                          "suggested_action": "Expiry target has moved"})

    # --- VIX shift between snapshots (intraday) ---
    prev_vix = prev_levels.get("prev_vix")
    if current_vix is not None and prev_vix is not None and prev_vix > 0:
        vix_delta = ((current_vix - prev_vix) / prev_vix) * 100
        if abs(vix_delta) >= VIX_SHIFT_MIN_PCT:
            direction = "UP" if vix_delta > 0 else "DOWN"
            events.append({"priority": 3, "icon": "🌪️", "type": "vix_shift", "level": "IMPORTANT",
                          "message": f"VIX shifted {direction} {vix_delta:+.1f}% ({prev_vix:.2f} → {current_vix:.2f}) since last snapshot",
                          "suggested_action": "Volatility regime changed — reassess position sizing"})

    # ============================================================
    # v1.4.0: OI bias flip / surge / wall shifts
    # ============================================================
    oi_buildup = nifty_oc.get("oi_buildup") or {}
    curr_bias = oi_buildup.get("net_bias_label")
    curr_bias_score = oi_buildup.get("net_bias_score")
    prev_bias = prev_levels.get("prev_net_bias_label")
    prev_bias_score = prev_levels.get("prev_net_bias_score")

    # --- OI bias flip ---
    if curr_bias and prev_bias and curr_bias != prev_bias:
        events.append({
            "priority": 1, "icon": "⚡", "type": "oi_bias_flip", "level": "MAJOR",
            "message": f"OI BIAS FLIP: {prev_bias} → {curr_bias} "
                       f"(score {prev_bias_score if prev_bias_score is not None else 0:+.1f} → "
                       f"{curr_bias_score if curr_bias_score is not None else 0:+.1f})",
            "suggested_action": f"Writers flipped {curr_bias.lower()} — recheck directional bias"
        })

    # --- OI net bias score surge ---
    if curr_bias_score is not None and prev_bias_score is not None:
        delta = abs(curr_bias_score - prev_bias_score)
        if delta >= OI_SURGE_SCORE_DELTA:
            direction = "bullish" if curr_bias_score > prev_bias_score else "bearish"
            events.append({
                "priority": 2, "icon": "🐋", "type": "oi_surge", "level": "IMPORTANT",
                "message": f"OI SURGE: net bias {prev_bias_score:+.1f} → {curr_bias_score:+.1f} ({direction} writing)",
                "suggested_action": f"Writers aggressively adding {direction} positions"
            })

    # --- Call wall shift (top call OI strike moved) ---
    curr_top_call = (nifty_oc.get("top_call_oi") or {}).get("strike")
    curr_top_call_oi = (nifty_oc.get("top_call_oi") or {}).get("oi", 0)
    prev_top_call = prev_levels.get("prev_top_call_oi_strike")
    if curr_top_call and prev_top_call and curr_top_call != prev_top_call:
        events.append({
            "priority": 4, "icon": "🧱", "type": "call_wall_shift", "level": "IMPORTANT",
            "message": f"Resistance is getting powerful. Level shifted from {int(prev_top_call):,} to {int(curr_top_call):,}. {int(curr_top_call_oi):,} OI made it happen.",
            "suggested_action": "Resistance wall relocating — adjust targets"
        })

    # --- Put wall shift (top put OI strike moved) ---
    curr_top_put = (nifty_oc.get("top_put_oi") or {}).get("strike")
    curr_top_put_oi = (nifty_oc.get("top_put_oi") or {}).get("oi", 0)
    prev_top_put = prev_levels.get("prev_top_put_oi_strike")
    if curr_top_put and prev_top_put and curr_top_put != prev_top_put:
        events.append({
            "priority": 4, "icon": "🧱", "type": "put_wall_shift", "level": "IMPORTANT",
            "message": f"Support is getting powerful. Level shifted from {int(prev_top_put):,} to {int(curr_top_put):,}. {int(curr_top_put_oi):,} OI made it happen.",
            "suggested_action": "Support wall relocating — adjust stops"
        })

    # ============================================================
    # v1.4.0: Conviction building / fading / break imminent
    # ============================================================
    conviction_block = nifty_oc.get("conviction") or {}
    spot = nifty_oc.get("spot")

    for side in ("support", "resistance"):
        conv = conviction_block.get(side) or {}
        curr_score = conv.get("score")
        if curr_score is None:
            continue

        # Compare with previous conviction — we recompute from prev_levels OI
        prev_oi = prev_levels.get(f"prev_{side}_oi")
        prev_coi = prev_levels.get(f"prev_{side}_coi")
        prev_strike = prev_levels.get(f"prev_{side}")
        curr_strike = (nifty_oc.get(side) or {}).get("level")

        # Only compare if the strike has NOT shifted (Q2-A: follow the level)
        if prev_strike is None or curr_strike is None or prev_strike != curr_strike:
            prev_score = None
        else:
            try:
                prev_conv = compute_conviction(
                    "NIFTY", prev_strike, prev_oi, prev_coi, side
                )
                prev_score = prev_conv.get("score")
            except Exception:
                prev_score = None

        side_label = side.upper()
        strike_str = f"{int(curr_strike):,}" if curr_strike else "—"

        # Conviction building / fading
        # v1.11.1: also emit STATE events when the strike shifts and a new
        # level establishes strong conviction (>=70/80/90). Fixes the gap
        # where support moving 22,000 -> 22,700 suppressed all signal.
        if prev_score is not None:
            delta = curr_score - prev_score
            if abs(delta) >= CONVICTION_BUILD_DELTA:
                if delta > 0:
                    events.append({
                        "priority": 3, "icon": "🏗️",
                        "type": f"{side}_conviction_building", "level": "IMPORTANT",
                        "message": f"{side_label} conviction BUILDING at {strike_str} "
                                   f"(+{delta:.0f}% → {curr_score:.0f}%)",
                        "suggested_action": f"Writers defending {strike_str} — {side_label.lower()} likely to hold"
                    })
                else:
                    events.append({
                        "priority": 3, "icon": "💨",
                        "type": f"{side}_conviction_fading", "level": "IMPORTANT",
                        "message": f"{side_label} conviction FADING at {strike_str} "
                                   f"({delta:.0f}% → {curr_score:.0f}%)",
                        "suggested_action": f"Writers pulling back — {side_label.lower()} may break"
                    })
        elif prev_strike is not None and curr_strike is not None and prev_strike != curr_strike:
            # Strike moved. Emit a STATE event for the new level so the
            # transition (support building at 22,700) is recorded.
            events.append({
                "priority": 3, "icon": "📍",
                "type": f"{side}_level_shift",
                "level": "IMPORTANT" if curr_score >= CONVICTION_STRONG else "SIGNAL",
                "message": f"{side_label} level shifted {int(prev_strike):,} → {strike_str} "
                           f"(new conviction {curr_score:.0f}%)",
                "suggested_action": f"Watch {strike_str} — new {side_label.lower()} pivot"
            })

        # v1.11.1: STRONG-state event — fires when a level crosses 70/80/90
        # upward, regardless of strike. Gives the drawer a durable record.
        if curr_score >= CONVICTION_STRONG:
            for tier, label in ((90, "HARDENED"), (80, "VERY_STRONG"), (70, "STRONG")):
                if curr_score >= tier and (prev_score is None or prev_score < tier):
                    events.append({
                        "priority": 2, "icon": "🛡️" if side == "support" else "🧱",
                        "type": f"{side}_conviction_{label.lower()}",
                        "level": "MAJOR" if tier >= 80 else "IMPORTANT",
                        "message": f"{side_label} conviction {label} at {strike_str} "
                                   f"({curr_score:.0f}%)",
                        "suggested_action": f"Writers firmly defending {strike_str}"
                    })
                    break  # only fire highest tier crossed

        # Break imminent: low conviction + price close to the level
        if (curr_score < CONVICTION_BREAK_THRESHOLD
                and spot is not None and curr_strike is not None):
            distance = abs(spot - curr_strike)
            if distance <= CONVICTION_BREAK_PRICE_PROXIMITY:
                events.append({
                    "priority": 1, "icon": "🚨",
                    "type": f"{side}_break_imminent", "level": "MAJOR",
                    "message": f"{side_label} at {strike_str} WEAKENING "
                               f"(conviction {curr_score:.0f}%, price {distance:.0f} pts away)",
                    "suggested_action": f"{side_label} may break — prepare for breakout direction"
                })

    # ============================================================
    # Cross-asset signals (existing v1.2.0)
    # ============================================================
    crude_sent = cache_peek("sentiment_CRUDEOIL")
    if crude_sent and crude_sent.get("score") is not None and crude_sent["score"] <= -3:
        events.append({"priority": 6, "icon": "🛢️", "type": "crude_warning", "level": "SIGNAL",
                      "message": f"Crudeoil bearish (score {crude_sent['score']}) — Reliance may follow",
                      "suggested_action": "Watch Reliance for sympathetic move"})

    gold_sent = cache_peek("sentiment_GOLD")
    if gold_sent and gold_sent.get("score") is not None and gold_sent["score"] >= 3:
        events.append({"priority": 6, "icon": "🥇", "type": "gold_strength", "level": "SIGNAL",
                      "message": f"Gold bullish (score {gold_sent['score']}) — defensive rotation",
                      "suggested_action": "Watch for risk-off trade developing"})

    # ============================================================
    # v1.5.0: Macro event suppression + tagging
    # ============================================================
    if macro_active and macro_event:
        for ev in events:
            lvl = ev.get("level", "SIGNAL")
            ev["level"] = MACRO_DOWNGRADE.get(lvl, lvl)
            ev["macro_context"] = {
                "event_id": macro_event.get("id"),
                "event_type": macro_event.get("event_type"),
                "title": macro_event.get("title"),
                "phase": macro_phase,
                "minutes_offset": macro_offset,
                "importance": macro_event.get("importance", "MEDIUM"),
                "downgraded_from": lvl if lvl != ev["level"] else None
            }
        events.insert(0, {
            "priority": 0, "icon": "📅", "type": "macro_event_live",
            "level": "MAJOR",
            "message": f"{macro_event.get('title')} — {macro_phase} window "
                       f"({abs(macro_offset)} min {'to' if macro_offset < 0 else 'after'})",
            "suggested_action": "Expect event-driven noise — size down",
            "macro_context": {
                "event_id": macro_event.get("id"),
                "event_type": macro_event.get("event_type"),
                "title": macro_event.get("title"),
                "phase": macro_phase,
                "minutes_offset": macro_offset,
                "importance": macro_event.get("importance", "MEDIUM"),
                "downgraded_from": None
            }
        })
    elif macro_ctx.get("same_day_event"):
        same = macro_ctx["same_day_event"]
        for ev in events:
            ev["macro_context"] = {
                "event_id": same.get("id"),
                "event_type": same.get("event_type"),
                "title": same.get("title"),
                "phase": "same_day",
                "minutes_offset": None,
                "importance": same.get("importance", "MEDIUM"),
                "downgraded_from": None
            }

    # v1.8.3: bridge ATM surges into the event stream
    try:
        _atm_events = _atm_surges_as_events("NIFTY")
        events.extend(_atm_events)
    except Exception as _e:
        print(f"[Flash] atm bridge into events error: {_e}")

    # v1.11.0: persist every event to history
    try:
        for ev in events:
            log_event(
                event_type=ev.get("type", "unknown"),
                level=ev.get("level", "SIGNAL"),
                icon=ev.get("icon", "•"),
                message=ev.get("message", ""),
                metadata={
                    "suggested_action": ev.get("suggested_action"),
                    "macro_context": ev.get("macro_context"),
                }
            )
    except Exception as _e:
        print(f"[Event history] batch log error: {_e}")

    # ---------- Sort + truncate + fallback ----------
    events.sort(key=lambda x: x["priority"])
    events = events[:ACTION_DASHBOARD_MAX_EVENTS]

    if not events:
        events.append({"priority": 99, "icon": "⚪", "type": "neutral", "level": "INFO",
                      "message": "No significant events detected — market is quiet",
                      "suggested_action": None})

    return events


# ============================================================
# GOOGLE TRENDS (v1.7.0)
# ============================================================
def init_google_trends_db():
    """Create google_trends table. Idempotent."""
    conn = sqlite3.connect(SENTIMENT_DB_PATH)
    c = conn.cursor()
    c.execute("""
        CREATE TABLE IF NOT EXISTS google_trends (
            id           INTEGER PRIMARY KEY AUTOINCREMENT,
            symbol       TEXT NOT NULL,
            keyword      TEXT NOT NULL,
            current      INTEGER,
            avg_7d       REAL,
            peak_7d      INTEGER,
            trend_delta  REAL,
            fetched_at   TEXT DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(symbol, keyword)
        )
    """)
    c.execute("CREATE INDEX IF NOT EXISTS idx_trends_symbol ON google_trends(symbol)")
    conn.commit()
    conn.close()

def save_trend(symbol, keyword, current, avg_7d, peak_7d, trend_delta):
    """Upsert a trend row (latest value overwrites)."""
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("""
            INSERT OR REPLACE INTO google_trends
            (symbol, keyword, current, avg_7d, peak_7d, trend_delta, fetched_at)
            VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
        """, (symbol, keyword, current, avg_7d, peak_7d, trend_delta))
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"[Trends] save error {symbol}: {e}")
        return False

def get_trend(symbol):
    """Fetch stored trend for a symbol. Returns dict or None."""
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("""
            SELECT symbol, keyword, current, avg_7d, peak_7d, trend_delta, fetched_at
            FROM google_trends WHERE symbol = ?
        """, (symbol,))
        row = c.fetchone()
        conn.close()
        if not row:
            return None
        return {
            "symbol": row[0], "keyword": row[1], "current": row[2],
            "avg_7d": row[3], "peak_7d": row[4], "trend_delta": row[5],
            "fetched_at": row[6]
        }
    except Exception as e:
        print(f"[Trends] read error {symbol}: {e}")
        return None

def get_all_trends():
    """Return all stored trends."""
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("""
            SELECT symbol, keyword, current, avg_7d, peak_7d, trend_delta, fetched_at
            FROM google_trends ORDER BY symbol
        """)
        rows = c.fetchall()
        conn.close()
        return [{
            "symbol": r[0], "keyword": r[1], "current": r[2],
            "avg_7d": r[3], "peak_7d": r[4], "trend_delta": r[5],
            "fetched_at": r[6]
        } for r in rows]
    except Exception as e:
        print(f"[Trends] read error: {e}")
        return []

init_google_trends_db()

# ============================================================
# NEWS PIPELINE (v1.6.0)
# ============================================================
def init_stock_news_db():
    """Create stock_news table. Idempotent."""
    conn = sqlite3.connect(SENTIMENT_DB_PATH)
    c = conn.cursor()
    c.execute("""
        CREATE TABLE IF NOT EXISTS stock_news (
            id           INTEGER PRIMARY KEY AUTOINCREMENT,
            symbol       TEXT NOT NULL,
            sector       TEXT,
            headline     TEXT NOT NULL,
            source       TEXT,
            url          TEXT,
            published_at TEXT,
            sentiment    REAL,
            fetched_at   TEXT DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(symbol, headline)
        )
    """)
    c.execute("CREATE INDEX IF NOT EXISTS idx_news_symbol_time ON stock_news(symbol, published_at DESC)")
    c.execute("CREATE INDEX IF NOT EXISTS idx_news_sector_time ON stock_news(sector, published_at DESC)")
    c.execute("CREATE INDEX IF NOT EXISTS idx_news_fetched ON stock_news(fetched_at DESC)")
    conn.commit()
    conn.close()

def score_news_sentiment(headline):
    """Lexicon-based sentiment score for a headline. Returns -1.0 to +1.0."""
    if not headline:
        return 0.0
    text = headline.lower()
    pos = sum(1 for w in NEWS_POSITIVE_WORDS if w in text)
    neg = sum(1 for w in NEWS_NEGATIVE_WORDS if w in text)
    total = pos + neg
    if total == 0:
        return 0.0
    score = (pos - neg) / total
    return round(max(-1.0, min(1.0, score)), 2)

def get_symbol_sector(symbol):
    """Look up sector for a Nifty/Sensex constituent. Returns None if not found."""
    sym_upper = symbol.upper()
    for c in NIFTY50_CONSTITUENTS:
        if c["symbol"].upper() == sym_upper:
            return c["sector"]
    for c in SENSEX30_CONSTITUENTS:
        if c["symbol"].upper() == sym_upper:
            return c["sector"]
    return None

init_stock_news_db()

# ============================================================
# DATA SOURCES
# ============================================================
def fetch_news_headlines(symbol: str, max_headlines: int = 7) -> list:
    query = urllib.parse.quote(SEARCH_QUERIES.get(symbol, symbol))
    url = f"https://news.google.com/rss/search?q={query}&hl=en-IN&gl=IN&ceid=IN:en"
    feed = feedparser.parse(url)
    fresh = [e for e in feed.entries if is_fresh(e)]
    return [entry.title for entry in fresh[:max_headlines]]

def fetch_twitter_posts(symbol: str, max_posts: int = 5) -> list:
    keyword = SEARCH_QUERIES.get(symbol, symbol)
    query = urllib.parse.quote(f'{keyword} site:x.com OR site:twitter.com')
    url = f"https://news.google.com/rss/search?q={query}&hl=en-IN&gl=IN&ceid=IN:en"
    feed = feedparser.parse(url)
    fresh = [e for e in feed.entries if is_fresh(e)]
    return [entry.title for entry in fresh[:max_posts]]

# ============================================================
# YOUTUBE
# ============================================================
FINANCE_CHANNELS = {"CNBC-TV18": "cnbctv18", "ET Now": "ETNOW"}
SYMBOL_KEYWORDS = {
    "NIFTY": ["nifty", "nifty50", "nifty 50"],
    "SENSEX": ["sensex", "bse sensex"],
    "GOLD": ["gold", "gold price", "gold rate", "mcx gold"],
    "SILVER": ["silver", "silver price", "silver rate"],
    "CRUDEOIL": ["crude", "crude oil", "brent", "wti"],
    "BITCOIN": ["bitcoin", "btc"],
}

def extract_video_id(url: str) -> str:
    match = re.search(r'(?:v=|youtu\.be/|/embed/|/shorts/)([A-Za-z0-9_-]{11})', url)
    return match.group(1) if match else ""

def fetch_youtube_transcript(symbol: str, max_chars: int = 2500) -> str:
    keywords = SYMBOL_KEYWORDS.get(symbol, [symbol.lower()])
    cutoff = datetime.now(timezone.utc) - timedelta(hours=NEWS_MAX_AGE_HOURS)

    try:
        api = YouTubeTranscriptApi()
    except Exception as e:
        print(f"[{symbol}] YouTube init error: {e}")
        return ""

    for channel_name, username in FINANCE_CHANNELS.items():
        try:
            feed_url = f"https://www.youtube.com/feeds/videos.xml?user={username}"
            feed = feedparser.parse(feed_url)

            for entry in feed.entries:
                published = getattr(entry, "published_parsed", None)
                if not published:
                    continue
                published_dt = datetime(*published[:6], tzinfo=timezone.utc)
                if published_dt < cutoff:
                    continue

                title_lower = entry.title.lower()
                if not any(kw in title_lower for kw in keywords):
                    continue

                video_id = extract_video_id(entry.link)
                if not video_id:
                    continue

                try:
                    transcript = api.fetch(video_id, languages=['en', 'en-IN', 'hi'])
                    parts = []
                    for chunk in transcript:
                        text = getattr(chunk, 'text', None)
                        if text:
                            parts.append(text)
                    full_text = ' '.join(parts)
                    print(f"[{symbol}] YouTube OK '{entry.title[:60]}' from {channel_name}")
                    return full_text[:max_chars]
                except Exception:
                    continue
        except Exception as e:
            print(f"[{symbol}] Channel {channel_name} error: {e}")
            continue

    print(f"[{symbol}] YouTube: no usable transcript found")
    return ""


# ============================================================
# v1.7.0 — GOOGLE TRENDS FETCHER
# ============================================================
def fetch_trends_for_keywords(keywords):
    """
    Fetch Google Trends interest for a batch of keywords.
    Returns dict {keyword: {current, avg_7d, peak_7d, trend_delta}}.
    """
    out = {}
    if not keywords:
        return out
    try:
        from pytrends.request import TrendReq
    except Exception as e:
        print(f"[Trends] pytrends import failed: {e}")
        return out
    try:
        pt = TrendReq(hl=TRENDS_HL, tz=TRENDS_TZ, timeout=(10, 25))
        pt.build_payload(keywords, cat=0, timeframe=TRENDS_TIMEFRAME, geo=TRENDS_GEO)
        df = pt.interest_over_time()
        if df is None or df.empty:
            print(f"[Trends] empty response for {keywords}")
            return out
        for kw in keywords:
            if kw not in df.columns:
                continue
            series = df[kw].dropna()
            if len(series) == 0:
                continue
            current = int(series.iloc[-1])
            avg_7d = round(float(series.mean()), 1)
            peak_7d = int(series.max())
            if len(series) >= 24:
                first_recent = float(series.iloc[-24])
                delta = round(current - first_recent, 1)
            else:
                delta = 0.0
            out[kw] = {
                "current": current,
                "avg_7d": avg_7d,
                "peak_7d": peak_7d,
                "trend_delta": delta
            }
    except Exception as e:
        print(f"[Trends] fetch error: {type(e).__name__}: {e}")
    return out

def refresh_trends():
    """Fetch and store trends for all symbols in TRENDS_SYMBOL_MAP."""
    started = datetime.now(IST)
    print(f"\n[Trends] Refresh started {started.strftime('%H:%M:%S IST')}")
    batch_size = TRENDS_MAX_KEYWORDS_PER_REQUEST
    pairs = list(TRENDS_SYMBOL_MAP)
    total_stored = 0
    for i in range(0, len(pairs), batch_size):
        batch = pairs[i:i + batch_size]
        keywords = [kw for _, kw in batch]
        results = fetch_trends_for_keywords(keywords)
        for sym, kw in batch:
            data = results.get(kw)
            if not data:
                continue
            ok = save_trend(
                sym, kw,
                data["current"], data["avg_7d"],
                data["peak_7d"], data["trend_delta"]
            )
            if ok:
                total_stored += 1
        if i + batch_size < len(pairs):
            time.sleep(TRENDS_REQUEST_DELAY_SEC)
    elapsed = (datetime.now(IST) - started).total_seconds()
    print(f"[Trends] Done: {total_stored}/{len(pairs)} stored, {elapsed:.1f}s")


# ============================================================
# v1.6.0 — NEWS FETCHER (Google News RSS per symbol)
# ============================================================
def _normalize_news_symbol(symbol):
    """Convert 'HDFCBANK.NS' -> 'HDFCBANK' for RSS query."""
    s = symbol.upper()
    for suf in (".NS", ".BO"):
        if s.endswith(suf):
            s = s[:-len(suf)]
    return s

def _is_news_headline(headline):
    """v1.6.1: filter out quote/ticker pages."""
    if not headline:
        return False
    text = headline.lower()
    return any(kw in text for kw in NEWS_SIGNAL_KEYWORDS)

def fetch_news_for_symbol(symbol, max_items=None):
    """
    v1.6.1 — Fetch headlines for one symbol from Google News RSS.
    Uses narrowed query + post-filter to exclude quote/ticker pages.
    Returns list of dicts: {headline, source, url, published_at}.
    """
    if max_items is None:
        max_items = NEWS_MAX_PER_SYMBOL
    clean = _normalize_news_symbol(symbol)
    # Narrowed query: news-event specific
    query = urllib.parse.quote(
        f'"{clean}" earnings OR results OR profit OR order OR acquisition OR board'
    )
    url = f"https://news.google.com/rss/search?q={query}&hl=en-IN&gl=IN&ceid=IN:en"
    all_items = []
    try:
        feed = feedparser.parse(url)
        for entry in feed.entries[:max_items * 2]:  # fetch extra, filter down
            pub = getattr(entry, "published_parsed", None)
            pub_iso = None
            if pub:
                try:
                    pub_iso = datetime(*pub[:6], tzinfo=timezone.utc).isoformat()
                except Exception:
                    pub_iso = None
            src = ""
            if hasattr(entry, "source") and entry.source:
                src = getattr(entry.source, "title", "") or ""
            all_items.append({
                "headline": entry.title,
                "source": src,
                "url": entry.link,
                "published_at": pub_iso
            })
    except Exception as e:
        print(f"[News] fetch error {symbol}: {e}")
        return []

    # Post-filter for news-signal keywords
    filtered = [it for it in all_items if _is_news_headline(it["headline"])]
    # Fallback: if filter yields nothing, keep 2 most recent unfiltered
    if not filtered and all_items:
        filtered = all_items[:2]
    return filtered[:max_items]

def store_news_items(symbol, sector, items):
    """Store news items in stock_news. Returns count of new inserts."""
    if not items:
        return 0
    inserted = 0
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        for it in items:
            hl = it.get("headline", "")
            if not hl:
                continue
            senti = score_news_sentiment(hl)
            try:
                c.execute("""
                    INSERT OR IGNORE INTO stock_news
                    (symbol, sector, headline, source, url, published_at, sentiment)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                """, (symbol, sector, hl, it.get("source"),
                      it.get("url"), it.get("published_at"), senti))
                if c.rowcount > 0:
                    inserted += 1
            except Exception as e:
                print(f"[News] insert error {symbol}: {e}")
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"[News] store error {symbol}: {e}")
    return inserted

def refresh_news_universe(limit=None):
    """
    Fetch and store news for the F&O universe.
    If limit given, only process first N symbols (for testing).
    """
    started = datetime.now(IST)
    print(f"\n[News] Refresh started {started.strftime('%H:%M:%S IST')}")
    try:
        stocks = get_fno_stocks()
    except Exception as e:
        print(f"[News] universe fetch error: {e}")
        return
    if limit is not None:
        stocks = stocks[:limit]
    total_fetched = 0
    total_inserted = 0
    for stock in stocks:
        sym = stock.get("symbol", "")
        sector = stock.get("sector") or get_symbol_sector(sym)
        items = fetch_news_for_symbol(sym)
        total_fetched += len(items)
        ins = store_news_items(sym, sector, items)
        total_inserted += ins
        time.sleep(NEWS_FETCH_DELAY_SEC)
    elapsed = (datetime.now(IST) - started).total_seconds()
    print(f"[News] Done: {len(stocks)} symbols, {total_fetched} fetched, "
          f"{total_inserted} new inserts, {elapsed:.1f}s")


def _news_symbol_variants(symbol):
    """
    v1.6.3 — Return possible DB symbol variants for a given input.
    DB stores 'RELIANCE.NS'; API gets 'RELIANCE'. Match both.
    """
    s = symbol.upper().strip()
    variants = [s]
    if not s.endswith(".NS") and not s.endswith(".BO"):
        variants.append(s + ".NS")
        variants.append(s + ".BO")
    else:
        # strip suffix
        for suf in (".NS", ".BO"):
            if s.endswith(suf):
                variants.append(s[:-len(suf)])
    return variants

def get_news_for_symbol(symbol, hours=24):
    """Return recent news for one symbol from DB."""
    try:
        _cut = datetime.now(timezone.utc).replace(microsecond=0) - timedelta(hours=hours)
        cutoff = _cut.strftime("%Y-%m-%dT%H:%M:%S+00:00")
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        variants = _news_symbol_variants(symbol)
        placeholders = ",".join("?" * len(variants))
        c.execute(f"""
            SELECT headline, source, url, published_at, sentiment
            FROM stock_news
            WHERE symbol IN ({placeholders})
              AND (published_at IS NULL OR published_at >= ?)
            ORDER BY published_at DESC
            LIMIT 50
        """, (*variants, cutoff))
        rows = c.fetchall()
        conn.close()
        return [{
            "headline": r[0], "source": r[1], "url": r[2],
            "published_at": r[3], "sentiment": r[4]
        } for r in rows]
    except Exception as e:
        print(f"[News] read error {symbol}: {e}")
        return []

def get_news_for_sector(sector, hours=24):
    """Return recent news aggregated for one sector."""
    try:
        _cut = datetime.now(timezone.utc).replace(microsecond=0) - timedelta(hours=hours)
        cutoff = _cut.strftime("%Y-%m-%dT%H:%M:%S+00:00")
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        # v1.6.3: sector match is case-insensitive + trim
        sector_norm = sector.strip()
        c.execute("""
            SELECT symbol, headline, source, url, published_at, sentiment
            FROM stock_news
            WHERE LOWER(sector) = LOWER(?)
              AND (published_at IS NULL OR published_at >= ?)
            ORDER BY published_at DESC
            LIMIT 100
        """, (sector_norm, cutoff))
        rows = c.fetchall()
        conn.close()
        items = [{
            "symbol": r[0], "headline": r[1], "source": r[2],
            "url": r[3], "published_at": r[4], "sentiment": r[5]
        } for r in rows]
        if items:
            scores = [i["sentiment"] for i in items if i["sentiment"] is not None]
            avg = round(sum(scores) / len(scores), 2) if scores else 0.0
        else:
            avg = 0.0
        return {"sector": sector, "count": len(items), "avg_sentiment": avg, "items": items}
    except Exception as e:
        print(f"[News] sector read error {sector}: {e}")
        return {"sector": sector, "count": 0, "avg_sentiment": 0.0, "items": []}


# ============================================================
# SENTIMENT AGGREGATOR
# ============================================================
def get_sentiment_score(symbol: str, bypass_cache: bool = False) -> dict:
    cache_key = f"sentiment_{symbol}"
    if not bypass_cache:
        cached = cache_get(cache_key)
        if cached:
            return cached

    news = fetch_news_headlines(symbol)
    tweets = fetch_twitter_posts(symbol)
    youtube_text = fetch_youtube_transcript(symbol)
    fii_dii_score = fetch_fii_dii_score() if symbol in FII_DII_SYMBOLS else 0.0

    news_score = ai_sentiment(symbol, '\n'.join(news)) if news else 0.0
    twitter_score = ai_sentiment(symbol, '\n'.join(tweets)) if tweets else 0.0
    youtube_score = ai_sentiment(symbol, youtube_text) if youtube_text else 0.0

    weights, scores = [], []
    if news:         weights.append(0.50); scores.append(news_score)
    if youtube_text: weights.append(0.20); scores.append(youtube_score)
    if tweets:       weights.append(0.10); scores.append(twitter_score)
    if symbol in FII_DII_SYMBOLS:
        weights.append(0.30); scores.append(fii_dii_score)

    if not scores:
        result = {
            "symbol": symbol, "score": 0.0, "label": "NEUTRAL",
            "news_score": 0.0, "twitter_score": 0.0, "youtube_score": 0.0,
            "fii_dii_score": 0.0,
            "headlines": [], "tweets": [], "has_youtube": False
        }
        cache_set(cache_key, result)
        save_to_history(symbol, result)
        return result

    total_weight = sum(weights)
    final_score = round(sum(s * w for s, w in zip(scores, weights)) / total_weight, 1)

    if final_score <= -1:
        label = "BEARISH"
    elif final_score >= 1:
        label = "BULLISH"
    else:
        label = "NEUTRAL"

    result = {
        "symbol": symbol, "score": final_score, "label": label,
        "news_score": news_score, "twitter_score": twitter_score,
        "youtube_score": youtube_score, "fii_dii_score": fii_dii_score,
        "headlines": news, "tweets": tweets, "has_youtube": bool(youtube_text)
    }
    cache_set(cache_key, result)
    save_to_history(symbol, result)
    return result

# ============================================================
# ZONE SCANNER — DB
# ============================================================
def init_zones_db():
    conn = sqlite3.connect(ZONES_DB_PATH)
    c = conn.cursor()
    c.execute("""
        CREATE TABLE IF NOT EXISTS zones (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            symbol TEXT NOT NULL,
            name TEXT,
            sector TEXT,
            zone_type TEXT NOT NULL,
            zone_top REAL NOT NULL,
            zone_bottom REAL NOT NULL,
            created_at TEXT NOT NULL,
            created_price REAL,
            age_bars INTEGER DEFAULT 0,
            entry_count INTEGER DEFAULT 0,
            first_entry_at TEXT,
            last_entry_at TEXT,
            last_entry_price REAL,
            is_active INTEGER DEFAULT 1,
            UNIQUE(symbol, zone_type, created_at)
        )
    """)
    c.execute("""
        CREATE TABLE IF NOT EXISTS zone_events (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            symbol TEXT NOT NULL,
            name TEXT,
            sector TEXT,
            event_type TEXT NOT NULL,
            zone_type TEXT,
            zone_top REAL,
            zone_bottom REAL,
            price REAL,
            event_at TEXT NOT NULL,
            tier TEXT,
            message TEXT
        )
    """)
    try:
        c.execute("ALTER TABLE zone_events ADD COLUMN sector TEXT")
    except sqlite3.OperationalError:
        pass
    conn.commit()
    conn.close()

init_zones_db()

def zone_exists(symbol, zone_type, created_at):
    conn = sqlite3.connect(ZONES_DB_PATH)
    c = conn.cursor()
    c.execute("SELECT id FROM zones WHERE symbol=? AND zone_type=? AND created_at=?",
              (symbol, zone_type, created_at))
    row = c.fetchone()
    conn.close()
    return row is not None

def zone_overlaps_existing(symbol, zone_type, zone_top, zone_bottom, overlap_threshold=0.60):
    """
    v1.3.0: Reject near-identical zones.
    If the new zone's range overlaps an existing active zone of the same type
    by > overlap_threshold (fraction of the smaller zone's width) — treat as dup.
    """
    new_width = zone_top - zone_bottom
    if new_width <= 0:
        return False
    try:
        conn = sqlite3.connect(ZONES_DB_PATH)
        c = conn.cursor()
        c.execute("""
            SELECT zone_top, zone_bottom FROM zones
            WHERE symbol = ? AND zone_type = ? AND is_active = 1
        """, (symbol, zone_type))
        rows = c.fetchall()
        conn.close()
    except Exception as e:
        print(f"[zone_overlaps] DB error: {e}")
        return False

    for (old_top, old_bottom) in rows:
        if old_top is None or old_bottom is None:
            continue
        overlap = min(zone_top, old_top) - max(zone_bottom, old_bottom)
        if overlap <= 0:
            continue
        old_width = old_top - old_bottom
        smaller_width = min(new_width, old_width) if old_width > 0 else new_width
        if smaller_width > 0 and (overlap / smaller_width) > overlap_threshold:
            return True
    return False

def insert_zone(zone):
    conn = sqlite3.connect(ZONES_DB_PATH)
    c = conn.cursor()
    try:
        c.execute("""
            INSERT OR IGNORE INTO zones
            (symbol, name, sector, zone_type, zone_top, zone_bottom,
             created_at, created_price, age_bars, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 1)
        """, (
            zone["symbol"], zone["name"], zone.get("sector", ""),
            zone["zone_type"], zone["zone_top"], zone["zone_bottom"],
            zone["created_at"], zone["created_price"]
        ))
        conn.commit()
        # v1.22.0: Log zone to accuracy tracker
        try:
            _zt = zone.get("zone_type", "").upper()
            _top = float(zone.get("zone_top") or 0)
            _bot = float(zone.get("zone_bottom") or 0)
            if _top > 0 and _bot > 0:
                _width = _top - _bot
                if "DEMAND" in _zt or "BULL" in _zt:
                    _entry = _top
                    _stop = _bot
                    _target = _top + (2 * _width)
                elif "SUPPLY" in _zt or "BEAR" in _zt:
                    _entry = _bot
                    _stop = _top
                    _target = _bot - (2 * _width)
                else:
                    _entry = _stop = _target = None
                if _entry is not None:
                    log_zone_to_tracker(
                        symbol=zone["symbol"],
                        zone_type=_zt,
                        entry_spot=_entry,
                        stop_spot=_stop,
                        target_spot=_target
                    )
        except Exception as _ze:
            print(f"[Zone Tracker] Skip: {_ze}")
    except Exception as e:
        print(f"Insert zone error: {e}")
    conn.close()

def insert_zone_event(event):
    conn = sqlite3.connect(ZONES_DB_PATH)
    c = conn.cursor()
    try:
        c.execute("""
            INSERT INTO zone_events
            (symbol, name, sector, event_type, zone_type, zone_top, zone_bottom,
             price, event_at, tier, message)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            event["symbol"], event.get("name"), event.get("sector", ""),
            event["event_type"], event.get("zone_type"), event.get("zone_top"),
            event.get("zone_bottom"), event.get("price"), event["event_at"],
            event.get("tier"), event.get("message")
        ))
        conn.commit()
    except Exception as e:
        print(f"Insert zone event error: {e}")
    conn.close()

def get_active_zones():
    cutoff = (datetime.now(IST) - timedelta(hours=ZONE_MAX_AGE_HOURS)).isoformat()
    conn = sqlite3.connect(ZONES_DB_PATH)
    c = conn.cursor()
    c.execute("""
        SELECT id, symbol, name, sector, zone_type, zone_top, zone_bottom,
               created_at, created_price, age_bars, entry_count,
               first_entry_at, last_entry_at, last_entry_price
        FROM zones
        WHERE is_active = 1 AND created_at >= ?
    """, (cutoff,))
    rows = c.fetchall()
    conn.close()
    return [{
        "id": r[0], "symbol": r[1], "name": r[2], "sector": r[3],
        "zone_type": r[4], "zone_top": r[5], "zone_bottom": r[6],
        "created_at": r[7], "created_price": r[8], "age_bars": r[9],
        "entry_count": r[10], "first_entry_at": r[11],
        "last_entry_at": r[12], "last_entry_price": r[13],
    } for r in rows]

def update_zone_entry(zone_id, price, at_time):
    conn = sqlite3.connect(ZONES_DB_PATH)
    c = conn.cursor()
    c.execute("""
        UPDATE zones
        SET entry_count = entry_count + 1,
            first_entry_at = COALESCE(first_entry_at, ?),
            last_entry_at = ?,
            last_entry_price = ?
        WHERE id = ?
    """, (at_time, at_time, price, zone_id))
    conn.commit()
    conn.close()

def deactivate_old_zones():
    cutoff = (datetime.now(IST) - timedelta(hours=ZONE_MAX_AGE_HOURS)).isoformat()
    conn = sqlite3.connect(ZONES_DB_PATH)
    c = conn.cursor()
    c.execute("UPDATE zones SET is_active = 0 WHERE created_at < ?", (cutoff,))
    conn.commit()
    conn.close()

# ============================================================
# ZONE SCANNER — PIVOTS
# ============================================================
def find_pivots(bars):
    pivots = []
    n = len(bars)
    if n < PIVOT_LEFT + PIVOT_RIGHT + 1:
        return pivots

    for i in range(PIVOT_LEFT, n - PIVOT_RIGHT):
        bar = bars[i]

        is_pivot_low = True
        for j in range(i - PIVOT_LEFT, i):
            if bars[j]["low"] <= bar["low"]:
                is_pivot_low = False
                break
        if is_pivot_low:
            for j in range(i + 1, i + PIVOT_RIGHT + 1):
                if bars[j]["low"] <= bar["low"]:
                    is_pivot_low = False
                    break

        if is_pivot_low:
            body_low = min(bar["open"], bar["close"])
            box_top = max(bar["low"], body_low)
            box_bottom = min(bar["low"], body_low)
            pivots.append({"index": i, "type": "bull",
                          "top": round(box_top, 2), "bottom": round(box_bottom, 2),
                          "price": bar["low"], "time": bar["time"]})

        is_pivot_high = True
        for j in range(i - PIVOT_LEFT, i):
            if bars[j]["high"] >= bar["high"]:
                is_pivot_high = False
                break
        if is_pivot_high:
            for j in range(i + 1, i + PIVOT_RIGHT + 1):
                if bars[j]["high"] >= bar["high"]:
                    is_pivot_high = False
                    break

        if is_pivot_high:
            body_high = max(bar["open"], bar["close"])
            box_top = max(bar["high"], body_high)
            box_bottom = min(bar["high"], body_high)
            pivots.append({"index": i, "type": "bear",
                          "top": round(box_top, 2), "bottom": round(box_bottom, 2),
                          "price": bar["high"], "time": bar["time"]})

    return pivots

def fetch_15m_bars(symbol, days=3):
    try:
        ticker = yf.Ticker(symbol)
        df = ticker.history(period=f"{days}d", interval="15m", prepost=False)
        if df.empty:
            return []
        bars = []
        for idx, row in df.iterrows():
            try:
                bars.append({
                    "time": idx.isoformat(),
                    "open": float(row["Open"]),
                    "high": float(row["High"]),
                    "low": float(row["Low"]),
                    "close": float(row["Close"]),
                    "volume": int(row["Volume"]) if not math.isnan(float(row["Volume"])) else 0,
                })
            except (ValueError, TypeError):
                continue
        return bars
    except Exception as e:
        print(f"[{symbol}] 15m fetch error: {e}")
        return []

def classify_zone_event(stock, zone, event_type, is_fresh=True):
    name = stock.get("name", stock["symbol"])
    zone_type = zone.get("zone_type")
    zone_label = "🟢 Bullish" if zone_type == "bull" else "🔴 Bearish"

    if event_type == "zone_created":
        tier = "IMPORTANT" if is_fresh else "SIGNAL"
        msg = f"NEW ZONE: {name} created a {zone_label} reversal zone ({zone['zone_bottom']}-{zone['zone_top']})"
    elif event_type == "zone_entered":
        entry_count = zone.get("entry_count", 0)
        if entry_count == 0:
            tier = "IMPORTANT"
            msg = f"FIRST ENTRY: {name} entered {zone_label} reversal zone ({zone['zone_bottom']}-{zone['zone_top']})"
        else:
            tier = "SIGNAL"
            msg = f"RE-ENTRY: {name} re-entered {zone_label} zone (entry #{entry_count + 1})"
    else:
        tier = "SIGNAL"
        msg = f"{name} zone event"

    return tier, msg

def run_zone_scan():
    started = datetime.now(IST)
    print(f"\n[{started.strftime('%Y-%m-%d %H:%M:%S IST')}] Zone scan started...")

    try:
        current_vix = None
        try:
            vix_t = yf.Ticker("^INDIAVIX")
            vix_h = vix_t.history(period="2d")
            if not vix_h.empty:
                current_vix = float(vix_h["Close"].iloc[-1])
        except Exception:
            pass
        oc = fetch_option_chain_levels("NIFTY", vix_value=current_vix)
        if oc and not oc.get("error"):
            print(f"  [NIFTY] intraday snapshot: S={oc.get('support',{}).get('level')} "
                  f"R={oc.get('resistance',{}).get('level')} PCR={oc.get('pcr')}")
    except Exception as e:
        print(f"  [NIFTY] snapshot error: {e}")

    stocks = get_fno_stocks()
    print(f"  Universe: {len(stocks)} F&O stocks")

    deactivate_old_zones()
    new_events = []

    active_zones_by_symbol = {}
    for z in get_active_zones():
        active_zones_by_symbol.setdefault(z["symbol"], []).append(z)

    scanned_count = 0
    pivots_found = 0
    entries_found = 0

    for stock in stocks:
        symbol = stock["symbol"]
        try:
            bars = fetch_15m_bars(symbol, days=3)
            if len(bars) < 10:
                continue

            current_price = bars[-1]["close"]
            if current_price < MIN_PRICE or current_price > MAX_PRICE:
                continue

            scanned_count += 1
            pivots = find_pivots(bars)
            if not pivots:
                continue

            fresh_pivots = [p for p in pivots if p["index"] >= len(bars) - PIVOT_RIGHT - 3]

            for p in fresh_pivots:
                created_at = p["time"]
                if zone_exists(symbol, p["type"], created_at):
                    continue
                if zone_overlaps_existing(symbol, p["type"], p["top"], p["bottom"]):
                    print(f"  [dedup] Skipping overlapping {p['type']} zone for {symbol}")
                    continue
                pivots_found += 1
                zone = {
                    "symbol": symbol, "name": stock["name"],
                    "sector": stock.get("sector", ""),
                    "zone_type": p["type"], "zone_top": p["top"],
                    "zone_bottom": p["bottom"], "created_at": created_at,
                    "created_price": p["price"],
                }
                insert_zone(zone)
                tier, msg = classify_zone_event(stock, zone, "zone_created", is_fresh=True)
                new_events.append({
                    "symbol": symbol, "name": stock["name"],
                    "sector": stock.get("sector", ""),
                    "event_type": "zone_created", "zone_type": p["type"],
                    "zone_top": p["top"], "zone_bottom": p["bottom"],
                    "price": current_price, "event_at": started.isoformat(),
                    "tier": tier, "message": msg,
                })

            symbol_zones = active_zones_by_symbol.get(symbol, [])
            entry_fired = False
            for zone in symbol_zones:
                if entry_fired:
                    break
                zt = zone["zone_top"]; zb = zone["zone_bottom"]
                for bar in bars[-3:]:
                    touched = (
                        (bar["low"] <= zt and bar["low"] >= zb) or
                        (bar["high"] >= zb and bar["high"] <= zt) or
                        (bar["low"] <= zb and bar["high"] >= zt)
                    )
                    if touched:
                        update_zone_entry(zone["id"], bar["close"], bar["time"])
                        tier, msg = classify_zone_event(stock, zone, "zone_entered")
                        new_events.append({
                            "symbol": symbol, "name": stock["name"],
                            "sector": stock.get("sector", ""),
                            "event_type": "zone_entered", "zone_type": zone["zone_type"],
                            "zone_top": zt, "zone_bottom": zb,
                            "price": bar["close"], "event_at": bar["time"],
                            "tier": tier, "message": msg,
                        })
                        entries_found += 1
                        entry_fired = True
                        break
        except Exception as e:
            print(f"[{symbol}] scan error: {e}")
            continue

    for evt in new_events:
        insert_zone_event(evt)

    elapsed = (datetime.now(IST) - started).total_seconds()
    print(f"  Scanned: {scanned_count}/{len(stocks)} stocks")
    print(f"  New zones: {pivots_found} | Entries: {entries_found}")
    print(f"  Completed in {elapsed:.1f}s")

    result = {
        "version": VERSION,
        "scanned_at": started.isoformat(),
        "scanned_at_human": started.strftime("%d %b %Y, %I:%M:%S %p IST"),
        "stocks_scanned": scanned_count,
        "new_zones_count": len([e for e in new_events if e["event_type"] == "zone_created"]),
        "entries_count": len([e for e in new_events if e["event_type"] == "zone_entered"]),
        "new_zones": [e for e in new_events if e["event_type"] == "zone_created"],
        "recent_entries": [e for e in new_events if e["event_type"] == "zone_entered"],
        "active_zones_total": len(get_active_zones()),
    }
    cache_set("latest_scan", result)
    return result

# ============================================================
# SCHEDULER REFRESH
# ============================================================
def snapshot_option_chain_dedicated():
    """
    v1.30.1 — Dedicated 15-min option chain snapshot.
    Independent of run_zone_scan() so the pipeline never stalls if the
    zone scanner errors out (Dhan timeout, F&O universe failure, etc.).
    """
    now_ist = datetime.now(IST)
    if now_ist.weekday() >= 5:
        return
    try:
        current_vix = None
        try:
            vix_t = yf.Ticker("^INDIAVIX")
            vix_h = vix_t.history(period="2d")
            if not vix_h.empty:
                current_vix = float(vix_h["Close"].iloc[-1])
        except Exception:
            pass

        for sym in ("NIFTY", "SENSEX", "BANKNIFTY"):
            try:
                oc = fetch_option_chain_levels(sym, vix_value=current_vix)
                if oc and not oc.get("error"):
                    print(f"[Snapshot] {sym} @ {now_ist.strftime('%H:%M:%S')} "
                          f"spot={oc.get('spot')} PCR={oc.get('pcr')}")
                else:
                    err = oc.get("error") if oc else "no_response"
                    print(f"[Snapshot] {sym} skipped: {err}")
            except Exception as e:
                print(f"[Snapshot] {sym} error: {e}")
    except Exception as e:
        print(f"[Snapshot] dedicated job error: {e}")


def scheduled_sentiment_refresh():
    print(f"\n[{datetime.now(IST).strftime('%Y-%m-%d %H:%M:%S IST')}] Scheduled sentiment refresh...")
    for sym in SYMBOLS:
        try:
            result = get_sentiment_score(sym, bypass_cache=True)
            print(f"   [{sym}] Score: {result['score']} ({result['label']})")
        except Exception as e:
            print(f"   [{sym}] error: {e}")

    current_vix = None
    try:
        vix_t = yf.Ticker("^INDIAVIX")
        vix_h = vix_t.history(period="2d")
        if not vix_h.empty:
            current_vix = float(vix_h["Close"].iloc[-1])
    except Exception:
        pass

    for idx in ("NIFTY", "SENSEX"):
        try:
            oc = fetch_option_chain_levels(idx, vix_value=current_vix)
            if oc and not oc.get("error"):
                print(f"   [{idx}] levels snapshotted: S={oc.get('support',{}).get('level')} "
                      f"R={oc.get('resistance',{}).get('level')} PCR={oc.get('pcr')}")
        except Exception as e:
            print(f"   [{idx}] snapshot error: {e}")

    print("Sentiment refresh complete.\n")

# ============================================================
# API ENDPOINTS
# ============================================================
@app.get("/api/sentiment")
def get_all_sentiments():
    return [get_sentiment_score(sym) for sym in SYMBOLS]

@app.get("/api/sentiment/{symbol}")
def get_single_sentiment(symbol: str):
    return get_sentiment_score(symbol.upper())

@app.get("/api/history/{symbol}")
def get_symbol_history(symbol: str, days: int = 7):
    return {"symbol": symbol.upper(), "history": get_history(symbol.upper(), days)}

@app.get("/api/option-chain/{symbol}")
def get_option_chain(symbol: str):
    return fetch_option_chain_levels(symbol.upper())


@app.get("/api/sector-constituents/{sector_name}")
def get_sector_constituents(sector_name: str):
    """Fetch live data for ALL F&O stocks in a specific sector."""
    try:
        from fno_stocks import FNO_STOCKS
        
        sector_stocks = [s for s in FNO_STOCKS if s["sector"].lower() == sector_name.lower()]
        if not sector_stocks:
            return {"error": f"No stocks found for sector {sector_name}"}
            
        symbols = [s["symbol"] for s in sector_stocks]
        
        data = yf.download(
            tickers=" ".join(symbols),
            period="5d",
            interval="1d",
            progress=False,
            group_by="ticker",
            auto_adjust=False,
            threads=True
        )
        
        results = []
        nifty_syms = [c["symbol"] for c in NIFTY50_CONSTITUENTS]
        
        for s in sector_stocks:
            symbol = s["symbol"]
            is_nc = symbol in nifty_syms
            display_symbol = symbol.replace(".NS", "")
            
            try:
                if len(symbols) == 1:
                    ticker_data = data
                else:
                    ticker_data = data[symbol] if symbol in data.columns.get_level_values(0) else None
                    
                if ticker_data is None or ticker_data.empty:
                    results.append({"symbol": display_symbol, "name": s["name"], "is_nc": is_nc, "price": None, "change_pct": None, "atr_pct": None})
                    continue
                    
                closes = ticker_data["Close"].dropna()
                highs = ticker_data["High"].dropna() if "High" in ticker_data else None
                lows = ticker_data["Low"].dropna() if "Low" in ticker_data else None
                
                if len(closes) < 2:
                    results.append({"symbol": display_symbol, "name": s["name"], "is_nc": is_nc, "price": None, "change_pct": None, "atr_pct": None})
                    continue
                    
                current_price = float(closes.iloc[-1])
                prev_close = float(closes.iloc[-2])
                change_pct = round(((current_price - prev_close) / prev_close) * 100, 2)
                
                atr_pct = None
                if highs is not None and lows is not None and len(highs) >= 2:
                    avg_range = ((highs - lows) / closes * 100).mean()
                    atr_pct = round(float(avg_range), 2)
                    
                results.append({
                    "symbol": display_symbol, "name": s["name"], "is_nc": is_nc,
                    "price": current_price, "change_pct": change_pct, "atr_pct": atr_pct
                })
            except Exception:
                results.append({"symbol": display_symbol, "name": s["name"], "is_nc": is_nc, "price": None, "change_pct": None, "atr_pct": None})
                
        results.sort(key=lambda x: x["change_pct"] if x["change_pct"] is not None else -999, reverse=True)
        return {"sector": sector_name, "count": len(results), "stocks": results}
    except Exception as e:
        return {"error": str(e)}

@app.get("/api/constituents/{index}")
def get_constituents(index: str):
    index_upper = index.upper()
    if index_upper not in ("NIFTY", "SENSEX"):
        return {"error": "Index must be NIFTY or SENSEX"}
    return fetch_constituents(index_upper)

@app.get("/api/action-dashboard-split")
def get_action_dashboard_split():
    """v1.24.0: Return dashboard split — Company from live events, Story from event_history."""
    try:
        # COMPANY: from generate_action_events() (tier moves)
        company_events = generate_action_events() or []
        
        # STORY: from event_history (trade calls + conviction + OI surges + shifts)
        # Only fetch today's story events
        today_str = datetime.now(IST).strftime("%Y-%m-%d")
        # Trade calls are excluded — they belong in Trade Drawer only
        story_types = "support_conviction_strong,support_conviction_very_strong,support_conviction_hardened,resistance_conviction_strong,resistance_conviction_very_strong,resistance_conviction_hardened,oi_surge,oi_bias_flip,call_wall_shift,put_wall_shift,vix_surge,vix_drop,support_shift,resistance_shift"
        
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        
        # Build the types filter
        type_list = [t.strip() for t in story_types.split(',')]
        placeholders = ','.join(['?' for _ in type_list])
        
        rows = c.execute(f"""
            SELECT event_at, event_type, level, icon, message, metadata
            FROM event_history
            WHERE date(event_at) = ? AND event_type IN ({placeholders})
            ORDER BY event_at DESC
            LIMIT 20
        """, (today_str, *type_list)).fetchall()
        conn.close()
        
        story_events = []
        for r in rows:
            story_events.append({
                "priority": 1,
                "icon": r["icon"] or "•",
                "type": r["event_type"],
                "level": r["level"] or "IMPORTANT",
                "message": r["message"] or "",
                "suggested_action": None,
                "timestamp": r["event_at"]
            })
        
        return {
            "story": story_events,
            "company": company_events,
            "story_count": len(story_events),
            "company_count": len(company_events),
            "count": len(story_events) + len(company_events),
            "updated": datetime.now(IST).strftime("%d %b %Y, %I:%M %p IST")
        }
    except Exception as e:
        print(f"[Split] Error: {e}")
        return {"error": str(e), "story": [], "company": []}


@app.get("/api/action-dashboard")
def get_action_dashboard():
    try:
        events = generate_action_events()
        return {
            "updated": datetime.now(IST).strftime("%d %b %Y, %I:%M %p IST"),
            "count": len(events),
            "max_events": ACTION_DASHBOARD_MAX_EVENTS,
            "events": events
        }
    except Exception as e:
        print(f"⚠️ Action dashboard error: {e}")
        return {"updated": datetime.now(IST).strftime("%d %b %Y, %I:%M %p IST"),
                "count": 0, "events": [], "error": str(e)[:200]}

@app.get("/api/market-narrative")
def get_market_narrative():
    try:
        return _clean(build_market_narrative("NIFTY"))
    except Exception as e:
        return {"error": str(e)[:200]}

@app.get("/api/range")
def get_expected_range():
    cached = cache_get("range")
    if cached: return cached
    try:
        nifty = yf.Ticker("^NSEI")
        vix = yf.Ticker("^INDIAVIX")
        nifty_data = nifty.history(period="1d")
        vix_data = vix.history(period="1d")
        if nifty_data.empty or vix_data.empty:
            return {"error": "Could not fetch market data."}
        last_close = nifty_data['Close'].iloc[-1]
        current_vix = vix_data['Close'].iloc[-1]
        vix_decimal = current_vix / 100 if current_vix > 1.0 else current_vix
        daily_move = last_close * (vix_decimal / math.sqrt(252))
        result = {
            "last_close": round(last_close, 2),
            "vix": round(current_vix, 2),
            "low": round(last_close - daily_move, 2),
            "high": round(last_close + daily_move, 2),
            "mid": round(last_close, 2)
        }
        cache_set("range", result)
        return result
    except Exception as e:
        return {"error": str(e)}

@app.get("/api/vix-changes")
def get_vix_changes_endpoint():
    """v1.23.0: Return today's VIX timeline, only when value changed."""
    try:
        today_str = datetime.now(IST).strftime("%Y-%m-%d")
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        
        rows = c.execute("""
            SELECT snapshot_at, vix 
            FROM intraday_levels_history 
            WHERE date = ? AND symbol = 'NIFTY' AND vix IS NOT NULL
            ORDER BY snapshot_at ASC
        """, (today_str,)).fetchall()
        conn.close()
        
        if not rows:
            return {"available": False, "reason": "no_data", "changes": []}
        
        changes = []
        prev_vix = None
        for (ts, vix) in rows:
            vix = round(float(vix), 2)
            if prev_vix is None or abs(vix - prev_vix) >= 0.05:
                changes.append({
                    "time": ts,
                    "vix": vix,
                    "delta": round(vix - prev_vix, 2) if prev_vix is not None else None
                })
                prev_vix = vix
        
        return {
            "available": True,
            "current": prev_vix,
            "count": len(changes),
            "changes": changes[-30:]
        }
    except Exception as e:
        print(f"[VIX Changes] Error: {e}")
        return {"available": False, "reason": str(e), "changes": []}


@app.get("/api/crude-impact")
def get_crude_impact():
    """v1.28.0: Crude Oil impact monitor with sector mapping."""
    try:
        import yfinance as yf
        
        # Fetch WTI (primary for Indian traders)
        wti = yf.Ticker("CL=F")
        wti_hist = wti.history(period="1d", interval="5m")
        
        # Fetch Brent (secondary, for context)
        brent = yf.Ticker("BZ=F")
        brent_hist = brent.history(period="1d", interval="5m")
        
        if wti_hist.empty:
            return {"available": False, "reason": "no_data"}
        
        # WTI metrics
        wti_open = float(wti_hist.iloc[0]['Open'])
        wti_latest = float(wti_hist.iloc[-1]['Close'])
        wti_high = float(wti_hist['High'].max())
        wti_low = float(wti_hist['Low'].min())
        wti_change_pct = ((wti_latest - wti_open) / wti_open) * 100
        
        # Brent metrics
        brent_data = None
        if not brent_hist.empty:
            brent_open = float(brent_hist.iloc[0]['Open'])
            brent_latest = float(brent_hist.iloc[-1]['Close'])
            brent_change_pct = ((brent_latest - brent_open) / brent_open) * 100
            brent_data = {
                "price": round(brent_latest, 2),
                "change_pct": round(brent_change_pct, 2),
                "open": round(brent_open, 2)
            }
        
        # Determine direction
        if wti_change_pct > 0.5:
            trend = "rising"
        elif wti_change_pct < -0.5:
            trend = "falling"
        else:
            trend = "flat"
        
        # Alert level
        abs_change = abs(wti_change_pct)
        if abs_change >= 3:
            alert_level = "CRITICAL"
        elif abs_change >= 2:
            alert_level = "HIGH"
        elif abs_change >= 1:
            alert_level = "MEDIUM"
        else:
            alert_level = "LOW"
        
        # Sector mapping (WTI rising = pressure on these)
        crude_impact_map = {
            "rising": {
                "hurts": [
                    {"sector": "Paints", "stocks": ["ASIANPAINT", "BERGEPAINT"], "reason": "Titanium dioxide & solvents from crude"},
                    {"sector": "Aviation", "stocks": ["INDIGO", "SPICEJET"], "reason": "ATF fuel cost"},
                    {"sector": "Tyres", "stocks": ["MRF", "APOLLOTYRE"], "reason": "Carbon black & rubber inputs"},
                    {"sector": "Oil Marketing", "stocks": ["BPCL", "HPCL", "IOC"], "reason": "Margin compression if retail prices held"},
                    {"sector": "Auto", "stocks": ["MARUTI", "TATAMOTORS", "M&M"], "reason": "Fuel cost impacts demand"}
                ],
                "helps": [
                    {"sector": "Upstream Oil", "stocks": ["ONGC", "OIL"], "reason": "Higher crude realizations"},
                    {"sector": "Gas", "stocks": ["GAIL"], "reason": "Higher price realizations"}
                ]
            },
            "falling": {
                "hurts": [
                    {"sector": "Upstream Oil", "stocks": ["ONGC", "OIL"], "reason": "Lower crude realizations"},
                    {"sector": "Gas", "stocks": ["GAIL"], "reason": "Lower price realizations"}
                ],
                "helps": [
                    {"sector": "Paints", "stocks": ["ASIANPAINT", "BERGEPAINT"], "reason": "Lower input costs"},
                    {"sector": "Aviation", "stocks": ["INDIGO", "SPICEJET"], "reason": "Lower ATF"},
                    {"sector": "Tyres", "stocks": ["MRF", "APOLLOTYRE"], "reason": "Lower raw material costs"},
                    {"sector": "Oil Marketing", "stocks": ["BPCL", "HPCL", "IOC"], "reason": "Better margins"},
                    {"sector": "Auto", "stocks": ["MARUTI", "TATAMOTORS", "M&M"], "reason": "Better demand sentiment"}
                ]
            },
            "flat": {"hurts": [], "helps": []}
        }
        
        impact = crude_impact_map.get(trend, {"hurts": [], "helps": []})
        
        # Message
        if trend == "rising":
            msg = f"CRUDE +{wti_change_pct:.2f}% (WTI) → pressure on Paints, Aviation, Tyres. Benefiting: ONGC, OIL, GAIL. Nifty likely range-bound with negative bias."
        elif trend == "falling":
            msg = f"CRUDE {wti_change_pct:.2f}% (WTI) → relief for Paints, Aviation, Tyres. Hurting: ONGC, OIL, GAIL. Nifty likely to get mild support."
        else:
            msg = f"CRUDE +{wti_change_pct:.2f}% (WTI) → flat, no significant sector impact."
        
        return {
            "available": True,
            "wti": {
                "price": round(wti_latest, 2),
                "open": round(wti_open, 2),
                "high": round(wti_high, 2),
                "low": round(wti_low, 2),
                "change_pct": round(wti_change_pct, 2)
            },
            "brent": brent_data,
            "primary_trend": trend,
            "alert_level": alert_level,
            "affected": impact,
            "message": msg,
            "updated": datetime.now(IST).strftime("%d %b %Y, %I:%M %p IST")
        }
    except Exception as e:
        print(f"[Crude Impact] Error: {e}")
        return {"available": False, "error": str(e)}


@app.get("/api/scan/zones-15m")
def get_zone_scan():
    cached = cache_get("latest_scan")
    if cached:
        return cached
    return run_zone_scan()

@app.get("/api/scan/rescan")
def force_zone_rescan():
    return run_zone_scan()

@app.get("/api/scan/active-zones")
def get_active_zones_endpoint():
    zones = get_active_zones()
    return {"count": len(zones), "zones": zones}

@app.get("/api/scan/recent-events")
def get_recent_zone_events(hours: int = 24):
    cutoff = (datetime.now(IST) - timedelta(hours=hours)).isoformat()
    conn = sqlite3.connect(ZONES_DB_PATH)
    c = conn.cursor()
    c.execute("""
        SELECT symbol, name, sector, event_type, zone_type, zone_top, zone_bottom,
               price, event_at, tier, message
        FROM zone_events
        WHERE event_at >= ?
        ORDER BY event_at DESC
        LIMIT 100
    """, (cutoff,))
    rows = c.fetchall()
    conn.close()
    return {
        "count": len(rows),
        "events": [{
            "symbol": r[0], "name": r[1], "sector": r[2], "event_type": r[3],
            "zone_type": r[4], "zone_top": r[5], "zone_bottom": r[6],
            "price": r[7], "event_at": r[8], "tier": r[9], "message": r[10],
        } for r in rows]
    }


@app.get("/api/dinks-history")
def get_dinks_history(hours: int = 24, tier: str = None, limit: int = 200):
    """v2.0 — Returns fires from dinks_history table, newest first."""
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        from datetime import datetime as _dt, timedelta as _td
        now_ist = _dt.now(IST)
        cutoff = (now_ist - _td(hours=hours)).isoformat()

        where = ["fired_at >= ?"]
        params = [cutoff]
        if tier:
            where.append("tier = ?")
            params.append(tier.upper())
        params.append(limit)

        rows = c.execute(f"""
            SELECT id, fired_at, trigger_type, tier, bias,
                   spot, conviction_support, conviction_resistance,
                   pcr, vix, crude_change_pct, footprint_delta,
                   sentence, action_ticket, trigger_payload_json
            FROM dinks_history
            WHERE {' AND '.join(where)}
            ORDER BY fired_at DESC
            LIMIT ?
        """, tuple(params)).fetchall()
        conn.close()

        events = []
        for r in rows:
            events.append({
                "id": r["id"],
                "fired_at": r["fired_at"],
                "trigger_type": r["trigger_type"],
                "tier": r["tier"],
                "bias": r["bias"],
                "spot": r["spot"],
                "conviction_support": r["conviction_support"],
                "conviction_resistance": r["conviction_resistance"],
                "pcr": r["pcr"],
                "vix": r["vix"],
                "crude_change_pct": r["crude_change_pct"],
                "footprint_delta": r["footprint_delta"],
                "sentence": r["sentence"],
                "action_ticket": r["action_ticket"],
                "trigger_payload": json_lib.loads(r["trigger_payload_json"]) if r["trigger_payload_json"] else None,
            })

        return {
            "count": len(events),
            "hours": hours,
            "tier_filter": tier,
            "events": events,
            "generated_at_ist": now_ist.strftime("%Y-%m-%d %H:%M:%S IST"),
        }
    except Exception as e:
        return {"count": 0, "events": [], "error": str(e)[:200]}


@app.get("/api/magnet-traps")
def get_magnet_traps(date: str = None, symbol: str = None, tolerance: float = 0.05):
    """v1.30.2 — O=H trap detection across NIFTY/BANKNIFTY/SENSEX.
    Reads option_chain_history, requires ≥3 snapshots per strike-side."""
    try:
        from magnet_detector import detect_traps
        target_date = date or datetime.now(IST).strftime("%Y-%m-%d")
        symbols = [symbol.upper()] if symbol else ["NIFTY", "BANKNIFTY", "SENSEX"]
        results = []
        for sym in symbols:
            try:
                r = detect_traps(sym, target_date, tolerance_pct=tolerance)
                results.append(r)
            except Exception as e:
                results.append({"symbol": sym, "error": str(e)[:200]})
        return {
            "date": target_date,
            "tolerance_pct": tolerance,
            "count": len(results),
            "results": results,
            "generated_at_ist": datetime.now(IST).strftime("%Y-%m-%d %H:%M:%S IST"),
        }
    except Exception as e:
        return {"error": str(e)[:200], "results": []}


@app.get("/api/dinks")
def get_dinku_analysis():
    """v1.20.0: Reads Dinks's cached analysis."""
    try:
        import os
        import json
        cache_path = os.path.join(os.path.dirname(__file__), 'dinks_cache.json')
        
        if not os.path.exists(cache_path):
            return {"status": "error", "message": "Cache not found. Run dinks_engine.py first."}
            
        with open(cache_path, 'r') as f:
            data = json.load(f)
            
        return {"status": "success", "data": data}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@app.get("/api/pcr-changes")
def get_pcr_changes():
    """v1.30.3: Returns the timeline of PCR shifts (formatted for frontend)"""
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        rows = c.execute("""
            SELECT snapshot_at, pcr 
            FROM intraday_levels_history 
            WHERE symbol='NIFTY' AND pcr IS NOT NULL 
            ORDER BY snapshot_at DESC LIMIT 50
        """).fetchall()
        conn.close()
        
        rows.reverse()
        timeline = []
        prev_pcr = None
        for r in rows:
            curr_pcr = round(r[1], 2)
            change = None
            if prev_pcr is not None:
                change = round(curr_pcr - prev_pcr, 2)
                
            time_str = r[0]
            if "T" in time_str:
                time_str = time_str.split("T")[1][:5]
            elif " " in time_str:
                time_str = time_str.split(" ")[1][:5]
                
            timeline.append({
                "time": time_str,
                "pcr": curr_pcr,
                "change": change
            })
            prev_pcr = curr_pcr
            
        return {"status": "success", "timeline": timeline}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@app.post("/api/update-token")
async def update_dhan_token(request: Request):
    """Updates the Dhan token and writes to .env"""
    try:
        data = await request.json()
        new_token = data.get("token")
        
        if not new_token or len(new_token) < 100:
            return {"status": "error", "message": "Invalid token format"}
            
        env_path = '/home/dinkstrade/pdmp/.env'
        with open(env_path, 'w') as f:
            f.write(f'DHAN_TOKEN="{new_token}"\n')
            
        import dhan_data
        dhan_data.ACCESS_TOKEN = new_token
        dhan_data.DHAN_CLIENT = dhan_data.get_client()
        
        return {"status": "success", "message": "Token updated successfully"}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@app.get("/api/status")
def get_market_status():
    now = datetime.now(IST)
    is_weekday = now.weekday() < 5
    is_market_hours = 9 <= now.hour < 15 or (now.hour == 15 and now.minute <= 30)
    status = "Market Open" if (is_weekday and is_market_hours) else "Market Closed"
    display_text = "Market Open" if status == "Market Open" else "Market Closed — Showing Recap"

    # v1.30.4: Extract token expiry from JWT with full debug
    token_expires_at_iso = None
    try:
        import os, jwt, traceback
        from dotenv import load_dotenv
        load_dotenv('/home/dinkstrade/pdmp/.env', override=True)
        token = os.getenv("DHAN_TOKEN", "")
        if token:
            decoded = jwt.decode(token, options={"verify_signature": False})
            exp = decoded.get("exp")
            if exp:
                token_expires_at_iso = datetime.fromtimestamp(exp, IST).isoformat()
    except Exception as e:
        print(f"[Status] JWT parse error: {type(e).__name__}: {e}")

    return {
        "status": status,
        "display": display_text,
        "updated": now.strftime("%d %b %Y, %I:%M %p IST"),
        "version": VERSION,
        "token_expires_at_iso": token_expires_at_iso
    }

@app.get("/api/scan/status")
def scan_status():
    now = datetime.now(IST)
    is_weekday = now.weekday() < 5
    is_market_hours = 9 <= now.hour < 15 or (now.hour == 15 and now.minute <= 30)
    status = "Market Open" if (is_weekday and is_market_hours) else "Market Closed"
    return {
        "version": VERSION,
        "status": status,
        "updated": now.strftime("%d %b %Y, %I:%M %p IST"),
        "universe_count": len(get_fno_stocks()),
        "active_zones": len(get_active_zones()),
        "price_filter": f"₹{MIN_PRICE} - ₹{MAX_PRICE}",
        "timeframe": "15m",
        "pivot_config": {"left": PIVOT_LEFT, "right": PIVOT_RIGHT, "zone_length_bars": ZONE_LENGTH_BARS}
    }

@app.get("/api/macro-events")
def get_macro_events_endpoint():
    return build_macro_events_response()

@app.delete("/api/macro-events/{event_id}")
def delete_macro_event(event_id: int):
    """Delete a macro event by ID. VM-local admin."""
    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("DELETE FROM macro_events WHERE id = ?", (event_id,))
        deleted = c.rowcount
        conn.commit()
        conn.close()
        if deleted:
            return {"ok": True, "deleted_id": event_id}
        return {"ok": False, "error": "Event not found"}
    except Exception as e:
        return {"ok": False, "error": str(e)[:200]}

@app.post("/api/macro-events")
def post_macro_event(payload: dict):
    # C6: validate time format
    for field in ("event_time_utc", "event_time_ist"):
        v = payload.get(field)
        if v is not None and not _TIME_RE.match(str(v)):
            return {"ok": False, "error": f"{field} must be HH:MM (got {v})"}
    if not payload.get("event_date"):
        return {"ok": False, "error": "event_date is required"}

    try:
        conn = sqlite3.connect(SENTIMENT_DB_PATH)
        c = conn.cursor()
        c.execute("""
            INSERT OR REPLACE INTO macro_events
            (event_date, event_time_utc, event_time_ist, region,
             event_type, title, importance, affects, notes)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            payload.get("event_date"),
            payload.get("event_time_utc"),
            payload.get("event_time_ist"),
            payload.get("region", "IN"),
            payload.get("event_type", "CUSTOM"),
            payload.get("title", "Custom event"),
            payload.get("importance", "MEDIUM"),
            json_lib.dumps(payload.get("affects", [])),
            payload.get("notes")
        ))
        conn.commit()
        conn.close()
        return {"ok": True, "message": "Event saved"}
    except Exception as e:
        return {"ok": False, "error": str(e)[:200]}

@app.get("/api/macro-selftest")
def macro_selftest():
    """v1.5.1 — Simulate a macro event window. Does NOT actually suppress."""
    try:
        fake_event = {
            "id": -1,
            "event_type": "SELFTEST",
            "title": "Synthetic Test Event",
            "importance": "HIGH",
            "phase": "post",
            "minutes_offset": 5
        }
        sample_levels = ["MAJOR", "IMPORTANT", "SIGNAL"]
        downgrade_preview = {lvl: MACRO_DOWNGRADE.get(lvl, lvl) for lvl in sample_levels}
        return {
            "ok": True,
            "message": "Selftest — no actual suppression applied",
            "fake_event": fake_event,
            "downgrade_mapping": downgrade_preview,
            "suppress_window": {
                "pre_min": MACRO_SUPPRESS_PRE_MIN,
                "post_min": MACRO_SUPPRESS_POST_MIN
            },
            "current_real_window": get_macro_context_now(),
            "generated_at_ist": datetime.now(IST).strftime("%Y-%m-%d %H:%M:%S IST")
        }
    except Exception as e:
        return {"ok": False, "error": str(e)[:200]}

@app.get("/api/news/{symbol}")
def get_news_endpoint(symbol: str, hours: int = 24):
    """Recent news for one symbol."""
    sym = symbol.upper()
    items = get_news_for_symbol(sym, hours=hours)
    scores = [i["sentiment"] for i in items if i["sentiment"] is not None]
    avg = round(sum(scores) / len(scores), 2) if scores else 0.0
    return {
        "symbol": sym,
        "hours": hours,
        "count": len(items),
        "avg_sentiment": avg,
        "items": items
    }

@app.get("/api/news/sector/{sector}")
def get_news_sector_endpoint(sector: str, hours: int = 24):
    """Recent news for a sector."""
    return get_news_for_sector(sector, hours=hours)

@app.post("/api/news/refresh")
def manual_news_refresh(limit: int = None):
    """
    Manually trigger a news refresh.
    Optional `limit` query param to cap symbols processed.
    WARNING: can take 1-3 min for full universe.
    """
    try:
        refresh_news_universe(limit=limit)
        return {"ok": True, "message": "News refresh triggered", "limit": limit}
    except Exception as e:
        return {"ok": False, "error": str(e)[:200]}

@app.get("/api/trends/{symbol}")
def get_trends_endpoint(symbol: str):
    """Latest Google Trends data for one symbol."""
    sym = symbol.upper()
    t = get_trend(sym)
    if t is None:
        return {"symbol": sym, "available": False, "message": "No trend data — run refresh"}
    return {"symbol": sym, "available": True, **t}

@app.get("/api/trends")
def get_all_trends_endpoint():
    """All stored trends."""
    rows = get_all_trends()
    return {"count": len(rows), "trends": rows}

@app.post("/api/trends/refresh")
def manual_trends_refresh():
    """
    Manually trigger a trends refresh for all 22 tracked symbols.
    Takes ~60 seconds (batching + delays to avoid rate limit).
    """
    try:
        refresh_trends()
        rows = get_all_trends()
        return {"ok": True, "message": "Trends refreshed", "stored": len(rows)}
    except Exception as e:
        return {"ok": False, "error": str(e)[:200]}

@app.get("/api/oi-neighborhood/{symbol}")
def get_oi_neighborhood_endpoint(symbol: str):
    """ATM-neighborhood OI ladder (ATM-2 to ATM+2) with current + previous."""
    sym = symbol.upper()
    nb = get_oi_neighborhood(sym)
    if not nb.get("available"):
        return nb
    surges = detect_oi_surge(sym)
    nb["surges"] = surges
    return nb

@app.get("/api/oi-surges/{symbol}")
def get_oi_surges_endpoint(symbol: str):
    """Only the surge events for a symbol."""
    sym = symbol.upper()
    surges = detect_oi_surge(sym)
    return {"symbol": sym, "count": len(surges), "surges": surges}

@app.get("/api/flash-alerts")
def get_flash_alerts_endpoint():
    """
    v1.8.3 — Recent flash-worthy events.
    Returns list of alerts that should trigger a visible overlay.
    """
    try:
        flashes = collect_flash_alerts()
        return {
            "count": len(flashes),
            "alerts": flashes,
            "generated_at_ist": datetime.now(IST).strftime("%Y-%m-%d %H:%M:%S IST"),
            "lookback_min": FLASH_LOOKBACK_MIN,
        }
    except Exception as e:
        return {"count": 0, "alerts": [], "error": str(e)[:200]}

@app.get("/api/commentary")
def get_dynamic_commentary_endpoint():
    """v1.9.0 — Dynamic commentary sentence."""
    try:
        return build_dynamic_commentary("NIFTY")
    except Exception as e:
        return {"sentence": "Commentary unavailable.", "error": str(e)[:200]}

@app.get("/api/day-direction")
def get_day_direction_endpoint():
    """v1.9.0 — Sustained directional call."""
    try:
        return build_day_direction("NIFTY")
    except Exception as e:
        return {"available": False, "error": str(e)[:200]}

@app.get("/api/trade-call")
def get_trade_call_endpoint():
    """v1.9.0 — Trade call (5-condition gate)."""
    try:
        res = build_trade_call("NIFTY")
        
        # v1.12.0: Log the dual trades to the A/B test database
        if res.get("available") and res.get("dual_trades"):
            try:
                conn = sqlite3.connect(SENTIMENT_DB_PATH)
                c = conn.cursor()
                now_iso = datetime.now(IST).isoformat()
                
                # Check if we already logged a trade in the last 15 minutes to prevent spam
                cutoff = (datetime.now(IST) - timedelta(minutes=15)).isoformat()
                c.execute("SELECT COUNT(*) FROM trade_call_ab_test WHERE call_time > ?", (cutoff,))
                if c.fetchone()[0] == 0:
                    for t in res["dual_trades"]:
                        c.execute("""
                            INSERT INTO trade_call_ab_test 
                            (call_time, direction, strategy_type, strike, entry_spot, entry_price, target_spot, target_1, target_2, target_3, stop_spot, status)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'OPEN')
                        """, (
                            now_iso, res["direction"], t["strategy"], t["strike"], 
                            res["spot"], t.get("entry_price"), t.get("t1"), t.get("t1"), t.get("t2"), t.get("t3"), t["stop"]
                        ))
                    conn.commit()
                    print(f"[Trade Call] Logged {len(res['dual_trades'])} new A/B trades to DB.")
                conn.close()
            except Exception as db_e:
                print(f"[Trade Call DB Error] {db_e}")

        return res
    except Exception as e:
        return {"available": False, "error": str(e)[:200]}

@app.get("/api/correlation")
def get_correlation_endpoint():
    """v1.10.0 — Rolling correlation matrix across major assets."""
    try:
        return build_correlation_matrix()
    except Exception as e:
        return {"available": False, "error": str(e)[:200]}

@app.get("/api/event-history")
def get_event_history_endpoint(hours: int = 24, types: str = None,
                                exclude_types: str = None, limit: int = 500):
    """
    v1.11.0 — Retrieve event history.
    v1.11.1 — added exclude_types (comma-separated) to suppress noise types.
    Optional filters:
      hours          — lookback window (default 24)
      types          — comma-separated event types to INCLUDE
      exclude_types  — comma-separated event types to EXCLUDE
      limit          — max items (default 500)
    """
    try:
        type_list = None
        if types:
            type_list = [t.strip() for t in types.split(",") if t.strip()]
        exclude_list = None
        if exclude_types:
            exclude_list = [t.strip() for t in exclude_types.split(",") if t.strip()]
        events = get_event_history(hours=hours, event_types=type_list,
                                    limit=limit, exclude_types=exclude_list)
        return {
            "count": len(events),
            "hours": hours,
            "types_filter": type_list,
            "exclude_filter": exclude_list,
            "events": events,
            "generated_at_ist": datetime.now(IST).strftime("%Y-%m-%d %H:%M:%S IST"),
        }
    except Exception as e:
        return {"count": 0, "events": [], "error": str(e)[:200]}

@app.post("/api/event-history/cleanup")
def cleanup_event_history_endpoint():
    """Manually trigger event history cleanup."""
    try:
        deleted = cleanup_event_history()
        return {"ok": True, "deleted": deleted}
    except Exception as e:
        return {"ok": False, "error": str(e)[:200]}

@app.get("/api/version")
def get_version():
    return {
        "version": VERSION,
        "date": datetime.now(IST).strftime("%Y-%m-%d"),
        "features": [
            "UNIFIED PLATFORM v1.10.2",
            "--- v1.10.0 POLISH ---",
            "ATR stops + R:R in trade call",
            "Range-locked commentary variant",
            "Cross-asset correlation matrix",
            "GET /api/correlation",
            "--- v1.8.0 ---",
            "--- v1.8.0 ATM-NEIGHBORHOOD OI ---",
            "ATM-2 to ATM+2 OI ladder tracked per snapshot",
            "Auto-detected strike interval",
            "COI surge detection (>=30% and >=25K abs)",
            "GET /api/oi-neighborhood/{symbol}",
            "GET /api/oi-surges/{symbol}",
            "--- v1.7.0 ---",
            "--- v1.7.0 GOOGLE TRENDS ---",
            "Google Trends fetcher (pytrends)",
            "22 symbols tracked (Top 20 F&O + NIFTY + BANKNIFTY)",
            "6-hour scheduled refresh",
            "GET /api/trends/{symbol}",
            "GET /api/trends",
            "POST /api/trends/refresh",
            "--- v1.6.4 ---",
            "Fixed: sector news now includes url field",
            "--- v1.6.3 ---",
            "--- v1.6.3 FIX ---",
            "Symbol normalization (RELIANCE <-> RELIANCE.NS)",
            "Case-insensitive sector matching",
            "--- v1.6.2 ---",
            "--- v1.6.2 FIX ---",
            "Fixed time cutoff (microseconds mismatch)",
            "--- v1.6.1 ---",
            "--- v1.6.1 NEWS QUALITY ---",
            "Narrowed search query",
            "Post-filter for news-signal keywords",
            "--- v1.6.0 ---",
            "--- v1.6.0 NEWS PIPELINE ---",
            "Google News RSS per F&O symbol",
            "Lexicon sentiment scoring",
            "Sector news rollup",
            "GET /api/news/{symbol}",
            "GET /api/news/sector/{sector}",
            "POST /api/news/refresh",
            "30-min scheduled refresh (market hours)",
            "--- v1.5.1 ---",
            "--- v1.5.1 CLEANUP ---",
            "Dynamic version date",
            "past_today array in /api/macro-events",
            "data_health block (coverage days)",
            "Events sorted by importance",
            "DELETE /api/macro-events/{id}",
            "Time format validation on POST",
            "/api/macro-selftest diagnostic",
            "Coverage warning (<30 days)",
            "RBI seed cleaned (guesses removed)",
            "--- v1.5.0 ---",
            "--- MACRO AWARENESS ---",
            "Macro event calendar",
            "Event suppression -5/+15 min",
            "Alert downgrade + macro_context tagging",
            "Daily macro refresh 00:05 IST",
            "GET+POST /api/macro-events",
            "--- (v1.4.0) ---",
            "OI conviction engine (support & resistance scores, 0-100)",
            "OI bias flip alert (BULLISH <-> BEARISH)",
            "OI surge alert (net writer bias score delta >= 5)",
            "Call wall shift + Put wall shift alerts",
            "Support/Resistance conviction building / fading / break-imminent alerts",
            "VIX persisted intraday + vix_shift alert (>=5%)",
            "Same-day snapshot filter (prevents cross-day false positives)",
            "S/R shift threshold raised 25 -> 50 pts",
            "--- Sentiment Scanner ---",
            "Multi-source AI sentiment (News + Twitter + YouTube)",
            "FII/DII institutional flows",
            "Option chain (Support/Resistance/Max Pain/PCR)",
            "Nifty 50 Top 25 + Sensex 30 constituents",
            "Weight-aware + ATR-based tiered alerting",
            "Live Action Dashboard",
            "Market Narrative panel (sector-driven commentary)",
            "--- Zone Scanner ---",
            "15-minute reversal zone scanner",
            "Pine Script pivot detection logic",
            "F&O stock universe (~190 stocks)",
            "New zone + zone entry detection",
            "Zone overlap dedup (>60%)",
            "Tiered alerts (IMPORTANT / SIGNAL)",
            "Automatic 15-minute scan schedule",
            "--- Shared ---",
            "Adaptive caching (market-hours-aware)",
            "SQLite persistence (2 DBs + intraday_levels_history with OI)",
            "Scheduled snapshots"
        ]
    }

@app.get("/api/scheduler/status")
def scheduler_status():
    jobs = scheduler.get_jobs()
    return {
        "version": VERSION,
        "timezone": str(IST),
        "current_time": datetime.now(IST).strftime("%Y-%m-%d %H:%M:%S IST"),
        "market_hours": is_market_hours_now(),
        "jobs": [
            {"id": j.id, "name": j.name,
             "next_run": j.next_run_time.strftime("%Y-%m-%d %H:%M:%S %Z") if j.next_run_time else None}
            for j in jobs
        ]
    }

# ============================================================
# DHAN WATCHDOG (v1.30.0)
# ============================================================
def dhan_watchdog_thread():
    """Runs in background. Checks if Dhan is alive during market hours."""
    global LAST_SUCCESSFUL_FETCH, LAST_DHAN_CLIENT_RESET
    import dhan_data
    while True:
        time.sleep(DHAN_WATCHDOG_INTERVAL)
        if not is_market_hours_now():
            continue
        
        now = time.time()
        time_since_last_fetch = now - LAST_SUCCESSFUL_FETCH
        
        if time_since_last_fetch > DHAN_TIMEOUT_SEC:
            print(f"[Watchdog] 🚨 Dhan dead for {int(time_since_last_fetch)}s. Resetting client...")
            # Force client reset
            try:
                dhan_data.DHAN_CLIENT = None
                dhan_data.get_client()  # re-init
                LAST_DHAN_CLIENT_RESET = now
                LAST_SUCCESSFUL_FETCH = now  # reset to avoid spam
                print("[Watchdog] ✅ Dhan client reset")
            except Exception as e:
                print(f"[Watchdog] ❌ Reset failed: {e}")

# Start the watchdog thread
threading.Thread(target=dhan_watchdog_thread, daemon=True).start()

# ============================================================
# SCHEDULER SETUP
# ============================================================
scheduler = BackgroundScheduler(timezone=IST)

scheduler.add_job(refresh_macro_events_daily,
    trigger=CronTrigger(hour=0, minute=5, timezone=IST),
    id='macro_refresh_0005', name='Macro events refresh 00:05',
    replace_existing=True)

# v1.6.0: news refresh every 30 min (market hours only: 9:00-16:00 IST)
for hour in range(9, 16):
    for minute in [0, 30]:
        scheduler.add_job(refresh_news_universe,
            trigger=CronTrigger(day_of_week="mon-fri", hour=hour, minute=minute, timezone=IST),
            id=f"news_{hour:02d}{minute:02d}",
            name=f"News refresh {hour:02d}:{minute:02d}",
            replace_existing=True, misfire_grace_time=180)

# v1.7.0: trends refresh 4x/day (00:00, 06:00, 12:00, 18:00 IST)
for h in [0, 6, 12, 18]:
    scheduler.add_job(refresh_trends,
        trigger=CronTrigger(hour=h, minute=15, timezone=IST),
        id=f"trends_{h:02d}15",
        name=f"Trends refresh {h:02d}:15",
        replace_existing=True, misfire_grace_time=600)

# v1.30.1 — dedicated option-chain snapshots every 15 min (independent of zone scan)
for hour in range(9, 16):
    for minute in [0, 15, 30, 45]:
        if hour == 9 and minute < 30: continue
        if hour == 15 and minute > 30: continue
        try:
            scheduler.add_job(snapshot_option_chain_dedicated,
                trigger=CronTrigger(day_of_week="mon-fri", hour=hour, minute=minute, second=15, timezone=IST),
                id=f"snapshot_{hour:02d}{minute:02d}",
                name=f"Option chain snapshot {hour:02d}:{minute:02d}",
                replace_existing=True, misfire_grace_time=120)
        except Exception:
            pass

scheduler.add_job(scheduled_sentiment_refresh,
    trigger=CronTrigger(day_of_week='mon-fri', hour=9, minute=0, timezone=IST),
    id='sentiment_9am', name='Sentiment 9:00 AM', replace_existing=True)
scheduler.add_job(scheduled_sentiment_refresh,
    trigger=CronTrigger(day_of_week='mon-fri', hour=12, minute=30, timezone=IST),
    id='sentiment_1230pm', name='Sentiment 12:30 PM', replace_existing=True)
scheduler.add_job(scheduled_sentiment_refresh,
    trigger=CronTrigger(day_of_week='mon-fri', hour=15, minute=30, timezone=IST),
    id='sentiment_330pm', name='Sentiment 3:30 PM', replace_existing=True)

for hour in range(9, 16):
    for minute in [0, 15, 30, 45]:
        if hour == 9 and minute < 30: continue
        if hour == 15 and minute > 30: continue
        try:
            scheduler.add_job(run_zone_scan,
                trigger=CronTrigger(day_of_week="mon-fri", hour=hour, minute=minute, second=2, timezone=IST),
                id=f"zone_{hour:02d}{minute:02d}",
                name=f"Zone scan {hour:02d}:{minute:02d}",
                replace_existing=True, misfire_grace_time=120)
        except Exception:
            pass

scheduler.add_job(run_zone_scan,
    trigger=CronTrigger(day_of_week="mon-fri", hour=16, minute=30, second=2, timezone=IST),
    id="zone_1630_final", name="Final zone scan 16:30",
    replace_existing=True, misfire_grace_time=600)

scheduler.start()

print(f"\n🚀 PDMP Unified Platform {VERSION}")
print(f"   Sentiment: 3 daily snapshots (9:00 / 12:30 / 15:30 IST)")
print(f"   Zone Scanner: every 15 min + final 16:30 IST")
print(f"   OI conviction engine: enabled")
print(f"   OI alerts: bias flip, surge, wall shifts")
print(f"   VIX persistence + shift alerts: enabled")
print(f"   S/R shift threshold: {SUPPORT_RESISTANCE_SHIFT_MIN} pts")
print(f"   Same-day snapshot filter: enabled")
print(f"   News pipeline: 30-min refresh, Google News RSS")
print(f"   Google Trends: 22 symbols, 6-hour refresh")
print(f"   ATM-neighborhood OI: 5-strike ladder tracked")
print(f"   Flash alerts: high-magnitude OI events")
print(f"   Narrative engine: dynamic commentary + trade calls")
print(f"   ATR stops + R:R: enabled")
print(f"   Correlation matrix: 6 assets, 30d rolling")
print(f"   Event history: 7-day retention")
print(f"   API: http://0.0.0.0:8000\n")

# ============================================================
# BACKFILL ZONES
# ============================================================
def delayed_backfill():
    time.sleep(3)
    try:
        print("Skipping initial zone backfill (disabled for local dev)...")
        # run_zone_scan()
        print("Backfill skipped.\n")
    except Exception as e:
        print(f"Zone backfill error: {e}")

threading.Thread(target=delayed_backfill, daemon=True).start()

# ============================================================
# ENTRY POINT
# ============================================================
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

@app.get("/api/zone-priority")
def get_zone_priority_endpoint(hours: int = 24, min_score: int = 0):
    """v1.16.0: Return priority-scored zones from the last N hours.
    Filters by min_score (default 0 to show all scored zones)."""
    try:
        conn = sqlite3.connect(ZONE_DB_PATH)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        cutoff = (datetime.now(IST) - timedelta(hours=hours)).isoformat()
        rows = c.execute("""
            SELECT id, symbol, zone_type, entry_spot, stop_spot, target_spot,
                   status, created_at, closed_at, priority_score, priority_class
            FROM zone_accuracy
            WHERE created_at > ? AND priority_score IS NOT NULL AND priority_score >= ?
            ORDER BY priority_score DESC, created_at DESC
            LIMIT 100
        """, (cutoff, min_score)).fetchall()
        result = [dict(r) for r in rows]
        conn.close()
        return {"count": len(result), "hours": hours, "min_score": min_score, "zones": result}
    except Exception as e:
        return {"error": str(e)}
