"""Guide-Ebene der Auto-Sequenz: generieren → QA → Repair-Loop bis 100 %/Stillstand."""
import blocks
import guide
import guide_qa
import guide_board


def _patch(monkeypatch, noten, calls):
    async def fake_gen(*a, **k):
        calls["gen"] += 1

    async def fake_rep(topic, fmt):
        calls["rep"] += 1
        return []

    async def fake_qa(topic, llm=False):
        return {"note_guide": noten.pop(0) if len(noten) > 1 else noten[0]}

    monkeypatch.setattr(guide, "generate_guide", fake_gen)
    monkeypatch.setattr(guide_board, "repair_karten", fake_rep)
    monkeypatch.setattr(guide_qa, "guide_qa_report", fake_qa)


async def test_guide_fertig_ohne_repair(testdb, monkeypatch):
    blocks._blocks_errors.pop("G1", None)
    calls = {"gen": 0, "rep": 0}
    _patch(monkeypatch, [10.0], calls)
    await blocks._guide_ebene("G1", "", "claude", lambda: False, lambda *a, **k: None)
    assert calls["gen"] == 1 and calls["rep"] == 0  # nur initial gebaut
    assert "G1" not in blocks._blocks_errors


async def test_guide_repariert_bis_100(testdb, monkeypatch):
    blocks._blocks_errors.pop("G2", None)
    calls = {"gen": 0, "rep": 0}
    _patch(monkeypatch, [7.0, 10.0], calls)  # erst 7.0, nach einem Repair 10.0
    await blocks._guide_ebene("G2", "", "claude", lambda: False, lambda *a, **k: None)
    assert calls["rep"] == 1
    assert "G2" not in blocks._blocks_errors


async def test_guide_stillstand_meldet_systemfehler(testdb, monkeypatch):
    blocks._blocks_errors.pop("G3", None)
    calls = {"gen": 0, "rep": 0}
    _patch(monkeypatch, [6.0], calls)  # Repair bewegt die Note nie
    await blocks._guide_ebene("G3", "", "claude", lambda: False, lambda *a, **k: None)
    assert "G3" in blocks._blocks_errors
    assert "Guide" in blocks._blocks_errors["G3"]
