"""DB-Roundtrip: Karten + Telemetrie."""
import json


async def test_karten_roundtrip(testdb):
    await testdb.kanban_upsert_card("p", "scan", "c1", "chunk", "schneiden", {"groesse": 10})
    await testdb.kanban_upsert_card("p", "scan", "c2", "chunk", "schneiden", {"groesse": 99})
    karten = await testdb.kanban_pull("p", "scan", "schneiden", 10)
    assert [k["card_id"] for k in karten] == ["c2", "c1"]  # LPT: größte zuerst
    assert karten[0]["payload"]["groesse"] == 99

    await testdb.kanban_advance_many("p", "scan", [("c1", "sammeln")])
    assert await testdb.kanban_count("p", "schneiden") == 1
    assert (await testdb.kanban_stage_counts("p"))["scan"] == {"schneiden": 1, "sammeln": 1}


async def test_payload_erhalt_bei_upsert_ohne_payload(testdb):
    await testdb.kanban_upsert_card("p", "scan", "c1", "chunk", "schneiden", {"datei": "a.py"})
    await testdb.kanban_upsert_card("p", "scan", "c1", "chunk", "nachfass", None)
    karte = await testdb.kanban_get_card("p", "scan", "c1")
    assert karte["stage"] == "nachfass" and karte["payload"]["datei"] == "a.py"


async def test_events_mit_run_id(testdb):
    testdb.set_current_run("p", "lauf-1")
    await testdb.add_event("p", "agent", key="scan:c1", status="ok", dur_ms=1200,
                           meta={"tokens": {"output": 500}})
    db = await testdb.get_db()
    cursor = await db.execute("SELECT kind, status, run_id, meta FROM events WHERE topic='p'")
    kind, status, run_id, meta = await cursor.fetchone()
    assert (kind, status, run_id) == ("agent", "ok", "lauf-1")
    assert json.loads(meta)["tokens"]["output"] == 500
    testdb.set_current_run("p", None)
