from pathlib import Path

from hockey_data.service import HockeyDataService

ROOT = Path(__file__).resolve().parents[1]
RUNTIME = (ROOT / "ui_builder/static/runtime.html").read_text(encoding="utf-8")
INDEX = (ROOT / "ui_builder/static/index.html").read_text(encoding="utf-8")
INTEGRATION = (ROOT / "ui_builder/integration.py").read_text(encoding="utf-8")
APP_JS = (ROOT / "ui_builder/static/app.js").read_text(encoding="utf-8")
APP = (ROOT / "app.py").read_text(encoding="utf-8")


def _penalty(side: str, remaining_ms: int = 120000):
    return {
        "side": side,
        "infraction": {"id": "minor"},
        "preset": "2m",
        "durationMs": 120000,
        "remainingMs": remaining_ms,
        "finished": False,
    }


def _strength(home=0, away=0, language="ru"):
    timer_state = {
        "penalty_board": {
            "penalties": [_penalty("home") for _ in range(home)] + [_penalty("away") for _ in range(away)]
        }
    }
    settings = {
        "strength_regulation_skaters": 5,
        "strength_regular_overtime_skaters": 3,
        "strength_playoff_overtime_skaters": 5,
        "strength_min_skaters": 3,
        "strength_state_labels": {
            "regulation": {
                "5x4": {"ru": "Играют в большинстве", "en": "Power play"},
                "4x4": {"ru": "4 на 4", "en": "4 on 4"},
                "4x3": {"ru": "Большинство 4 на 3", "en": "4 on 3 power play"},
            }
        },
    }
    return HockeyDataService._strength_payload(
        settings,
        stage="regular",
        current_period="1",
        timer_state=timer_state,
        language=language,
    )


def test_runtime_badge_is_server_build_version_placeholder():
    assert "BUILD __UI_BUILDER_BUILD_VERSION__" in RUNTIME
    assert "BUILD __UI_BUILDER_BUILD_VERSION__" in INDEX
    assert '.replace("__UI_BUILDER_BUILD_VERSION__", str(build_version or asset_version))' in INTEGRATION
    assert "build_version=BUILD_VERSION" in APP
    assert 'BUILD_VERSION = "2026.08.20.13"' in APP


def test_play_by_play_defaults_collapsed_until_operator_opens_it():
    assert "Object.prototype.hasOwnProperty.call(state.formValues, collapsedKey)" in APP_JS
    assert ": true;" in APP_JS


def test_penalized_side_gets_numeric_condition_and_advantage_side_keeps_pp_caption():
    payload = _strength(home=1, away=0)
    assert payload["home_label"] == "Играют в большинстве"
    assert payload["away_label"] == "Играют в большинстве"


def test_equal_coincidental_penalties_expose_numeric_condition_on_both_mapping_sides():
    payload = _strength(home=1, away=1)
    assert payload["advantage_side"] == ""
    assert payload["home_label"] == "4 на 4"
    assert payload["away_label"] == "4 на 4"


def test_english_penalty_side_uses_numeric_condition():
    payload = _strength(home=1, away=0, language="en")
    assert payload["home_label"] == "Power play"
    assert payload["away_label"] == "Power play"
