from pathlib import Path


def test_strength_transition_recomputes_configured_label():
    from hockey_data.service import HockeyDataService

    settings = {
        "strength_regulation_skaters": 5,
        "strength_min_skaters": 3,
        "strength_state_labels": {
            "regulation": {
                "5x3": {"ru": "5 на 3", "en": "5 on 3"},
                "5x4": {"ru": "PP", "en": "PP"},
            },
        },
    }

    def penalty(remaining: int) -> dict:
        return {
            "side": "home",
            "infraction": {"code": "TEST"},
            "preset": "2",
            "durationMs": 120000,
            "remainingMs": remaining,
            "finished": False,
        }

    double_state = {"penalty_board": {"penalties": [penalty(70000), penalty(40000)]}}
    single_state = {"penalty_board": {"penalties": [penalty(70000)]}}

    double = HockeyDataService._strength_payload(
        settings, stage="regular", current_period="1", timer_state=double_state, language="ru"
    )
    single = HockeyDataService._strength_payload(
        settings, stage="regular", current_period="1", timer_state=single_state, language="ru"
    )

    assert double["state_key"] == "5x3"
    assert double["state_label"] == "5 на 3"
    assert single["state_key"] == "5x4"
    assert single["state_label"] == "PP"
    assert single["away_label"] == "PP"


def test_runtime_refreshes_only_changed_mapping_when_strength_changes():
    js = Path("ui_builder/static/app.js").read_text(encoding="utf-8")
    bridge = Path("hockey_data/agent_bridge.py").read_text(encoding="utf-8")

    assert "function hockeyStrengthMappingSignature" in js
    assert "function hockeyRefreshVmixMappingForStrength" in js
    assert "apply-mapping?only_changed=true" in js
    assert "hockeyStrengthMappingSignature(previousControl) !== hockeyStrengthMappingSignature(payload)" in js
    assert "vmixStrengthMappingRefreshPending" in js
    assert "vmixStrengthMappingRefreshQueued" in js

    assert "only_changed: bool = False" in bridge
    assert 'reason="runtime_strength_changed" if only_changed else "manual_apply"' in bridge
    assert "only_changed=only_changed" in bridge
