"""Golden tests for SELL_LOT_PARETO_SELECTOR_V1 (governance/todo/v8_9_p0_adoption_plan.yaml P0-2.3).

Maps to v8.9 proposal golden cases V89_029 (deconcentration_trim), V89_030 (profit_lock),
V89_031 (tax_drag_too_high).
"""
from __future__ import annotations

import importlib.util
from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]
MODULE_PATH = ROOT / "tools" / "build_sell_waterfall_engine_v4.py"


def _load_module():
    spec = importlib.util.spec_from_file_location("build_sell_waterfall_engine_v4", MODULE_PATH)
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module


def test_v89_029_deconcentration_trim_dominates_lower_benefit_candidate() -> None:
    mod = _load_module()
    candidate_a = {"avoided_tail_loss_krw": 100000, "tax_fee_slippage_krw": 10000}
    candidate_b = {"avoided_tail_loss_krw": 50000, "tax_fee_slippage_krw": 20000}
    assert mod._dominates(candidate_a, candidate_b) is True
    assert mod._dominates(candidate_b, candidate_a) is False


def test_v89_030_missing_missed_upside_penalty_uses_zero_not_estimate() -> None:
    mod = _load_module()
    score, missing_fields = mod._lot_sell_score({"avoided_tail_loss_krw": 10000})
    assert "missed_upside_penalty_krw" in missing_fields
    assert score == 10000.0


def test_v89_031_tax_drag_exceeding_benefit_yields_negative_score() -> None:
    mod = _load_module()
    score, _ = mod._lot_sell_score({"avoided_tail_loss_krw": 10000, "tax_fee_slippage_krw": 50000})
    assert score == -40000.0


def test_pareto_group_ranking_orders_by_score_within_stage() -> None:
    mod = _load_module()
    rows = [
        {"candidate_id": "A", "avoided_tail_loss_krw": 100000, "tax_fee_slippage_krw": 10000, "lot_sell_score_krw": 90000.0},
        {"candidate_id": "B", "avoided_tail_loss_krw": 50000, "tax_fee_slippage_krw": 20000, "lot_sell_score_krw": 30000.0},
    ]
    ranked = mod._rank_pareto_group(rows)
    assert ranked[0]["candidate_id"] == "A"
    assert ranked[0]["pareto_rank"] == 1
    assert ranked[1]["pareto_dominated"] is True
