import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "app"))

import math
import pytest


def test_calc_draw_score_basic():
    """세트별 결과 → draw_score 계산"""
    from strategy_evolver import calc_draw_score

    results = [
        {"correct": 3, "rank": 5},  # 3/6 + 0.1 = 0.6
        {"correct": 1, "rank": 0},  # 1/6 + 0 = 0.167
    ]
    score = calc_draw_score(results)
    expected = ((3/6 + 0.1) + (1/6)) / 2
    assert abs(score - expected) < 0.01


def test_calc_draw_score_empty():
    """빈 결과 → 0"""
    from strategy_evolver import calc_draw_score
    assert calc_draw_score([]) == 0.0


def test_recalculate_weights_softmax():
    """EMA → Softmax 가중치 변환"""
    from strategy_evolver import _softmax_weights

    ema_scores = {
        "combined": 0.30,
        "simulation": 0.25,
        "heatmap": 0.15,
        "manual": 0.10,
        "custom": 0.05,
    }
    weights = _softmax_weights(ema_scores)

    assert abs(sum(weights.values()) - 1.0) < 0.001
    assert weights["combined"] > weights["simulation"]
    assert weights["simulation"] > weights["heatmap"]
    assert all(w >= 0.049 for w in weights.values())


def test_recalculate_weights_min_weight():
    """한 전략의 EMA가 매우 낮아도 최소 5% 보장"""
    from strategy_evolver import _softmax_weights

    ema_scores = {
        "combined": 0.50,
        "simulation": 0.01,
        "heatmap": 0.01,
        "manual": 0.01,
        "custom": 0.01,
    }
    weights = _softmax_weights(ema_scores)

    assert weights["simulation"] >= 0.049
    assert weights["custom"] >= 0.049
    assert abs(sum(weights.values()) - 1.0) < 0.001


def test_update_ema():
    """EMA 갱신 공식 검증"""
    from strategy_evolver import ALPHA

    old_ema = 0.15
    draw_score = 0.40
    new_ema = ALPHA * draw_score + (1 - ALPHA) * old_ema
    expected = 0.3 * 0.40 + 0.7 * 0.15  # = 0.225
    assert abs(new_ema - expected) < 0.001
