# holiday_guard.py — v2026-11-11
# Blocks trading engines when raw_vault.db has no snapshot in last 60 min.
import sqlite3
from datetime import datetime
from zoneinfo import ZoneInfo

IST = ZoneInfo('Asia/Kolkata')
VAULT_DB = '/home/dinkstrade/pdmp/raw_vault.db'
SENTIMENT_DB = '/home/dinkstrade/pdmp/sentiment_history.db'
THRESHOLD_MIN = 60


def is_market_live(caller='unknown'):
    """
    Returns (bool, reason_str).
    True if vault has a snapshot within last THRESHOLD_MIN minutes.
    False otherwise. Writes an INFO row to system_health_log on False.
    """
    try:
        vconn = sqlite3.connect(VAULT_DB, timeout=5)
        row = vconn.execute("SELECT MAX(snapshot_at) FROM vault_option_chain").fetchone()
        vconn.close()

        if not row or not row[0]:
            return _block(caller, "vault empty")

        ts = row[0]
        for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"):
            try:
                last_dt = datetime.strptime(ts[:19], "%Y-%m-%d %H:%M:%S")
                break
            except ValueError:
                continue
        else:
            return _block(caller, f"unparseable timestamp: {ts}")

        last_dt = last_dt.replace(tzinfo=IST)
        age_min = (datetime.now(IST) - last_dt).total_seconds() / 60.0

        if age_min >= THRESHOLD_MIN:
            return _block(caller, f"vault stale {age_min:.1f} min")
        return (True, f"vault fresh {age_min:.1f} min")
    except Exception as e:
        return _block(caller, f"vault check error: {e}")


def _block(caller, reason):
    try:
        sconn = sqlite3.connect(SENTIMENT_DB, timeout=5)
        sconn.execute(
            "INSERT INTO system_health_log (check_time, status, message) VALUES (?, 'INFO', ?)",
            (datetime.now(IST).isoformat(),
             f"Holiday guard: {reason}, skipping {caller}")
        )
        sconn.commit()
        sconn.close()
    except Exception:
        pass
    return (False, reason)
