import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..")))
from server.world.level_progression_curve import calculate_piecewise_exp_curve

def verify_curve():
    benchmarks = calculate_piecewise_exp_curve()
    
    # 1. Total levels
    assert len(benchmarks) == 100, f"Expected 100 levels, got {len(benchmarks)}"
    
    # 2. Strict monotonicity of cumulative_exp
    for lvl in range(2, 101):
        prev = benchmarks[lvl - 1]
        curr = benchmarks[lvl]
        assert curr.cumulative_exp > prev.cumulative_exp, f"Cumulative EXP not strictly increasing at {lvl}: {curr.cumulative_exp} <= {prev.cumulative_exp}"
        assert curr.target_exp == curr.cumulative_exp, f"target_exp mismatch at {lvl}"
        if lvl < 100:
            assert curr.exp_to_next_level > 0, f"exp_to_next_level <= 0 at {lvl}"
        else:
            assert curr.exp_to_next_level == 0, f"exp_to_next_level != 0 at 100"

    # 3. Budget ratios: Lv 1-20 < 0.1% of lifetime
    total_lifetime = benchmarks[100].cumulative_exp
    cum_20 = benchmarks[20].cumulative_exp
    ratio_1_20 = cum_20 / total_lifetime
    print(f"Total lifetime EXP (Lv 100): {total_lifetime:,}")
    print(f"Lv 20 cumulative EXP: {cum_20:,} ({ratio_1_20 * 100:.4f}%)")
    assert ratio_1_20 < 0.001, f"Lv 1-20 budget ratio {ratio_1_20} >= 0.001 (0.1%)"

    # 4. Soft-wall Lv 99->100 delta >= 30% of total 1-98 EXP
    sum_1_98 = benchmarks[99].cumulative_exp
    delta_99 = benchmarks[99].exp_to_next_level
    ratio_99_to_98 = delta_99 / sum_1_98
    ratio_99_to_lifetime = delta_99 / total_lifetime
    print(f"Cumulative EXP 1-98: {sum_1_98:,}")
    print(f"Delta EXP 99->100: {delta_99:,}")
    print(f"Delta 99 / Cumulative 1-98: {ratio_99_to_98 * 100:.2f}% (spec: >= 30%)")
    print(f"Delta 99 / Lifetime EXP: {ratio_99_to_lifetime * 100:.2f}% (spec: 25-35%)")
    assert ratio_99_to_98 >= 0.30, f"Delta 99 ratio {ratio_99_to_98} < 0.30"
    assert 0.20 <= ratio_99_to_lifetime <= 0.35, f"Delta 99 lifetime ratio {ratio_99_to_lifetime} not in [0.20, 0.35]"

    # 5. Death penalty brackets
    for lvl in range(1, 61):
        assert benchmarks[lvl].death_penalty_ratio == 0.0, f"Death penalty at {lvl} != 0.0"
    for lvl in range(61, 81):
        assert benchmarks[lvl].death_penalty_ratio == 0.05, f"Death penalty at {lvl} != 0.05"
    for lvl in range(81, 90):
        assert benchmarks[lvl].death_penalty_ratio == 0.10, f"Death penalty at {lvl} != 0.10"
    for lvl in range(90, 99):
        assert benchmarks[lvl].death_penalty_ratio == 0.15, f"Death penalty at {lvl} != 0.15"
    assert benchmarks[99].death_penalty_ratio == 0.25, f"Death penalty at 99 != 0.25"
    assert benchmarks[100].death_penalty_ratio == 0.0, f"Death penalty at 100 != 0.0"

    print("ALL MATHEMATICAL VERIFICATIONS PASSED 100%!")

if __name__ == "__main__":
    verify_curve()
