from pathlib import Path

from hockey_data.auth_bridge import HockeyUser
from hockey_data.mapping_context import MappingDataService
from tests.support import LocalTestDatabase

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


def test_prepared_titles_is_forced_to_last_runtime_tab_and_uses_hockey_api_directly():
    assert 'state.config.tabs = state.config.tabs.filter((tab) => tab?.id !== "prepared_titles")' in APP
    assert 'state.config.tabs.push({ id: "prepared_titles", label: "Заготовки" });' in APP
    # BUILD84 accidentally routed these through boot.api (/api/ui-builder/runtime), producing 404 Not Found.
    prepared_slice = APP[APP.index("async function hockeyLoadPreparedMappingSources"):APP.index("function renderHockeyPreparedTitlesWorkspace")]
    assert 'api(`/api/hockey/prepared-titles' not in prepared_slice
    assert 'api("/api/hockey/prepared-titles' not in prepared_slice
    assert 'hockeyGameControlRequest(`/prepared-titles' in prepared_slice
    assert 'hockeyGameControlRequest(`/agents/vmix-inventory' in prepared_slice


def test_prepared_title_browser_keeps_title_inputs_visible_even_without_field_inventory():
    start = APP.index("function hockeyPreparedInventoryInputs")
    end = APP.index("function hockeyPreparedSourceIdentity", start)
    block = APP[start:end]
    assert 'fields.length > 0' in block
    assert '(GT|XAML|TITLE)' in block


def test_penalty_side_context_is_match_shared_between_operator_and_admin(tmp_path):
    db = LocalTestDatabase(tmp_path / "ctx.sqlite3")
    db.create_all()
    service = MappingDataService(db)
    operator = HockeyUser(id="op", login="operator", display_name="Operator")
    admin = HockeyUser(id="admin", login="admin", display_name="Admin")

    service.set_context_value("selected_home_penalty_id", "pen-home-17", operator, {"game_id": "game-1"})
    service.set_context_value("selected_away_penalty_id", "pen-away-9", operator, {"game_id": "game-1"})
    context, variables = service.resolve_context(admin, {"game_id": "game-1"})
    values = {item["key"]: item.get("value", "") for item in variables}

    assert context["selected_home_penalty_id"] == "pen-home-17"
    assert context["selected_away_penalty_id"] == "pen-away-9"
    assert values["selected_home_penalty_id"] == "pen-home-17"
    assert values["selected_away_penalty_id"] == "pen-away-9"


def test_context_batch_route_precedes_dynamic_context_key_route(tmp_path):
    from fastapi import FastAPI
    from fastapi.testclient import TestClient
    from hockey_data.agent_bridge import VmixAgentHub, create_hockey_agent_router

    db = LocalTestDatabase(tmp_path / "batch.sqlite3")
    db.create_all()
    hub = VmixAgentHub(db)  # type: ignore[arg-type]
    user = HockeyUser(id="op", login="operator", display_name="Operator")

    async def auth():
        return user

    app = FastAPI()
    app.include_router(create_hockey_agent_router(hub, auth_dependency=auth))
    client = TestClient(app)
    response = client.post(
        "/api/hockey/context/batch",
        json={
            "values": {
                "selected_home_penalty_id": "pen-home-17",
                "selected_home_penalty_player_id": "777",
                "selected_home_penalty_player_db_id": "42",
                "selected_home_penalty_team_penalty": "0",
            },
            "context": {"game_id": "game-1"},
        },
    )
    assert response.status_code == 200, response.text
    payload = response.json()
    assert payload["ok"] is True
    assert {item["key"] for item in payload["items"]} == {
        "selected_home_penalty_id",
        "selected_home_penalty_player_id",
        "selected_home_penalty_player_db_id",
        "selected_home_penalty_team_penalty",
    }
