"""
trigger_eval_collect.py — TRIGGER 스냅샷 수집 vs 필터 적용 분리
================================================================
- 필터 OFF: 실매 주문은 막지 않음
- 수집 ON: TRIGGER 시점 호가·프로그램 스냅 + 판정 결과를 DB에 저장 (백테·파람서치용)
"""
from __future__ import annotations

from typing import Any, Dict

from kis_trader.utils.env import get_env_bool, get_env_from_db


def _strategy_prefix_orderbook(strategy: str) -> str:
    s = (strategy or "").strip().upper()
    if s in ("BREAKOUT", "BO"):
        return "BREAKOUT"
    if s in ("MOMENTUM", "MOM"):
        return "MOMENTUM"
    if s in ("TAIL", "SHORT", "TAIL_CATCH"):
        return "TAIL"
    return s or "ORDERBOOK"


def _strategy_prefix_program(strategy: str) -> str:
    s = (strategy or "").strip().upper()
    if s in ("BREAKOUT", "BO"):
        return "BREAKOUT"
    if s in ("MOMENTUM", "MOM"):
        return "MOMENTUM"
    if s in ("TAIL", "SHORT", "TAIL_CATCH"):
        return "TAIL"
    return s or "PROGRAM"


def trigger_eval_save_master_enabled() -> bool:
    """TriggerEvalRecorder 마스터 스위치."""
    return get_env_bool("WS_TRIGGER_EVAL_SAVE_ENABLED", True)


def orderbook_collect_enabled(params: Dict[str, Any], strategy: str) -> bool:
    """TRIGGER 호가 스냅 DB 수집 여부 (필터 ON/OFF 와 무관)."""
    if params.get("_skip_trigger_eval_persist"):
        return False
    ov_all = params.get("_trigger_eval_collect_enabled")
    if ov_all is not None and not bool(ov_all):
        return False
    if not trigger_eval_save_master_enabled():
        return False
    ov = params.get("_orderbook_collect_enabled")
    if ov is not None:
        return bool(ov)
    pfx = _strategy_prefix_orderbook(strategy)
    sk = f"{pfx}_ORDERBOOK_COLLECT_ENABLED"
    if str(get_env_from_db(sk, "")).strip():
        return get_env_bool(sk, True)
    return get_env_bool("WS_ORDERBOOK_COLLECT_ENABLED", True)


def program_collect_enabled(params: Dict[str, Any], strategy: str) -> bool:
    """TRIGGER 프로그램 스냅 DB 수집 여부 (필터 ON/OFF 와 무관)."""
    if params.get("_skip_trigger_eval_persist"):
        return False
    ov_all = params.get("_trigger_eval_collect_enabled")
    if ov_all is not None and not bool(ov_all):
        return False
    if not trigger_eval_save_master_enabled():
        return False
    ov = params.get("_program_collect_enabled")
    if ov is not None:
        return bool(ov)
    pfx = _strategy_prefix_program(strategy)
    sk = f"{pfx}_PROGRAM_COLLECT_ENABLED"
    if str(get_env_from_db(sk, "")).strip():
        return get_env_bool(sk, True)
    return get_env_bool("WS_PROGRAM_COLLECT_ENABLED", True)
