from __future__ import annotations

import argparse
import csv
from pathlib import Path

from move_no_invoice import classify_no_invoice, move_candidates


def test_classify_no_invoice_is_conservative() -> None:
    assert classify_no_invoice({"ok": "True", "path": "a.pdf", "preview": "Regulamin usług"}) == (
        True,
        "non_invoice_marker:regulamin",
    )
    assert classify_no_invoice({"ok": "True", "path": "a.pdf", "preview": "Faktura VAT"}) == (
        False,
        "invoice_marker:faktura",
    )
    assert classify_no_invoice({"ok": "False", "path": "a.pdf", "preview": "Regulamin"}) == (
        False,
        "ocr_not_ok",
    )


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

    def run(self, uri, payload):
        self.calls.append((uri, payload))
        return {"result": {"value": {
            "ok": True,
            "dryRun": payload["dry_run"],
            "moved": not payload["dry_run"],
            "target": "no_invoice/" + payload["path"],
        }}}


def write_input(path: Path) -> None:
    with path.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=["path", "ok", "preview"])
        writer.writeheader()
        writer.writerow({"path": "a.pdf", "ok": "True", "preview": "Regulamin usług"})
        writer.writerow({"path": "b.pdf", "ok": "True", "preview": "Faktura VAT"})


def test_move_candidates_dry_run_and_execute(tmp_path: Path) -> None:
    input_csv = tmp_path / "files.csv"
    write_input(input_csv)
    args = argparse.Namespace(
        node_url="http://node",
        input_csv=str(input_csv),
        output_dir=str(tmp_path),
        target_dir="no_invoice",
        move_uri="fs://host/file/command/move_to_dir",
        timeout=10,
        execute=False,
    )
    dry = move_candidates(args, client=FakeClient())
    assert dry["candidate_count"] == 1
    assert dry["moved_count"] == 0

    args.execute = True
    moved = move_candidates(args, client=FakeClient())
    assert moved["candidate_count"] == 1
    assert moved["moved_count"] == 1
