from pathlib import Path

from hockey_data.auth_bridge import HockeyUser
from hockey_data.mapping_context import MappingDataService
from hockey_data.models import Game
from hockey_data.service import HockeyDataService
from tests.support import LocalTestDatabase

ROOT = Path(__file__).resolve().parents[1]
APP = (ROOT / "ui_builder/static/app.js").read_text(encoding="utf-8")
ADMIN = (ROOT / "hockey_data/static/admin-directories.js").read_text(encoding="utf-8")
MAPPING = (ROOT / "hockey_data/mapping_context.py").read_text(encoding="utf-8")


def test_penalty_card_no_longer_renders_technical_id_block():
    start = APP.index("function hockeyPenaltyCard")
    end = APP.index("function hockeyPenaltyContext", start) if "function hockeyPenaltyContext" in APP[start:] else start + 12000
    snippet = APP[start:end]
    assert "hpd-team-card-identifiers" not in snippet
    assert "Player external ID" not in snippet
    assert "Player DB ID" not in snippet


def test_side_penalty_context_is_shared_between_accounts(tmp_path: Path):
    database = LocalTestDatabase(tmp_path / "shared-penalty-context.sqlite3")
    database.create_all()
    with database.session() as session:
        session.add(Game(external_id="G1", tournament_external_id="T1", home_team_external_id="H", away_team_external_id="A"))
    service = MappingDataService(database)  # type: ignore[arg-type]
    operator = HockeyUser(id="10", login="operator", display_name="Operator", is_admin=False, role="operator")
    admin = HockeyUser(id="99", login="admin", display_name="Admin", is_admin=True, role="admin")

    service.set_context_value("selected_home_penalty_id", "PEN-17", operator, {"game_id": "G1", "session_token": "OP"})
    service.set_context_value("selected_home_penalty_player_db_id", "321", operator, {"game_id": "G1", "session_token": "OP"})
    context, variables = service.resolve_context(admin, {"game_id": "G1", "session_token": "ADM"})
    assert context["selected_home_penalty_id"] == "PEN-17"
    assert context["selected_home_penalty_player_db_id"] == "321"
    variable = next(item for item in variables if item["key"] == "selected_home_penalty_id")
    assert variable["scope"] == "match_shared"


def test_mapping_input_picker_sorts_by_number_and_fields_naturally():
    start = ADMIN.index("function mappingInventoryInputs(profile)")
    end = ADMIN.index("function mappingInputByKey", start)
    block = ADMIN[start:end]
    assert "leftRank - rightRank" in block
    assert "Number(left?.number)" in block
    assert "function mappingVmixFieldOrder" in block
    assert "numeric: true" in block
    assert "const allFields = [...(currentInput.fields || [])].sort(mappingVmixFieldOrder);" in ADMIN


def test_coincidental_penalties_do_not_fill_side_powerplay_labels():
    settings = {
        "strength_regulation_skaters": 5,
        "strength_min_skaters": 3,
        "strength_state_labels": {"regulation": {"4x4": {"ru": "4 на 4", "en": "4 on 4"}}},
    }
    def penalty(side: str):
        return {"side": side, "infraction": {"code": "TEST"}, "preset": "2", "durationMs": 120000, "remainingMs": 90000, "finished": False}
    timer_state = {"penalty_board": {"penalties": [penalty("home"), penalty("away")]}}
    value = HockeyDataService._strength_payload(settings, stage="regular", current_period="1", timer_state=timer_state, language="ru")
    assert value["advantage_side"] == ""
    assert value["state_key"] == "4x4"
    assert value["home_label"] == "4 на 4"
    assert value["away_label"] == "4 на 4"
