from typing import Any

from models.discipline import PineConfigPayload
from services.runtime_rules import runtime_rules


def _pick(data: dict[str, Any], *keys: str) -> Any:
    for key in keys:
        if key in data and data[key] not in (None, ""):
            return data[key]
    return None


def parse_pine_config_payload(payload: dict[str, Any]) -> PineConfigPayload:
    max_trades = _pick(payload, "max_trades_per_session", "max_trades", "maxTrades")
    max_loss = _pick(payload, "max_daily_loss_pct", "max_loss_pct", "maxDailyLossPct")

    return PineConfigPayload(
        session_start=_pick(payload, "session_start", "sessionStart"),
        session_end=_pick(payload, "session_end", "sessionEnd"),
        session_timezone=_pick(payload, "session_timezone", "timezone", "sessionTimezone"),
        max_trades_per_session=int(max_trades) if max_trades is not None else None,
        max_daily_loss_pct=float(max_loss) if max_loss is not None else None,
        max_open_positions=(
            int(v) if (v := _pick(payload, "max_open_positions", "maxOpenPositions")) is not None else None
        ),
        max_quantity=(
            float(v) if (v := _pick(payload, "max_quantity", "maxQuantity")) is not None else None
        ),
        strategy_name=_pick(payload, "strategy", "strategy_name", "strategyName"),
    )


def apply_pine_config(payload: dict[str, Any]) -> dict[str, Any]:
    config = parse_pine_config_payload(payload)
    state = runtime_rules.apply_pine_config(config)
    return {
        "session_start": state.session_start,
        "session_end": state.session_end,
        "session_timezone": state.session_timezone,
        "max_trades_per_session": state.max_trades_per_session,
        "max_daily_loss_pct": state.max_daily_loss_pct,
        "pine_strategy": state.pine_strategy,
        "updated_from": state.updated_from,
    }
