"""
avoid_rules.py -- [2026-10-12] The user: the "DO NOT TRADE" list (reports/entry_knowledge.html) as rules, each with an
on/off switch and adjustable numbers (config.json -> "avoid_rules"). All OFF to start; they will be tested one by one.
Called after entry_v2 says BUY. check() always returns BOTH:
  hits    every rule that WOULD block now (computed even when the rule is off -> logged in the decision metrics,
          so each rule can be judged on live data before it is switched on)
  blocked only the hits of rules that are ON -> the buy is stopped
Rules (key: what it blocks -- default numbers):
  min_atr_pct          calm stock: daily ATR % < min (8.0)                                         [list A2]
  max_gap_pct          gap over the previous close > max % (10.0)                                  [A10]
  no_buy_before        before this time ("09:45")                                                  [A8]
  no_buy_after         after this time ("14:30")                                                   [A7]
  max_vwap_pct         price more than max % above VWAP (2.0)                                      [A1]
  max_above_open_pct   price more than max % above the open, NO breakout exception (3.0)           [A5]
  breakout_exception   the v2 buy passed only through the breakout exception (over the open limit) [A5/A15]
  heavy_volume         last-15-min volume > max_vol15_x times normal (3.0)                         [A9]
  recent_climax        a bar with >= vol_x times normal volume in the last `minutes` (10.0, 30)    [A9]
  net_selling_drop     down >= drop_pct over `minutes` with buy share < max_buy_share (1.0, 15, 0.5) [A6]
  lower_low_by_1030    from 10:30: the 10:00-10:30 low broke under the 9:30-10:00 low               [A11]
  choppy_many_vs       already >= max_vs Vs today (>= drop_pct drop, 3 bars each side) (3, 1.0)    [A13]
  flat_bars_at_low     >= flat_bars flat bars WITH trades in the last `lookback` bars while within
                       near_low_pct of the 30-bar low (2, 5, 1.0)                                  [A14]
  sec_avoid            an SEC filing tagged "avoid" for this stock today or `days` back (1) -- LIVE only [A16]
Never raises: any error = no block (logged once).
"""
import json
import logging
from datetime import timedelta
from pathlib import Path

log = logging.getLogger("trade_bot.avoid_rules")
BASE = Path(__file__).resolve().parent

DEFAULTS = {
    "min_atr_pct": {"enabled": False, "min": 8.0},
    "max_gap_pct": {"enabled": False, "max": 10.0},
    "no_buy_before": {"enabled": False, "time": "09:45"},
    "no_buy_after": {"enabled": False, "time": "14:30"},
    "max_vwap_pct": {"enabled": False, "max": 2.0},
    "max_above_open_pct": {"enabled": False, "max": 3.0},
    "breakout_exception": {"enabled": False},
    "heavy_volume": {"enabled": False, "max_vol15_x": 3.0},
    "recent_climax": {"enabled": False, "vol_x": 10.0, "minutes": 30},
    "net_selling_drop": {"enabled": False, "drop_pct": 1.0, "minutes": 15, "max_buy_share": 0.5},
    "lower_low_by_1030": {"enabled": False},
    "choppy_many_vs": {"enabled": False, "max_vs": 3, "drop_pct": 1.0},
    "flat_bars_at_low": {"enabled": False, "flat_bars": 2, "lookback": 5, "near_low_pct": 1.0},
    "sec_avoid": {"enabled": False, "days": 1},
}
_warned = set()


def _hm(s):
    h, m = s.split(":")
    return (int(h) - 9) * 60 + int(m) - 30


def _sec_avoid(symbol, day, days):
    hits = []
    for k in range(days + 1):
        p = BASE / "data" / "events" / f"{(day - timedelta(days=k)).isoformat()}.jsonl"
        if not p.exists():
            continue
        for line in open(p):
            try:
                e = json.loads(line)
            except Exception:
                continue
            if symbol in (e.get("tickers") or []) and e.get("verdict") == "avoid":
                hits.append((e.get("tags") or [[e.get("form")]])[0][0])
    return hits


def check(symbol, bars, ref, metrics, minute, cfg=None, v2cfg=None, day=None, live=False):
    """bars: today's 1-min bars, the last one forming; ref: reference.load(); metrics: entry_v2 metrics;
    minute: minutes since 9:30 now. Returns (blocked, hits) -- lists of 'rule: reason' strings."""
    c = {k: {**v, **((cfg or {}).get(k) or {})} for k, v in DEFAULTS.items()}
    hits = []
    try:
        done = bars[:-1]
        price = metrics.get("price") or (bars[-1]["c"] if bars else None)
        ref = ref or {}
        pc, atr = ref.get("prev_close"), ref.get("atr14")
        if pc and atr:
            atrp = atr / pc * 100
            if atrp < c["min_atr_pct"]["min"]:
                hits.append(("min_atr_pct", f"calm stock: daily ATR {atrp:.1f}% < {c['min_atr_pct']['min']}%"))
        if pc and bars:
            gap = (bars[0]["o"] / pc - 1) * 100
            if gap > c["max_gap_pct"]["max"]:
                hits.append(("max_gap_pct", f"gap {gap:+.1f}% > {c['max_gap_pct']['max']}%"))
        if minute < _hm(c["no_buy_before"]["time"]):
            hits.append(("no_buy_before", f"before {c['no_buy_before']['time']}"))
        if minute >= _hm(c["no_buy_after"]["time"]):
            hits.append(("no_buy_after", f"after {c['no_buy_after']['time']}"))
        vw = metrics.get("vwap_pct")
        if vw is not None and vw > c["max_vwap_pct"]["max"]:
            hits.append(("max_vwap_pct", f"{vw:+.2f}% over VWAP > {c['max_vwap_pct']['max']}%"))
        ext = metrics.get("ext_open_pct")
        if ext is not None and ext > c["max_above_open_pct"]["max"]:
            hits.append(("max_above_open_pct", f"{ext:+.2f}% over the open > {c['max_above_open_pct']['max']}% (no breakout exception)"))
        v2max = (v2cfg or {}).get("max_above_open_pct", 3.0)
        if metrics.get("breakout") and ext is not None and ext > v2max:
            hits.append(("breakout_exception", f"bought only through the breakout exception ({ext:+.2f}% over the open)"))
        vx = metrics.get("vol15_x")
        if vx is not None and vx > c["heavy_volume"]["max_vol15_x"]:
            hits.append(("heavy_volume", f"last-15-min volume {vx:.1f}x normal > {c['heavy_volume']['max_vol15_x']}x"))
        vpm = ref.get("vol_per_min")
        if vpm and done:
            n = int(c["recent_climax"]["minutes"])
            for i, b in enumerate(done[-n:]):
                m = minute - min(n, len(done)) + i
                if 0 <= m < len(vpm) and vpm[m] and b["v"] / vpm[m] >= c["recent_climax"]["vol_x"]:
                    hits.append(("recent_climax", f"a {b['v'] / vpm[m]:.0f}x-volume bar in the last {n} min")); break
        nm = int(c["net_selling_drop"]["minutes"])
        if len(done) > nm and price:
            chg = (price / done[-nm - 1]["c"] - 1) * 100
            bs = metrics.get("buy_share15")
            if chg <= -c["net_selling_drop"]["drop_pct"] and bs is not None and bs < c["net_selling_drop"]["max_buy_share"]:
                hits.append(("net_selling_drop", f"down {chg:.1f}% in {nm} min on net selling (buy share {bs:.2f})"))
        if minute >= 60 and len(done) >= 60:
            lo1 = min(b["l"] for b in done[:30]); lo2 = min(b["l"] for b in done[30:60])
            if lo2 < lo1:
                hits.append(("lower_low_by_1030", "the 10:00-10:30 low broke the 9:30-10:00 low"))
        H = [b["h"] for b in done]; L = [b["l"] for b in done]
        cv, dp = 0, c["choppy_many_vs"]["drop_pct"]
        for j in range(15, len(done) - 3):
            lo = L[j]
            if lo <= min(L[j - 3:j + 4]) and (j == 0 or L[j - 1] != lo) and max(H[max(0, j - 30):j]) / lo - 1 >= dp / 100:
                cv += 1
        if cv >= c["choppy_many_vs"]["max_vs"]:
            hits.append(("choppy_many_vs", f"{cv} Vs already today (>= {c['choppy_many_vs']['max_vs']})"))
        fb = c["flat_bars_at_low"]; lb = int(fb["lookback"])
        if len(done) >= 30 and price:
            flat = sum(1 for b in done[-lb:] if b["h"] - b["l"] < 0.005 and b["v"] > 0)
            low30 = min(L[-30:])
            if flat >= fb["flat_bars"] and price <= low30 * (1 + fb["near_low_pct"] / 100):
                hits.append(("flat_bars_at_low", f"{flat} flat bars with trades near the 30-min low"))
        if live and day is not None:
            s = _sec_avoid(symbol, day, int(c["sec_avoid"]["days"]))
            if s:
                hits.append(("sec_avoid", f"SEC filing tagged avoid: {', '.join(sorted(set(s)))}"))
    except Exception as e:
        if symbol not in _warned:
            _warned.add(symbol); log.warning(f"[AVOID] {symbol}: {e}")
    blocked = [f"avoid {k}: {r}" for k, r in hits if c[k].get("enabled")]
    return blocked, [f"{k}: {r}" for k, r in hits]
