"""
Regime classifier — port fedele V15 _determine_regime_multitf.

Extracted from V15 monolith into a pure function so V16 can call
it from the TechSnapshot builder without dragging the router state.

Output regimes:
  - TRENDING       : strong, TF allowed on pullbacks
  - TRENDING_SOFT  : moderate, MR allowed (TF skipped)
  - BREAKOUT       : volatility spike, SKIP both Brains
  - RANGING        : neither, MR-on-extremes only

The caller passes the relevant tech fields explicitly (no dict),
keeping this function side-effect-free and unit-testable.
"""

from __future__ import annotations


def determine_regime(
    rsi_h1: float,
    market_structure: str,
    trend_maturity: int,
    atr_ratio: float,
    vol_spike: bool,
    h1_struct_bull: bool,
    h1_struct_bear: bool,
) -> tuple[str, str, list[str]]:
    """
    Returns (regime, reason, near_trending_diagnostics).

    near_trending_diagnostics: list of human-readable strings describing
    "why this is RANGING but close to TRENDING" — useful for log analytics
    during calibration.
    """
    # 1. STRONG TRENDING: H1 RSI extreme + expansive structure + maturity
    if rsi_h1 < 30 and market_structure == "BEARISH_EXPANSION" and trend_maturity >= 3:
        return "TRENDING", "H1 strong bearish (RSI<30+exp+mat>=3)", []
    if rsi_h1 > 70 and market_structure == "BULLISH_EXPANSION" and trend_maturity >= 3:
        return "TRENDING", "H1 strong bullish (RSI>70+exp+mat>=3)", []

    # 2. BREAKOUT: volatility spike
    if atr_ratio > 2.0 and vol_spike:
        return "BREAKOUT", "Volatility breakout", []

    # 3. ATR + maturity
    if atr_ratio > 1.3 and trend_maturity >= 3:
        return "TRENDING", "ATR+maturity confirm (ATR>1.3)", []
    if atr_ratio > 1.1 and trend_maturity >= 3:
        return "TRENDING_SOFT", "ATR moderate (1.1-1.3) - routing to MR", []

    # 4. Structural HH+HL / LH+LL with maturity
    if trend_maturity >= 3:
        if h1_struct_bull and market_structure == "BULLISH_EXPANSION" and rsi_h1 > 50:
            return "TRENDING", "Struct bull: HH+HL confirmed H1", []
        if h1_struct_bear and market_structure == "BEARISH_EXPANSION" and rsi_h1 < 50:
            return "TRENDING", "Struct bear: LH+LL confirmed H1", []

    # 5. RANGING + diagnostic of "near trending"
    near: list[str] = []
    if rsi_h1 < 40 and market_structure == "BEARISH_EXPANSION":
        near.append(f"bearish: RSI_H1={rsi_h1:.0f}<40+EXP mat={trend_maturity}")
    if rsi_h1 > 60 and market_structure == "BULLISH_EXPANSION":
        near.append(f"bullish: RSI_H1={rsi_h1:.0f}>60+EXP mat={trend_maturity}")
    if atr_ratio > 1.0 and trend_maturity >= 2:
        near.append(f"ATR={atr_ratio:.2f} mat={trend_maturity}")
    if (h1_struct_bull or h1_struct_bear) and trend_maturity >= 2:
        near.append(
            f"struct: bull={h1_struct_bull} bear={h1_struct_bear} mat={trend_maturity}"
        )

    return "RANGING", "Multi-TF neutral", near
