"""Where a replay is filed, and what it says about itself (`replay_library`).

The module has carried the library's naming, the Real/Simulated split and the whole sidecar since it
was written, with no tests at all — while every claim in it is the kind that fails silently. A film
filed under the wrong day, or a sidecar describing a window the MP4 beside it does not have, is not
something a render reports; it is something somebody notices six months later, if ever.

The window fields are here because they were exactly that failure: the sidecar said
`preStartSeconds: 180` while the film opened at T−2:00 and ended fourteen seconds before the last
boat crossed.
"""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import replay_library as RL  # noqa: E402

GUN_MS = 1_786_257_779_187                       # 2026-08-09 08:42:59 +02:00 in Stockholm
T0_MS = GUN_MS - 180_000                         # the exporter's T−3
END_MS = T0_MS + 1_662_332                       # …and its stop + 30 s


def _feed(**over) -> dict:
    feed = {
        "meta": {"gunUtcMs": GUN_MS, "trackStartUtcMs": T0_MS, "trackEndUtcMs": END_MS,
                 "raceName": "Race 2001", "eventName": "Team Racing World Championship 2026",
                 "venue": {"name": "Stockholm", "timeZone": "Europe/Stockholm"},
                 "simulated": True},
        "teams": [{"name": "GBR", "fullName": "Great Britain", "boats": [{"sailId": "1"}]},
                  {"name": "USA", "fullName": "United States", "boats": [{"sailId": "3"}]}],
        "result": {"winnerName": "GBR", "maxFinishSec": 1633},
        "source": "sim",
    }
    feed.update(over)
    return feed


# --- the film's own window -------------------------------------------------------------------

def test_the_sidecar_reports_the_window_the_film_actually_has():
    """T−3 to the finish, stated in both origins and labelled with which is which."""
    gun_sec = (GUN_MS - T0_MS) / 1000                        # 180
    duration = (END_MS - T0_MS) / 1000                       # the whole feed window
    m = RL.replay_metadata(_feed(), race_id="sim2001",
                           film_start_race_sec=-gun_sec, film_duration_s=duration)
    assert m["filmStartsAtGunOffsetS"] == -180.0, "the film opens at T−3:00"
    assert m["filmStartsAtFeedSec"] == 0.0, "…which is the feed's own first frame"
    assert m["preStartSeconds"] == 180
    assert m["filmEndsAtFeedSec"] == round(duration, 1)
    assert m["coversFinish"] is True


def test_it_says_so_when_the_finish_is_outside_the_film():
    """The defect, reproduced. The old window opened at T−2:00 and ended at the scorer's
    `maxFinishSec` before `-shortest` trimmed it further — on this race the last boat crossed at feed
    1633 s and the film ended at 1619. Nothing anywhere said so."""
    m = RL.replay_metadata(_feed(), race_id="sim2001",
                           film_start_race_sec=-120.0, film_duration_s=1559.3)
    assert m["filmStartsAtGunOffsetS"] == -120.0
    assert m["filmEndsAtFeedSec"] == 1619.3, "gun 180 − 120 opened + 1559.3 of film"
    assert m["filmEndsAtFeedSec"] < _feed()["result"]["maxFinishSec"]
    assert m["coversFinish"] is False, "a film that stops before the finish must admit it"


def test_a_race_with_no_scored_finish_covers_it_vacuously():
    """A sea trial or an abandoned heat scores no finish; there is nothing to be outside the film."""
    feed = _feed(result=None)
    m = RL.replay_metadata(feed, race_id="seatrial_r2",
                           film_start_race_sec=-180.0, film_duration_s=1350.0)
    assert m["coversFinish"] is True


def test_the_feeds_pre_start_is_reported_separately_from_the_films():
    """They were one field, and they were not the same number."""
    m = RL.replay_metadata(_feed(), race_id="sim2001",
                           film_start_race_sec=-120.0, film_duration_s=1000.0)
    assert m["feedPreStartSeconds"] == 180, "the exporter's window"
    assert m["preStartSeconds"] == 120, "…and the film's"


def test_a_render_that_declares_no_window_still_produces_a_sidecar():
    """`--out`/demo renders pass none; the metadata must not become conditional on the new fields."""
    m = RL.replay_metadata(_feed(), race_id="sim2001")
    assert m["raceName"] == "Race 2001" and "filmStartsAtGunOffsetS" not in m
    assert m["preStartSeconds"] == 180


# --- filing: the parts that have always been untested ------------------------------------------

def test_a_simulated_race_is_filed_apart_from_a_real_one():
    base = Path("/library")
    assert RL.replay_dir_for(base, _feed()).name == RL.SIMULATED_DIR
    assert RL.replay_dir_for(base, _feed(meta={**_feed()["meta"], "simulated": False},
                                         source="real")).name == RL.REAL_DIR


def test_a_feed_predating_the_simulated_flag_is_still_filed_as_simulated():
    """`source == "sim"` is the older stamp. Reading only `meta.simulated` files every one of those as
    REAL, which is the direction that turns a rehearsal into apparent evidence."""
    feed = _feed(meta={"gunUtcMs": GUN_MS, "trackStartUtcMs": T0_MS}, source="sim")
    assert RL.is_simulated(feed) is True


def test_the_name_sorts_by_race_day_in_the_VENUE_s_zone():
    """08:42 UTC+2 is still the 9th; the render machine's zone is wrong by construction (the cloud
    gateway runs UTC), and that is how a day's races get filed under the wrong date."""
    assert RL.replay_name(_feed(), "sim2001").startswith("2026-08-09_")


def test_accented_letters_are_transliterated_not_dropped():
    """Swedish "före" became "f-re", which is not a shorter spelling of anything — and venues and team
    names in this product are routinely Nordic."""
    assert RL._slug("Test före Sommarcupen") == "Test-fore-Sommarcupen"
    assert RL._slug("Skärgården") == "Skargarden"


def test_the_matchup_in_the_name_is_the_codes():
    """The spelled-out names live in the sidecar, where there is room."""
    assert "GBR-v-USA" in RL.replay_name(_feed(), "sim2001")


def test_a_field_the_feed_does_not_carry_is_omitted_not_defaulted():
    """An absent winner is a race with no result — a sea trial has none — and `null` says that where
    an empty string would read as a team whose name is missing."""
    m = RL.replay_metadata(_feed(result={}), race_id="x")
    assert "winner" not in m
