# app/src/trading/market_analysis/models.py

from __future__ import annotations

from dataclasses import dataclass
from enum import StrEnum

from src.core.types import JsonDict


class MarketState(StrEnum):
    TREND_UP = "TREND_UP"
    TREND_DOWN = "TREND_DOWN"
    RANGE = "RANGE"
    HIGH_VOLATILITY = "HIGH_VOLATILITY"
    LOW_VOLATILITY = "LOW_VOLATILITY"
    UNKNOWN = "UNKNOWN"


class MarketStructure(StrEnum):
    HH_HL = "HH_HL"
    LH_LL = "LH_LL"
    MIXED = "MIXED"
    UNKNOWN = "UNKNOWN"


class TrendDirection(StrEnum):
    UP = "UP"
    DOWN = "DOWN"
    FLAT = "FLAT"
    UNKNOWN = "UNKNOWN"


class MomentumState(StrEnum):
    NONE = "NONE"
    MOMENTUM_UP = "MOMENTUM_UP"
    MOMENTUM_DOWN = "MOMENTUM_DOWN"
    BREAKOUT_UP = "BREAKOUT_UP"
    BREAKOUT_DOWN = "BREAKOUT_DOWN"
    EXHAUSTED = "EXHAUSTED"
    UNKNOWN = "UNKNOWN"


class VolatilityState(StrEnum):
    LOW = "LOW"
    NORMAL = "NORMAL"
    HIGH = "HIGH"
    UNKNOWN = "UNKNOWN"


class TrendStrength(StrEnum):
    WEAK = "WEAK"
    NORMAL = "NORMAL"
    STRONG = "STRONG"
    UNKNOWN = "UNKNOWN"


class MarketPhase(StrEnum):
    IMPULSE = "IMPULSE"
    PULLBACK = "PULLBACK"
    RANGE = "RANGE"
    SQUEEZE = "SQUEEZE"
    UNKNOWN = "UNKNOWN"


class TrendQuality(StrEnum):
    CLEAN = "CLEAN"
    NORMAL = "NORMAL"
    NOISY = "NOISY"
    UNKNOWN = "UNKNOWN"


class EmaDistanceState(StrEnum):
    COMPRESSED = "COMPRESSED"
    HEALTHY = "HEALTHY"
    EXTENDED = "EXTENDED"
    OVEREXTENDED = "OVEREXTENDED"
    UNKNOWN = "UNKNOWN"


class EntryTimingState(StrEnum):
    EARLY = "EARLY"
    NORMAL = "NORMAL"
    LATE = "LATE"
    CHASING = "CHASING"
    UNKNOWN = "UNKNOWN"


@dataclass(slots=True)
class HtfContext:
    # Старший таймфрейм.
    interval: str | None = None

    # Состояние старшего рынка.
    market_state: MarketState | None = None
    trend: TrendDirection | None = None
    trend_strength: TrendStrength | None = None
    trend_quality: TrendQuality | None = None
    market_phase: MarketPhase | None = None

    # Волатильность старшего таймфрейма.
    volatility: VolatilityState | None = None
    atr_percent: float | None = None
    atr_percent_baseline: float | None = None
    volatility_ratio: float | None = None

    # Подтверждение локального направления старшим ТФ.
    alignment: str | None = None
    confirmation_score: float | None = None
    reason: str | None = None


@dataclass(slots=True)
class MarketAnalysisResult:
    # Основное
    symbol: str
    interval: str
    candles_count: int
    reason: str
    is_trade_allowed: bool
    payload: JsonDict

    # Основное состояние рынка
    state: MarketState
    trend: TrendDirection
    volatility: VolatilityState
    trend_strength: TrendStrength
    trend_quality: TrendQuality
    market_phase: MarketPhase
    market_structure: MarketStructure
    market_structure_reason: str

    # Базовые индикаторы
    close_price: float | None
    ema_fast: float | None
    ema_slow: float | None
    atr: float | None
    atr_percent: float | None
    rsi: float | None

    # Метрики тренда
    trend_gap_percent: float | None
    trend_consistency: float | None
    trend_efficiency: float | None
    trend_quality_score: float | None
    ema_distance_atr_ratio: float | None
    ema_fast_slope_percent: float | None
    ema_slow_slope_percent: float | None

    # EMA distance / entry timing
    ema_distance_state: EmaDistanceState
    entry_timing_state: EntryTimingState
    entry_timing_reason: str | None

    # Фаза рынка
    phase_direction: TrendDirection
    phase_change_percent: float | None
    phase_direction_consistency: float | None
    phase_reason: str | None

    # Текущая свеча / интервал
    current_interval_change_percent: float | None
    current_interval_direction: TrendDirection
    current_interval_label: str

    # Momentum / Breakout
    momentum_state: MomentumState
    momentum_direction: TrendDirection
    momentum_change_percent: float | None
    momentum_strength: float | None
    breakout_level: float | None
    breakout_distance_percent: float | None
    breakout_reason: str | None

    # Старший таймфрейм.
    # Новый сгруппированный объект. Пока можно использовать параллельно
    # со старыми flat-полями ниже, чтобы не ломать result.py/snapshot.py сразу.
    htf: HtfContext | None = None

    # Старые flat HTF-поля оставлены для совместимости.
    # Позже их можно удалить после перевода result.py/snapshot.py/formatter.py на htf.
    htf_interval: str | None = None
    htf_atr_percent: float | None = None
    htf_atr_percent_baseline: float | None = None
    htf_volatility_ratio: float | None = None
    htf_volatility: VolatilityState | None = None

    htf_market_state: MarketState | None = None
    htf_trend: TrendDirection | None = None
    htf_trend_strength: TrendStrength | None = None
    htf_trend_quality: TrendQuality | None = None
    htf_market_phase: MarketPhase | None = None
    htf_alignment: str | None = None
    htf_confirmation_score: float | None = None
    htf_reason: str | None = None

    # Общая оценка рынка 0..100.
    market_score: int | None = None
    market_score_label: str | None = None

    # Направленные оценки входа 0..100.
    market_long_score: int | None = None
    market_short_score: int | None = None