from pathlib import Path

from hockey_data.mapping_context import MappingDataService
from hockey_data.service import HockeyDataService
from tests.support import LocalTestDatabase

ROOT = Path(__file__).resolve().parents[1]
APP_JS = (ROOT / "ui_builder/static/app.js").read_text(encoding="utf-8")
ADMIN_JS = (ROOT / "hockey_data/static/admin-directories.js").read_text(encoding="utf-8")
AGENT = (ROOT / "hockey_data/agent_bridge.py").read_text(encoding="utf-8")


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


def test_strength_engine_reports_advantage_for_4x3_and_3x4():
    settings = {"strength_regulation_skaters": 5, "strength_min_skaters": 3}
    home_advantage = HockeyDataService._strength_payload(
        settings,
        stage="regular",
        current_period="2",
        timer_state={"penalty_board": {"penalties": [_penalty("home"), _penalty("away"), _penalty("away")]}},
        language="ru",
    )
    assert home_advantage["strength_label"] == "4×3"
    assert home_advantage["advantage_side"] == "home"

    away_advantage = HockeyDataService._strength_payload(
        settings,
        stage="regular",
        current_period="2",
        timer_state={"penalty_board": {"penalties": [_penalty("home"), _penalty("home"), _penalty("away")]}},
        language="ru",
    )
    assert away_advantage["strength_label"] == "3×4"
    assert away_advantage["advantage_side"] == "away"


def test_penalty_plate_routing_uses_single_advantage_side_and_global_shortest_timer():
    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 'const advantageSide = penaltyLocalAdvantageSide(home.length, away.length);' in block
    assert 'if (!advantageSide)' in block
    assert 'transitionEntry = all[0]' in block
    assert 'home: advantageSide === "home"' in block
    assert 'away: advantageSide === "away"' in block


def test_database_schema_reference_lists_real_hockey_tables(tmp_path: Path):
    database = LocalTestDatabase(tmp_path / "schema.sqlite3")
    database.create_all()
    service = MappingDataService(database)  # type: ignore[arg-type]
    payload = service.database_schema_reference()
    names = {row["name"] for row in payload["tables"]}
    assert "hockey_players" in names
    assert "hockey_games" in names
    players = next(row for row in payload["tables"] if row["name"] == "hockey_players")
    column_names = {column["name"] for column in players["columns"]}
    assert "id" in column_names
    assert "external_id" in column_names


def test_sql_parameters_and_table_reference_are_collapsed_by_default():
    assert 'class="hockey-map-sql-reference hockey-map-sql-params-ref"' in ADMIN_JS
    assert 'class="hockey-map-sql-reference hockey-map-sql-schema-ref"' in ADMIN_JS
    assert 'Справочник таблиц БД' in ADMIN_JS
    assert 'data-sql-table-name=' in ADMIN_JS
    assert '<details class="hockey-map-sql-reference hockey-map-sql-params-ref">' in ADMIN_JS
    assert '<details class="hockey-map-sql-reference hockey-map-sql-schema-ref">' in ADMIN_JS
    assert '/api/hockey/admin/mapping-data/database-schema' in AGENT
