from __future__ import annotations

import argparse
import json
from pathlib import Path

from host_compute_ocr import crawl_files, run_host_compute, split_extensions


def test_split_extensions_normalizes() -> None:
    assert split_extensions("pdf,png,.jpg") == {".pdf", ".png", ".jpg"}


class FakeClient:
    def __init__(self):
        self.calls = []

    def run(self, uri, payload):
        self.calls.append((uri, payload))
        path = payload["path"]
        if path == ".":
            return {"result": {"value": {"ok": True, "entries": [
                {"name": "2026.05", "type": "dir", "size": None},
                {"name": "skip.bin", "type": "file", "size": 1},
            ]}}}
        if path == "2026.05":
            return {"result": {"value": {"ok": True, "entries": [
                {"name": "invoice.pdf", "type": "file", "size": 10},
            ]}}}
        raise AssertionError(path)


def test_crawl_files_recurses_and_filters() -> None:
    files = crawl_files(FakeClient(), extensions="pdf", max_files=10)
    assert files == [{"path": "2026.05/invoice.pdf", "size": 10}]


def test_run_host_compute_writes_reports(tmp_path: Path) -> None:
    args = argparse.Namespace(
        node_url="http://node",
        start_path=".",
        extensions="pdf",
        max_files=10,
        max_depth=8,
        max_chars=100,
        max_blob_bytes=1000,
        backend="auto",
        timeout=10,
        output_dir=str(tmp_path),
    )

    def fake_ocr(**kwargs):
        payload = json.loads(kwargs["source_payload_json"])
        assert payload["path"] == "2026.05/invoice.pdf"
        return {
            "ok": True,
            "backend": "text-file",
            "chars": 7,
            "text": "Invoice",
            "source": {"sha256": "abc"},
        }

    result = run_host_compute(args, client=FakeClient(), ocr_func=fake_ocr)
    assert result["ok"] is True
    assert result["ok_count"] == 1
    assert Path(result["reports"]["csv"]).is_file()
