# app/src/trading/execution/payloads.py

from __future__ import annotations

from src.core.types import JsonDict
from src.trading.auto.state import AutoTradeState


def build_market_payload(state: AutoTradeState) -> JsonDict:
    return {
        "market_score": state.market_score,
        "market_score_label": state.market_score_label,
        "market_long_score": state.market_long_score,
        "market_short_score": state.market_short_score,
        "market_state": state.market_state,
        "market_trend": state.market_trend,
        "market_volatility": state.market_volatility,
        "market_trend_strength": state.market_trend_strength,
        "market_trend_quality": state.market_trend_quality,
        "market_phase": state.market_phase,
        "market_phase_direction": state.market_phase_direction,
        "market_structure": state.market_structure,
        "market_structure_reason": state.market_structure_reason,
        "last_closed_candle_change_percent": state.last_closed_candle_change_percent,
        "last_closed_candle_direction": state.last_closed_candle_direction,
        "current_interval_change_percent": state.current_interval_change_percent,
        "current_interval_direction": state.current_interval_direction,
        "current_interval_label": state.current_interval_label,
    }


def build_momentum_payload(state: AutoTradeState) -> JsonDict:
    return {
        "momentum_state": state.momentum_state,
        "momentum_direction": state.momentum_direction,
        "momentum_strength": state.momentum_strength,
        "momentum_change_percent": state.momentum_change_percent,
        "breakout_level": state.breakout_level,
        "breakout_distance_percent": state.breakout_distance_percent,
        "breakout_reason": state.breakout_reason,
    }


def build_htf_payload(state: AutoTradeState) -> JsonDict:
    return {
        "htf_interval": state.htf_interval,
        "htf_atr_percent": state.htf_atr_percent,
        "htf_atr_percent_baseline": state.htf_atr_percent_baseline,
        "htf_volatility_ratio": state.htf_volatility_ratio,
        "htf_volatility": state.htf_volatility,
        "htf_market_state": state.htf_market_state,
        "htf_trend": state.htf_trend,
        "htf_trend_strength": state.htf_trend_strength,
        "htf_trend_quality": state.htf_trend_quality,
        "htf_market_phase": state.htf_market_phase,
        "htf_alignment": state.htf_alignment,
        "htf_confirmation_score": state.htf_confirmation_score,
        "htf_reason": state.htf_reason,
    }


def build_market_runtime_payload(state: AutoTradeState) -> JsonDict:
    return {
        "market_runtime_degraded": state.market_runtime_degraded,
        "runtime_expired_reason": state.runtime_expired_reason,
        "runtime_expired_message": state.runtime_expired_message,
        "market_is_open": state.market_is_open,
        "market_status": state.market_status,
        "market_status_message": state.market_status_message,
    }


def build_market_context_payload(state: AutoTradeState) -> JsonDict:
    return {
        **build_market_payload(state),
        **build_momentum_payload(state),
        **build_htf_payload(state),
        **build_market_runtime_payload(state),
    }

def build_runtime_payload(state: AutoTradeState) -> JsonDict:
    return {
        "status": state.status,
        "strategy": state.strategy,
        "cycle_number": state.cycle_number,
    }


def build_signal_payload(
    state: AutoTradeState,
    *,
    confidence: float | None = None,
    reason: str | None = None,
) -> JsonDict:
    return {
        "signal": state.last_signal,
        "confidence": (
            state.last_signal_confidence
            if confidence is None
            else confidence
        ),
        "repeat_count": state.last_signal_repeat_count,
        "reason": (
            state.last_signal_reason
            if reason is None
            else reason
        ),
    }


def build_decision_payload(state: AutoTradeState) -> JsonDict:
    return {
        "decision_status": state.decision_status,
        "decision_reason": state.decision_reason,
    }


def build_runtime_blocks_payload(state: AutoTradeState) -> JsonDict:
    return {
        "entry_block_reason": state.entry_block_reason,
        "entry_block_message": state.entry_block_message,
        "execution_block_reason": state.execution_block_reason,
        "execution_block_title": state.execution_block_title,
        "execution_block_message": state.execution_block_message,
        "execution_block_action": state.execution_block_action,
        "last_flip_block_reason": state.last_flip_block_reason,
    }


def build_execution_quality_payload(state: AutoTradeState) -> JsonDict:
    return {
        "execution_confidence_score": state.execution_confidence_score,
        "execution_confidence_level": state.execution_confidence_level,
        "execution_confidence_reason": state.execution_confidence_reason,
        "execution_quality": state.execution_quality,
        "execution_quality_reason": state.execution_quality_reason,
        "execution_quality_message": state.execution_quality_message,
        "spread_percent": state.spread_percent,
        "snapshot_age_seconds": state.snapshot_age_seconds,
    }


def build_execution_price_payload(state: AutoTradeState) -> JsonDict:
    return {
        "execution_price_source": state.execution_price_source,
        "execution_price_age_seconds": state.execution_price_age_seconds,
        "execution_bid_price": state.execution_bid_price,
        "execution_ask_price": state.execution_ask_price,
        "execution_last_price": state.execution_last_price,
        "execution_price_freshness": state.execution_price_freshness,
    }


def build_adaptive_size_payload(state: AutoTradeState) -> JsonDict:
    return {
        "adaptive_size_base": state.adaptive_size_base,
        "adaptive_size_final": state.adaptive_size_final,
        "adaptive_size_multiplier": state.adaptive_size_multiplier,
        "adaptive_size_reason": state.adaptive_size_reason,
        "adaptive_size_factors": state.adaptive_size_factors,
        "effective_risk_percent": state.effective_risk_percent,
        "effective_target_risk_usd": state.effective_target_risk_usd,
    }


def build_risk_settings_payload(state: AutoTradeState) -> JsonDict:
    return {
        "risk_percent": state.risk_percent,
        "stop_loss_percent": state.stop_loss_percent,
        "take_profit_percent": state.take_profit_percent,
        "max_loss_usd": state.max_loss_usd,
        "max_reserved_balance_percent": state.max_reserved_balance_percent,
        "allocated_balance_usd": state.allocated_balance_usd,
        "leverage": state.leverage,
    }


def build_position_health_payload(state: AutoTradeState) -> JsonDict:
    return {
        "position_hold_seconds": state.position_hold_seconds,
        "position_health_status": state.position_health_status,
        "position_health_score": state.position_health_score,
        "position_health_reason": state.position_health_reason,
        "position_risk_level": state.position_risk_level,
        "position_risk_reason": state.position_risk_reason,
        "position_trend_alignment": state.position_trend_alignment,
        "position_adverse_momentum": state.position_adverse_momentum,
    }


def build_position_intelligence_payload(state: AutoTradeState) -> JsonDict:
    return {
        "position_exit_signal": state.position_exit_signal,
        "position_exit_confidence": state.position_exit_confidence,
        "position_exit_urgency": state.position_exit_urgency,
        "position_reversal_risk": state.position_reversal_risk,
        "position_fatigue_state": state.position_fatigue_state,
        "position_giveback_percent": state.position_giveback_percent,
        "position_mfe_percent": state.position_mfe_percent,
        "position_mae_percent": state.position_mae_percent,
        "position_peak_pnl_usd": state.position_peak_pnl_usd,
        "position_peak_pnl_percent": state.position_peak_pnl_percent,
    }


def build_full_position_intelligence_payload(state: AutoTradeState) -> JsonDict:
    return {
        "position_lifecycle_stage": state.position_lifecycle_stage,
        "position_hold_quality": state.position_hold_quality,
        "position_decay_state": state.position_decay_state,
        "position_exit_signal": state.position_exit_signal,
        "position_exit_confidence": state.position_exit_confidence,
        "position_exit_urgency": state.position_exit_urgency,
        "position_reversal_risk": state.position_reversal_risk,
        "position_intelligence_reason": state.position_intelligence_reason,
        "position_recommended_action": state.position_recommended_action,
        "position_peak_pnl_usd": state.position_peak_pnl_usd,
        "position_peak_pnl_percent": state.position_peak_pnl_percent,
        "position_mfe_percent": state.position_mfe_percent,
        "position_mae_percent": state.position_mae_percent,
        "position_fatigue_score": state.position_fatigue_score,
        "position_fatigue_state": state.position_fatigue_state,
        "position_giveback_percent": state.position_giveback_percent,
        "position_stall_state": state.position_stall_state,
        "position_stall_reason": state.position_stall_reason,
    }


def build_autonomous_payload(state: AutoTradeState) -> JsonDict:
    return {
        "autonomous_action": state.autonomous_action,
        "autonomous_action_reason": state.autonomous_action_reason,
        "autonomous_action_confidence": state.autonomous_action_confidence,
        "autonomous_protection_required": state.autonomous_protection_required,
        "autonomous_reduce_required": state.autonomous_reduce_required,
        "autonomous_exit_required": state.autonomous_exit_required,
    }


def build_runtime_protection_payload(state: AutoTradeState) -> JsonDict:
    return {
        "position_protection_status": state.position_protection_status,
        "position_protection_reason": state.position_protection_reason,
        "runtime_protection_action": state.runtime_protection_action,
        "runtime_protection_reason": state.runtime_protection_reason,
        "break_even_armed": state.break_even_armed,
        "break_even_price": state.break_even_price,
        "profit_lock_active": state.profit_lock_active,
        "profit_lock_price": state.profit_lock_price,
        "trailing_stop_active": state.trailing_stop_active,
        "trailing_stop_price": state.trailing_stop_price,
    }