"""The running lease's authoritative progress tracks the runner's progress telemetry."""

from __future__ import annotations

import threading
import time
from typing import Any

import pytest

from mgf.test_web.warden import RunRequest, Warden


@pytest.mark.concurrency
def test_lease_progress_tracks_runner_telemetry() -> None:
    gate = threading.Event()

    def runner(request: RunRequest, emit: Any) -> str:
        emit({"kind": "test_start"})
        emit({"kind": "progress", "progress": 0.6})
        gate.wait(timeout=5)
        emit({"kind": "test_end", "result": "pass"})
        return "pass"

    warden = Warden("proj", runner)
    warden.submit(RunRequest("r1", "T-1"))

    progress = 0.0
    for _ in range(300):
        running = warden.status()["running"]
        if running:
            progress = running[0]["progress"]
            if progress == 0.6:
                break
        time.sleep(0.01)
    assert progress == 0.6, "the warden lifts progress from the runner's telemetry"

    gate.set()
    assert warden.wait_idle()
