#!/usr/bin/env python3
"""
WBS-9.3: Stop Price 자동 충전 절차

조건: stop_price IS NULL AND atr20 IS NOT NULL
"""

def calculate_stop_price(
    entry_price: float = None,
    close_price: float = None,
    atr20: float = None,
    multiplier: float = 2.0,
    fallback_pct: float = -5.0
) -> float:
    """
    Calculate stop loss price.

    전략 (우선순위):
    1. entry_price 있으면: entry - (atr20 × multiplier)
    2. entry_price 없으면: close - (atr20 × multiplier)
    3. atr20 없으면: price × (1 + fallback_pct/100)

    입력:
      entry_price: 진입가 (선택)
      close_price: 현재가 (필수 또는 entry_price)
      atr20: ATR20 (권장)
      multiplier: ATR 배수 (default: 2.0)
      fallback_pct: ATR 미사용시 폴백 (default: -5%)

    출력:
      stop_price (숫자) 또는 None (실패시)
    """
    # ATR 기반 계산 (권장)
    if atr20 is not None and atr20 > 0:
        base_price = entry_price if entry_price is not None else close_price
        if base_price is not None and base_price > 0:
            stop_price = base_price - (atr20 * multiplier)
            return max(round(stop_price, 0), base_price * 0.8)  # 최소 20% 하방선

    # Fallback: 단순 백분율 기반
    if close_price is not None and close_price > 0:
        fallback_stop = close_price * (1 + fallback_pct / 100)
        return max(round(fallback_stop, 0), close_price * 0.7)  # 최소 30% 하방선

    return None


def auto_fill_stop_price(
    row: dict,
    multiplier: float = 2.0,
    fallback_pct: float = -5.0
) -> dict:
    """
    자동 충전: stop_price 필드

    입력:
      row: 현재 행 (stop_price = None)
      multiplier: ATR 배수 (default: 2.0)
      fallback_pct: 폴백 백분율 (default: -5%)

    출력:
      row (stop_price 채워짐) 또는 원본 (실패시)
    """
    if row.get("stop_price") is not None:
        return row

    stop_price = calculate_stop_price(
        entry_price=row.get("entry_price"),
        close_price=row.get("close_price"),
        atr20=row.get("atr20"),
        multiplier=multiplier,
        fallback_pct=fallback_pct
    )

    if stop_price is not None:
        row["stop_price"] = stop_price
        row["_fill_source"] = "auto_fill_stop_price_v1"
        row["_stop_price_basis"] = (
            "atr20" if row.get("atr20") is not None else "fallback_pct"
        )

    return row
