"""CLI `fxhnt bybit-ingest-funding` — universe build + funding ingest into bybit_features. NO network:
the BybitFunding adapter is monkeypatched with a fake, and the operational DSN points at a temp sqlite db."""
from __future__ import annotations

from typer.testing import CliRunner

from fxhnt.cli import app


class _FakeBybit:
    def active_universe(self):
        return ["BTCUSDT", "ETHUSDT"]

    def ever_listed_universe(self, *a, **k):
        return ["BTCUSDT", "ETHUSDT", "LUNAUSDT"]  # +1 delisted

    def funding_history(self, symbol, *, start_ms=None):
        return {19000: 0.0003, 19001: -0.0001}


def _patch(monkeypatch, tmp_path):
    dsn = f"sqlite:///{tmp_path / 'op.db'}"
    monkeypatch.setenv("FXHNT_OPERATIONAL_DSN", dsn)
    monkeypatch.setenv("FXHNT_FEATURE_STORE", "postgres")  # not used directly, but keeps intent clear
    from fxhnt import cli as climod
    climod.get_settings.cache_clear()
    # Inject the fake adapter so no HTTP fires.
    monkeypatch.setattr("fxhnt.adapters.data.bybit_funding.BybitFunding", lambda *a, **k: _FakeBybit())
    return dsn


def test_cli_active_only(monkeypatch, tmp_path):
    dsn = _patch(monkeypatch, tmp_path)
    res = CliRunner().invoke(app, ["bybit-ingest-funding", "--symbols", "all"])
    assert res.exit_code == 0, res.output
    assert "2 symbols (active)" in res.output
    assert "done: 2 symbols, 4 day-rows" in res.output
    assert "oldest date 2022-01-08" in res.output  # epoch_day 19000

    # Verify the rows actually landed in bybit_features (isolated table).
    from fxhnt.adapters.warehouse.timescale_feature_store import TimescaleFeatureStore
    store = TimescaleFeatureStore(dsn, table="bybit_features")
    assert store.crypto_funding_panel() == {
        "BTCUSDT": {19000: 0.0003, 19001: -0.0001},
        "ETHUSDT": {19000: 0.0003, 19001: -0.0001},
    }
    store.close()


def test_cli_include_delisted(monkeypatch, tmp_path):
    _patch(monkeypatch, tmp_path)
    res = CliRunner().invoke(app, ["bybit-ingest-funding", "--symbols", "all", "--include-delisted"])
    assert res.exit_code == 0, res.output
    assert "3 symbols (ever-listed)" in res.output
    assert "LUNAUSDT" in res.output  # the delisted name was ingested (survivorship-free)


def test_cli_explicit_symbols_and_from(monkeypatch, tmp_path):
    _patch(monkeypatch, tmp_path)
    res = CliRunner().invoke(app, ["bybit-ingest-funding", "--symbols", "BTCUSDT", "--from", "2022-01"])
    assert res.exit_code == 0, res.output
    assert "1 symbols (explicit)" in res.output
    assert "floor=2022-01" in res.output


def test_cli_bad_from_month(monkeypatch, tmp_path):
    _patch(monkeypatch, tmp_path)
    res = CliRunner().invoke(app, ["bybit-ingest-funding", "--symbols", "BTCUSDT", "--from", "2022"])
    assert res.exit_code == 1
    assert "must be YYYY-MM" in res.output
