"""`fxhnt fetch` wiring: runs the selected fetchers into the data dir (fetchers monkeypatched — no network)."""
from __future__ import annotations

from typer.testing import CliRunner

from fxhnt import cli

runner = CliRunner()


def test_fetch_crypto_only_invokes_crypto(monkeypatch, tmp_path) -> None:
    calls = {}

    def _fake_crypto(data_dir, **kw):
        calls["crypto"] = data_dir
        return (5, 5)

    def _fake_futures(data_dir, **kw):
        calls["futures"] = data_dir
        return (0, 0, 0.0)

    monkeypatch.setattr(cli, "fetch_crypto_pit", _fake_crypto)
    monkeypatch.setattr(cli, "fetch_futures", _fake_futures)
    res = runner.invoke(cli.app, ["fetch", "--data-dir", str(tmp_path), "--crypto", "--no-futures"])
    assert res.exit_code == 0
    assert calls.get("crypto") == str(tmp_path) and "futures" not in calls


def test_fetch_futures_invokes_futures(monkeypatch, tmp_path) -> None:
    calls = {}

    def _fake_futures(data_dir, **kw):
        calls["futures"] = data_dir
        return (10, 1, 0.3)

    monkeypatch.setattr(cli, "fetch_crypto_pit", lambda data_dir, **kw: (0, 0))
    monkeypatch.setattr(cli, "fetch_futures", _fake_futures)
    monkeypatch.setenv("DATABENTO_API_KEY", "test-key")
    res = runner.invoke(cli.app, ["fetch", "--data-dir", str(tmp_path), "--no-crypto", "--futures"])
    assert res.exit_code == 0 and calls.get("futures") == str(tmp_path)


def test_fetch_futures_without_key_exits_clean(monkeypatch, tmp_path) -> None:
    monkeypatch.delenv("DATABENTO_API_KEY", raising=False)
    monkeypatch.setattr(cli, "fetch_crypto_pit", lambda data_dir, **kw: (0, 0))
    res = runner.invoke(cli.app, ["fetch", "--data-dir", str(tmp_path), "--no-crypto", "--futures"])
    assert res.exit_code == 1
    assert "DATABENTO_API_KEY" in res.output
