from fxhnt.application.allocation_policy import (
    ALLOCATION_POLICY,
    ALLOCATION_POLICY_VERSION,
    AllocationPolicy,
    allocation_policy_hash,
)

_EXPECTED_HASH = "1583d909e7d28932d06f88e6877d9218562138b9a372bf92d8db8af9dfe6b26d"


def test_policy_defaults():
    p = ALLOCATION_POLICY
    assert (p.target_vol, p.kelly_fraction, p.max_leverage, p.max_strategy_weight) == (
        0.12,
        0.5,
        1.5,
        0.5,
    )
    assert (p.marginal_gate, p.min_history_days) == (True, 60)
    assert (p.kill_dd, p.reenter_dd) == (0.25, 0.10)
    assert p.capital_ceiling == 35_000.0
    assert p.capacity_min_sharpe == 1.0
    assert p.equity_default_ceiling == 10_000_000.0


def test_hash_content_derived_and_pinned():
    assert allocation_policy_hash(ALLOCATION_POLICY, ALLOCATION_POLICY_VERSION) == allocation_policy_hash(
        ALLOCATION_POLICY, ALLOCATION_POLICY_VERSION
    )  # stable
    assert allocation_policy_hash(
        AllocationPolicy(target_vol=0.10), ALLOCATION_POLICY_VERSION
    ) != allocation_policy_hash(ALLOCATION_POLICY, ALLOCATION_POLICY_VERSION)  # field change
    assert (
        allocation_policy_hash(ALLOCATION_POLICY, 2)
        != allocation_policy_hash(ALLOCATION_POLICY, 1)
    )
    assert (
        allocation_policy_hash(ALLOCATION_POLICY, ALLOCATION_POLICY_VERSION)
        == _EXPECTED_HASH  # noqa: F821
    )


def test_cvar_alpha_default_and_version_bumped():
    from fxhnt.application.allocation_policy import AllocationPolicy, ALLOCATION_POLICY_VERSION
    assert AllocationPolicy().cvar_alpha == 0.10
    assert ALLOCATION_POLICY_VERSION == 4


def test_policy_has_capacity_knobs_and_version_bumped():
    from fxhnt.application.allocation_policy import AllocationPolicy, ALLOCATION_POLICY_VERSION
    p = AllocationPolicy()
    assert p.capacity_min_sharpe == 1.0 and p.equity_default_ceiling == 10_000_000.0
    assert ALLOCATION_POLICY_VERSION >= 3


def test_resolve_policy_paper_vs_live_ceiling_and_hash():
    from fxhnt.config import Settings
    from fxhnt.application.allocation_policy import (
        resolve_allocation_policy, allocation_policy_hash, ALLOCATION_POLICY_VERSION)
    paper = Settings()                       # allow_live defaults False
    live = Settings(); live.execution.allow_live = True
    p_pol = resolve_allocation_policy(paper); l_pol = resolve_allocation_policy(live)
    assert p_pol.capital_ceiling == 1_000_000.0
    assert l_pol.capital_ceiling == 35_000.0
    # the resolved ceiling is in the hash -> paper vs live audit-distinguishable
    assert (allocation_policy_hash(p_pol, ALLOCATION_POLICY_VERSION)
            != allocation_policy_hash(l_pol, ALLOCATION_POLICY_VERSION))
