"""Guards for kernel_fusion.py: the chip it copies, the byte counts, the executors, the ridge, the matrix-multiply case, and the numbers the lesson prints."""
import re
from pathlib import Path

import numpy as np
import pytest

import kernel_fusion as kf

ROOFLINE = Path(__file__).resolve().parents[2] / "tiled-matmul-roofline" / "code" / "tiled_roofline.py"
LESSON = Path(__file__).resolve().parents[1] / "lesson.md"
CHAIN: list[kf.Step] = [("add", 0.5), ("relu", 0.0), ("mul", 1.25)]   # bias, activation, scale


def test_chip_constants_equal_the_roofline_lessons(tmp_path):
    """Guards a copy that drifted: the lesson quotes the roofline lesson's A100 numbers, so both files must hold the same ones."""
    source = ROOFLINE.read_text(encoding="utf-8")
    for name in ("A100_PEAK_FLOPS", "A100_BANDWIDTH", "FP16_BYTES"):
        theirs = re.search(rf"^{name} = (\S+)$", source, re.M)
        assert theirs, f"{name} not found in the roofline lesson: update this test"
        assert float(theirs.group(1)) == getattr(kf, name), name


def test_three_steps_move_6_passes_unfused_and_2_fused():
    """Guards the lesson's headline count: 201,326,592 bytes against 67,108,864, a ratio of exactly 3."""
    assert kf.pass_bytes() == 33_554_432
    assert kf.chain_bytes(3, fused=False) == 6 * 33_554_432 == 201_326_592
    assert kf.chain_bytes(3, fused=True) == 2 * 33_554_432 == 67_108_864


@pytest.mark.parametrize("steps", range(1, kf.MAX_STEPS + 1))
def test_while_memory_bound_the_time_ratio_equals_the_byte_ratio(steps):
    """Guards the claim 'time follows bytes': for 1 to 8 steps the chain is memory-bound both ways, so time saved equals bytes saved."""
    ratio_time = kf.chain_time(steps, False) / kf.chain_time(steps, True)
    ratio_bytes = kf.chain_bytes(steps, False) / kf.chain_bytes(steps, True)
    assert ratio_bytes == steps
    assert ratio_time == pytest.approx(steps, rel=1e-12)


def test_a_single_step_gains_nothing_from_fusion():
    """Guards a fused count that charges for fusing: one step is already one read and one write."""
    assert kf.chain_bytes(1, True) == kf.chain_bytes(1, False)
    assert kf.chain_time(1, True) == kf.chain_time(1, False)


def test_intensity_rises_by_the_number_of_steps_but_stays_below_the_ridge():
    """Guards the claim that 3 fused steps are still memory-bound (0.75 FLOP/byte against a ridge of 4.8 for the steps and 153 for the multiply),
    and the step rate: half of the FMA-counted 19.5 TFLOPS, which is 108 SMs x 64 cores x 2 x 1.41 GHz. Charging the steps at 19.5 moves the ridge to 9.6."""
    assert kf.chain_intensity(3, False) == 0.25
    assert kf.chain_intensity(3, True) == 0.75
    assert kf.ridge() == pytest.approx(153.0, abs=0.05)
    assert kf.ridge(kf.A100_STEP_FLOPS) == pytest.approx(4.78, abs=0.005)
    assert kf.A100_STEP_FLOPS == 9.75e12
    assert 108 * 64 * 2 * 1.41e9 == pytest.approx(kf.A100_FP32_FLOPS, rel=0.002)


@pytest.mark.parametrize("peak, first_busy", [(kf.A100_STEP_FLOPS, 20), (kf.A100_FP16_FLOPS / 2, 77)])
def test_the_step_where_the_fused_kernel_stops_waiting_on_memory(peak, first_busy):
    """Guards the crossover against the FMA-counted 19.5 TFLOPS, which doubles the step rate and raises the crossover from 20 to 39; the
    second case is steps done in FP16 arithmetic (78 TFLOPS, halved the same way). Steps before `first_busy` still take the traffic time,
    and `first_busy` is limited by math."""
    traffic_time = kf.chain_bytes(first_busy - 1, True) / kf.A100_BANDWIDTH
    assert kf.steps_to_reach_ridge(peak_flops=peak) == first_busy
    assert kf.chain_time(first_busy - 1, True, peak) == pytest.approx(traffic_time, rel=1e-12)
    assert kf.chain_time(first_busy, True, peak) > kf.chain_bytes(first_busy, True) / kf.A100_BANDWIDTH * (1 + 1e-6)


@pytest.mark.parametrize("fused", [False, True])
def test_the_three_step_times_do_not_depend_on_which_calculation_rate_is_right(fused):
    """Guards the headline against the calculation rate: 3 steps take the same time at the step rate, at the FMA-counted and FP16 rates,
    at the tensor-core rate and at a rate 4 times below the step rate, because they wait on memory in all of them."""
    want = kf.chain_time(3, fused)
    for rate in (kf.A100_STEP_FLOPS, kf.A100_FP32_FLOPS, kf.A100_FP16_FLOPS, kf.A100_PEAK_FLOPS, kf.A100_STEP_FLOPS / 4):
        assert kf.chain_time(3, fused, rate) == want


def test_the_big_matrix_multiply_is_compute_bound_and_fusion_only_removes_the_chains_passes():
    """Guards the 'where fusion pays little' claim: the multiply takes its calculation floor, fused or not, and the chain is the only part that shrinks."""
    assert kf.matmul_flops() / kf.A100_PEAK_FLOPS > kf.matmul_min_bytes() / kf.A100_BANDWIDTH
    assert kf.matmul_time() == kf.matmul_flops() / kf.A100_PEAK_FLOPS
    assert kf.matmul_intensity() == pytest.approx(kf.SIDE / 3) and kf.matmul_intensity() > kf.ridge()
    fused, unfused = kf.matmul_then_chain_time(3, True), kf.matmul_then_chain_time(3, False)
    assert fused == kf.matmul_time()          # the steps' arithmetic is taken to overlap the multiply's calculating
    assert unfused - fused == pytest.approx(kf.chain_time(3, False), rel=1e-9)
    assert 1 - fused / unfused < 0.2          # about 18%, nowhere near the 67% the chain alone saves
    assert 1 - kf.chain_time(3, True) / kf.chain_time(3, False) == pytest.approx(2 / 3)


@pytest.mark.parametrize("size,chunk", [(1000, 7), (1000, 1000), (1000, 1001), (1000, 1), (1024, 256), (999, 100)])
def test_counted_traffic_matches_the_closed_form_and_the_outputs_agree(size, chunk):
    """Guards a remainder chunk that is dropped or counted twice: the counters must equal the closed form for any chunk size,
    and the fused and unfused runs must produce the very same numbers as the plain chain. This checks the counting model against
    its formula; it is not a measurement of a GPU."""
    x = np.random.default_rng(size).standard_normal(size).astype(np.float32)
    a, b = x.copy(), x.copy()
    tu, tf = kf.Traffic(), kf.Traffic()
    kf.run_unfused(a, CHAIN, tu)
    kf.run_fused(b, CHAIN, tf, chunk)
    want = kf.reference(x, CHAIN)
    assert np.array_equal(a, want) and np.array_equal(b, want)
    assert (tu.loads, tu.stores) == (size * len(CHAIN), size * len(CHAIN))
    assert (tf.loads, tf.stores) == (size, size)
    assert tu.nbytes(2) == kf.chain_bytes(len(CHAIN), False, size)
    assert tf.nbytes(2) == kf.chain_bytes(len(CHAIN), True, size)


def test_the_hand_worked_example_of_the_lesson():
    """Guards the table in Go deeper: six numbers, three steps, chunks of two. Unfused 36 numbers cross, fused 12."""
    steps = [("add", 1.0), ("mul", 2.0), ("sub", 3.0)]
    x = np.array([1, 2, 3, 4, 5, 6], dtype=np.float32)
    a, b = x.copy(), x.copy()
    tu, tf = kf.Traffic(), kf.Traffic()
    kf.run_unfused(a, steps, tu)
    kf.run_fused(b, steps, tf, 2)
    assert a.tolist() == b.tolist() == [1, 3, 5, 7, 9, 11]
    assert tu.loads + tu.stores == 36 and tf.loads + tf.stores == 12


def test_timing_split_covers_the_array_exactly():
    """Guards the CPU timing setup: a worker count that does not divide the array would leave a tail untouched and shorten the timed work."""
    assert kf.CPU_ELEMS % kf.CPU_WORKERS == 0
    slabs = kf._slabs(np.arange(kf.CPU_ELEMS, dtype=np.float32), kf.CPU_WORKERS)
    assert sum(s.size for s in slabs) == kf.CPU_ELEMS and slabs[0][0] == 0 and slabs[-1][-1] == kf.CPU_ELEMS - 1


def test_the_lesson_pastes_the_real_output_and_quotes_its_numbers(capsys):
    """Guards the lesson text against the code: every line main() prints is pasted verbatim into the lesson, and each figure the prose
    quotes, formatted here from the model and not typed, appears in the lesson."""
    kf.main()
    text = LESSON.read_text(encoding="utf-8")
    for line in capsys.readouterr().out.splitlines():
        assert line in text, line
    us = lambda seconds: f"{seconds * 1e6:.1f} \u00b5s"
    after, fused_after = kf.matmul_then_chain_time(3, False), kf.matmul_then_chain_time(3, True)
    quoted = [
        f"{kf.pass_bytes():,}", f"{kf.chain_bytes(3, False):,}", f"{kf.chain_bytes(3, True):,}", f"{kf.pass_bytes() / 1e6:.1f} MB",
        us(kf.chain_time(3, False)), us(kf.chain_time(3, True)), us(kf.chain_time(6, False)), us(kf.chain_time(6, True)),
        f"{kf.chain_intensity(3, False):.2f}", f"{kf.chain_intensity(3, True):.2f}",
        f"{kf.ridge():.1f}", f"{kf.ridge(kf.A100_STEP_FLOPS):.1f}", f"{kf.A100_STEP_FLOPS / 1e12:g} trillion", f"{kf.A100_FP32_FLOPS / 1e12:g} trillion",
        f"{kf.steps_to_reach_ridge()} steps", f"about {kf.steps_to_reach_ridge(peak_flops=kf.A100_FP16_FLOPS / 2)} steps",
        f"{kf.matmul_flops() / 1e9:.1f} billion", us(kf.matmul_time()), us(kf.matmul_min_bytes() / kf.A100_BANDWIDTH),
        f"{kf.matmul_intensity():,.1f}", us(after), f"{after / fused_after:.2f}", f"{(after - fused_after) / after * 100:.1f}%",
    ]
    for figure in quoted:
        assert figure in text, figure
