import hashlib
from pathlib import Path

from cyberbrain26.product import ingest_worker as iw
from cyberbrain26.product.shared_root import ensure_shared_root


def test_compute_sha256(tmp_path: Path):
    p = tmp_path / "f.txt"
    p.write_text("abc")
    assert iw.compute_sha256(p) == hashlib.sha256(b"abc").hexdigest()


def test_read_manifest_entries_empty(tmp_path: Path):
    root = ensure_shared_root(tmp_path / "shared")
    assert iw.read_manifest_entries(root) == []


def test_is_ai_export_name(tmp_path: Path):
    p = tmp_path / "conversations.json"
    p.write_text("{}")
    assert iw.is_ai_export(p)


def test_is_ai_export_content(tmp_path: Path):
    p = tmp_path / "data.json"
    p.write_text('{"messages": [{"role":"user"}]}')
    assert iw.is_ai_export(p)


def test_classify_file(tmp_path: Path):
    p = tmp_path / "n.md"
    p.write_text("x")
    assert iw.classify_file(p) == "note"
    p2 = tmp_path / "conversations.json"
    p2.write_text('{"messages":[]}')
    assert iw.classify_file(p2) == "ai-export"


def test_process_batch_dedup(tmp_path: Path):
    root = ensure_shared_root(tmp_path / "shared")
    proc = root / "processing" / "b1"
    proc.mkdir(parents=True)
    (proc / "a.txt").write_text("same")
    (proc / "b.txt").write_text("same")
    # pre-populate manifest with hash of "same" as classified
    import hashlib
    h = hashlib.sha256(b"same").hexdigest()
    from cyberbrain26.product.shared_root import manifest_write
    manifest_write({"sha256": h, "status": "classified"}, shared_root=root)
    res = iw.process_batch("b1", shared_root=root)
    assert res["processed"] + res["duplicates"] == 2
    # at least one duplicate
    assert res["duplicates"] >= 1
