from pathlib import Path

from hockey_data.service import HockeyDataService

ROOT = Path(__file__).resolve().parents[1]
APP_JS = (ROOT / "ui_builder/static/app.js").read_text(encoding="utf-8")


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


def test_complex_two_vs_one_keeps_real_strength_and_outputs_caption_on_advantage_side():
    settings = {
        "strength_regulation_skaters": 5,
        "strength_min_skaters": 3,
        "strength_state_labels": {"regulation": {"4x3": {"ru": "Играют в большинстве", "en": "Power play"}}},
    }
    value = HockeyDataService._strength_payload(
        settings,
        stage="regular",
        current_period="2",
        timer_state={"penalty_board": {"penalties": [_penalty("home"), _penalty("home"), _penalty("away")] }},
        language="ru",
    )
    assert value["strength_label"] == "3×4"
    assert value["advantage_side"] == "away"
    assert value["home_label"] == "Играют в большинстве"
    assert value["away_label"] == "Играют в большинстве"


def test_single_remaining_penalty_outputs_pp_caption_on_opposite_team():
    settings = {
        "strength_regulation_skaters": 5,
        "strength_min_skaters": 3,
        "strength_state_labels": {"regulation": {"5x4": {"ru": "Играют в большинстве", "en": "Power play"}}},
    }
    value = HockeyDataService._strength_payload(
        settings,
        stage="regular",
        current_period="2",
        timer_state={"penalty_board": {"penalties": [_penalty("home")] }},
        language="ru",
    )
    assert value["advantage_side"] == "away"
    assert value["home_label"] == "Играют в большинстве"
    assert value["away_label"] == "Играют в большинстве"


def test_display_plan_never_outputs_two_penalty_plates():
    start = APP_JS.index("function penaltyDisplayEntriesByTargetSide")
    end = APP_JS.index("function hockeyPenaltySideMappingDetail", start)
    block = APP_JS[start:end]
    assert 'const all = [...home, ...away].sort' in block
    assert 'return { home: [], away: [], routedToAdvantage: false' in block
    assert 'home: advantageSide === "home" && transitionEntry ? [transitionEntry] : []' in block
    assert 'away: advantageSide === "away" && transitionEntry ? [transitionEntry] : []' in block
