"""Tests for CLI bulk subcommand."""

from __future__ import annotations

import json
import tempfile
from pathlib import Path
from unittest.mock import patch

import pytest

from orxaq.experiences.cli import main as cli_main


def _make_jsonl(records: list[dict]) -> str:
    """Write records as JSON-lines to a temp file, return path."""
    f = tempfile.NamedTemporaryFile(
        mode="w", suffix=".jsonl", delete=False
    )
    for r in records:
        f.write(json.dumps(r) + "\n")
    f.close()
    return f.name


@pytest.fixture()
def jsonl_file():
    """Create a small JSON-lines input file."""
    records = [{"id": i, "value": i * 10} for i in range(20)]
    path = _make_jsonl(records)
    yield path
    Path(path).unlink(missing_ok=True)


class TestBulkRun:
    def test_run_json(self, jsonl_file, capsys):
        with patch("sys.argv", [
            "orxaq", "--json", "bulk", "run", "--input", jsonl_file,
        ]):
            rc = cli_main()
        assert rc == 0
        out = json.loads(capsys.readouterr().out)
        assert out["result_count"] == 20
        assert out["error_count"] == 0

    def test_run_text(self, jsonl_file, capsys):
        with patch("sys.argv", [
            "orxaq", "bulk", "run", "--input", jsonl_file,
        ]):
            rc = cli_main()
        assert rc == 0
        out = capsys.readouterr().out
        assert "Processed: 20" in out
        assert "Succeeded: 20" in out

    def test_run_threaded(self, jsonl_file, capsys):
        with patch("sys.argv", [
            "orxaq", "--json", "bulk", "run",
            "--input", jsonl_file, "--workers", "2",
        ]):
            rc = cli_main()
        assert rc == 0
        out = json.loads(capsys.readouterr().out)
        assert out["result_count"] == 20

    def test_run_missing_input(self, capsys):
        with patch("sys.argv", ["orxaq", "bulk", "run", "--input", "/nonexistent.jsonl"]):
            rc = cli_main()
        assert rc == 1


class TestBulkDryRun:
    def test_dry_run_json(self, jsonl_file, capsys):
        with patch("sys.argv", [
            "orxaq", "--json", "bulk", "dry-run",
            "--input", jsonl_file, "--sample-size", "5",
        ]):
            rc = cli_main()
        assert rc == 0
        out = json.loads(capsys.readouterr().out)
        assert out["sample_size"] == 5
        assert out["total_records"] == 20

    def test_dry_run_text(self, jsonl_file, capsys):
        with patch("sys.argv", [
            "orxaq", "bulk", "dry-run", "--input", jsonl_file,
        ]):
            rc = cli_main()
        assert rc == 0
        out = capsys.readouterr().out
        assert "Dry run:" in out
        assert "Est. error rate:" in out

    def test_dry_run_missing_input(self, capsys):
        with patch("sys.argv", [
            "orxaq", "bulk", "dry-run", "--input", "/nonexistent.jsonl",
        ]):
            rc = cli_main()
        assert rc == 1
