from pathlib import Path

from cyberbrain26.product import index_builder as ib
from cyberbrain26.product.shared_root import ensure_shared_root


def test_extract_task_lines():
    text = "TODO: do thing\nnormal line\nACTION: act\nrozhodnuto X"
    lines = ib._extract_task_lines(text)
    assert any("TODO" in line for line in lines)
    assert any("ACTION" in line for line in lines)


def test_build_index_creates_jsonl(tmp_path: Path):
    root = ensure_shared_root(tmp_path / "shared")
    sorted_dir = root / "sorted" / "note"
    sorted_dir.mkdir(parents=True)
    (sorted_dir / "n.md").write_text("hello world")
    res = ib.build_index(shared_root=root)
    assert res["entries_count"] == 1
    idx = root / "index" / "index.jsonl"
    assert idx.exists()
    entries = ib.read_index(shared_root=root)
    assert len(entries) == 1
    assert "summary" in entries[0]


def test_extract_tasks_finds_todo(tmp_path: Path):
    root = ensure_shared_root(tmp_path / "shared")
    sorted_dir = root / "sorted" / "note"
    sorted_dir.mkdir(parents=True)
    (sorted_dir / "n.md").write_text("TODO: fix bug\nsome text")
    res = ib.extract_tasks(shared_root=root)
    assert res["total_tasks"] >= 1
    data = (root / "tasks" / "tasks.json").read_text()
    assert "TODO" in data
