"""Tests from Lab 10's recorded crash test (whisper-base.en, voxbench-v1, 16 shards, 8 workers).
Run: pytest test_platform_practice.py"""
import math

from platform_practice import comparable, completeness, corpus_wer, merge_keyed, shard_of

# The four shards that crashed (numbered 1-16, as in the chapter): every clip, in run order,
# as (clip id, errors, words). Errors and words are the stored results of the crash-test run.
SHARDS = {
    1: [
        ("read/2094-142345-0044", 1, 7),
        ("read/3575-170457-0015", 0, 45),
        ("read/5142-33396-0006", 4, 22),
        ("read/5142-33396-0054", 1, 22),
        ("read/1580-141084-0001", 0, 9),
        ("read/8555-284449-0012", 5, 30),
        ("read/121-123852-0004", 5, 33),
        ("read/3080-5040-0026", 0, 17),
        ("phone/3080-5040-0026", 3, 17),
        ("phone/5484-24317-0033", 2, 12),
        ("calls/e22-4481904-310", 8, 7),
        ("calls/e22-4481904-299", 2, 9),
        ("calls/e22-4481904-147", 3, 15),
        ("calls/e22-4481601-73", 6, 36),
        ("calls/e22-4472403-112", 2, 8),
        ("calls/e22-2020-03-0230487MTN-Ghana-2019-Annual-Results-Call-50", 0, 17),
    ],
    5: [
        ("read/1320-122617-0006", 0, 17),
        ("read/8455-210777-0012", 0, 10),
        ("read/4970-29095-0014", 1, 7),
        ("phone/7902-96592-0011", 3, 23),
        ("read/5484-24318-0031", 1, 9),
        ("read/7975-280076-0023", 1, 20),
        ("read/8131-117016-0033", 1, 10),
        ("phone/8461-281231-0010", 4, 18),
        ("phone/4294-35475-0019", 24, 41),
        ("read/1688-142285-0020", 0, 7),
        ("read/2609-156975-0001", 0, 9),
        ("read/8188-269288-0023", 3, 6),
    ],
    14: [
        ("read/5142-33396-0022", 3, 14),
        ("read/1221-135767-0004", 2, 49),
        ("read/8224-274381-0001", 1, 46),
        ("read/1580-141084-0017", 0, 5),
        ("read/1580-141084-0033", 1, 23),
        ("read/4970-29095-0030", 2, 11),
        ("read/3080-5032-0024", 0, 25),
        ("read/8280-266249-0029", 4, 27),
        ("read/5442-32873-0019", 2, 17),
        ("read/8461-281231-0026", 2, 24),
        ("read/7105-2330-0026", 1, 10),
        ("read/8188-269288-0041", 0, 12),
        ("phone/8188-269288-0041", 3, 12),
        ("calls/e22-4481601-113", 3, 20),
        ("calls/e22-4472403-435", 10, 31),
        ("calls/e22-2020-03-0230487MTN-Ghana-2019-Annual-Results-Call-477", 9, 35),
    ],
    16: [
        ("read/4446-2275-0025", 0, 7),
        ("phone/7902-96591-0020", 2, 32),
        ("read/7902-96592-0011", 0, 23),
        ("read/7902-96594-0008", 1, 9),
        ("phone/2033-164914-0007", 6, 8),
        ("read/7975-280057-0012", 1, 16),
        ("phone/8131-117016-0001", 5, 9),
        ("read/8131-117016-0049", 0, 12),
        ("read/4294-9934-0024", 0, 13),
        ("read/1688-142285-0004", 1, 16),
        ("read/1688-142285-0036", 1, 15),
        ("read/2609-156975-0017", 2, 16),
        ("calls/e22-2020-03-0230487MTN-Ghana-2019-Annual-Results-Call-282", 1, 9),
    ],
}
# Crashed attempts in the crash test: (shard, clips already sent before the crash).
# Shard 1 crashed twice; every crashed shard was retried until it finished.
CRASHES = [(1, 0), (5, 1), (14, 5), (1, 3), (16, 12)]
# The other 12 shards (183 clips), which never crashed: their totals.
OTHER = {"errors": 523, "words": 3104}


def row(clip_id, errors, words, attempt=1):
    return {"clip_id": clip_id, "attempt": attempt, "errors": errors, "words": words}


def streamed_rows():
    """Every row the workers sent back for the four crashed shards, crashed attempts included."""
    rows, attempts = [], {}
    for shard, after in CRASHES:
        attempts[shard] = attempts.get(shard, 0) + 1
        rows += [row(*c, attempt=attempts[shard]) for c in SHARDS[shard][:after]]
    for shard, clips in SHARDS.items():
        rows += [row(*c, attempt=attempts[shard] + 1) for c in clips]
    return rows


def test_shards_depend_only_on_the_clip_id():
    for shard, clips in SHARDS.items():
        assert {shard_of(c[0], 16) for c in clips} == {shard - 1}  # the tool counts shards from 0
    # the clip from the run record: shard 14
    assert shard_of("read/1580-141084-0017", 16) == 13
    # the same id always lands in the same shard, so a retry runs the same clips
    assert shard_of("read/1580-141084-0017", 16) == shard_of("read/1580-141084-0017", 16)


def test_corpus_wer_is_a_ratio_of_sums():
    assert math.isclose(corpus_wer([row("a", 1, 2), row("b", 0, 98)]), 1.0)  # not (50% + 0%) / 2
    assert corpus_wer([]) == 0.0
    # the whole run, from the clean result totals: 666 errors in 4,133 words
    assert round(corpus_wer([OTHER, *(row(*c) for s in SHARDS.values() for c in s)]), 2) == 16.11


def test_adding_up_every_row_counts_21_clips_twice():
    rows = streamed_rows()
    assert len(rows) == 57 + 21  # 57 clips in these shards, 0 + 1 + 5 + 3 + 12 sent twice
    # the naive add-up over the whole run: 261 rows, and a better-looking WER
    assert len(rows) + 183 == 261
    assert round(corpus_wer(rows + [OTHER]), 2) == 15.36
    # the clips counted twice were easy ones
    once = {r["clip_id"]: r for r in rows}
    twice = [once[c] for c in once if sum(r["clip_id"] == c for r in rows) == 2]
    assert len(twice) == 21
    assert round(corpus_wer(twice), 2) == 7.67


def test_one_slot_per_clip():
    store = merge_keyed(streamed_rows())
    assert len(store) == 57
    assert round(corpus_wer(list(store.values()) + [OTHER]), 2) == 16.11  # the run without crashes
    # the later row wins: shard 14's first five clips hold the retry's result
    assert store["read/1580-141084-0017"]["attempt"] == 2
    assert store["read/4970-29095-0030"]["attempt"] == 2
    # shard 1 crashed twice; its third attempt finished
    assert store["read/2094-142345-0044"]["attempt"] == 3


def test_without_retries_the_run_is_incomplete():
    manifest = [c[0] for clips in SHARDS.values() for c in clips]
    first_try = {shard: after for shard, after in CRASHES[:3] + CRASHES[4:]}  # no second crash of shard 1
    stored = [c[0] for shard, clips in SHARDS.items() for c in clips[:first_try[shard]]]
    status, missing = completeness(stored, manifest)
    assert status == "incomplete"
    assert len(missing) == 39  # 201 of 240 stored in the whole run
    assert missing[0] == "read/2094-142345-0044" and missing[-1] == "calls/e22-2020-03-0230487MTN-Ghana-2019-Annual-Results-Call-282"
    # the score on what's there: 15.99% over the whole run
    there = [row(*c) for shard, clips in SHARDS.items() for c in clips[:first_try[shard]]]
    assert round(corpus_wer(there + [OTHER]), 2) == 15.99
    assert completeness(manifest, manifest) == ("complete", [])


CLEAN = {"run_id": "20261102-215158-bf301a", "status": "complete", "dataset": "voxbench-v1",
         "fingerprint": "6212109252ac", "normalizer": "whisper-normalizer==0.1.15"}


def test_compare_refuses_what_does_not_line_up():
    noretry = {**CLEAN, "run_id": "20261102-215507-e8a576", "status": "incomplete"}
    assert comparable(noretry, CLEAN) == ["run 20261102-215507-e8a576 is incomplete"]
    phone = {**CLEAN, "run_id": "20261102-215720-715251", "fingerprint": "3065f0ad044d"}
    assert comparable(phone, CLEAN) == [
        "different dataset versions (voxbench-v1 3065f0ad044d vs voxbench-v1 6212109252ac)"]
    chaos = {**CLEAN, "run_id": "20261102-215320-254f7c"}
    assert comparable(chaos, CLEAN) == []
    # the third rule, not shown in the video
    other = {**CLEAN, "normalizer": "my-normalizer==1.0"}
    assert comparable(CLEAN, other) == [
        "different normalizers (whisper-normalizer==0.1.15 vs my-normalizer==1.0)"]
    assert len(comparable(noretry, {**phone, "normalizer": "x"})) == 3
