"""Golden tests for PORTFOLIO_TRANSITION_UTILITY_V1 (governance/todo/v8_9_p0_adoption_plan.yaml P0-1.5).

Maps to v8.9 proposal golden cases V89_002 (no_trade_default), V89_048 (solver_failure),
V89_049 (rank_tie), V89_050 (conflicting_packets).
"""
from __future__ import annotations

import importlib.util
import sys
from pathlib import Path

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


def _load_module():
    spec = importlib.util.spec_from_file_location("build_portfolio_transition_optimizer_v1", 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_002_no_decision_packet_returns_no_trade_default() -> None:
    mod = _load_module()
    result = mod._hard_constraint_pass({"numeric_provenance_status": "DATA_MISSING"}, {})
    ok, reason = result
    assert ok is False
    assert reason == "DATA_INVALID"


def test_v89_048_missing_execution_mode_blocks_candidate() -> None:
    mod = _load_module()
    ok, reason = mod._hard_constraint_pass(
        {"numeric_provenance_status": "PASS"}, {"execution_mode": None}
    )
    assert ok is False
    assert reason == "EXECUTION_MODE_BLOCK"


def test_v89_049_negative_utility_is_vetoed_not_silently_zeroed() -> None:
    mod = _load_module()
    utility = mod._transition_utility_krw(
        candidate={"action_type": "SELL_CASH_REPAIR", "planned_amount_krw": -500000},
        ce70_net_profit_krw=None,
        tax_fee_slippage_krw=100000,
        cash_repair_benefit_krw=0,
        concentration_reduction_benefit_krw=0,
        turnover_penalty_krw=0,
    )
    assert utility is not None
    assert utility < 0


def test_v89_050_missing_inputs_emit_quarantine_not_fabricated_zero(tmp_path) -> None:
    mod = _load_module()
    sys.argv = [
        "build_portfolio_transition_optimizer_v1.py",
        "--decision-packet", str(tmp_path / "missing_packet.json"),
        "--sell-waterfall", str(tmp_path / "missing_sw.json"),
        "--cash-recovery", str(tmp_path / "missing_cr.json"),
        "--simulation", str(tmp_path / "missing_sim.json"),
        "--out", str(tmp_path / "out.json"),
    ]
    rc = mod.main()
    assert rc == 0
    out = (tmp_path / "out.json").read_text(encoding="utf-8")
    assert "NO_TRADE_AND_QUARANTINE" in out
    assert "missing_optimizer_inputs" in out
