"""CLI `fxhnt bybit-carry-revalidate` — default report and --trustworthy 2-row report on Bybit data (the
venue we trade; Phase 0b venue consolidation retired the Binance-baseline comparison this used to also
render). NO network: the operational DSN points at a temp sqlite db seeded with bybit_features."""
from __future__ import annotations

import math

from typer.testing import CliRunner

from fxhnt.cli import app

_DAY = 86_400


def _seed_carry(store, sym, *, days, funding, turnover, range_frac=0.0, idx=0):
    rows = []
    for d in range(days):
        f = funding + 0.0002 * math.cos(0.5 * d + idx)
        rows.append((d * _DAY, {
            "funding": f, "close": 100.0, "spot_close": 100.0,
            "high": 100.0 * (1 + range_frac), "low": 100.0 * (1 - range_frac),
            "spot_high": 100.0 * (1 + range_frac), "spot_low": 100.0 * (1 - range_frac),
            "turnover": turnover,
        }))
    store.write_features(sym, rows)


def _seed(dsn):
    from fxhnt.adapters.warehouse.timescale_feature_store import TimescaleFeatureStore
    bybit = TimescaleFeatureStore(dsn, table="bybit_features")
    real = {"AAAUSDT": 0.001, "BBBUSDT": 0.001, "CCCUSDT": 0.001,
            "XXXUSDT": -0.001, "YYYUSDT": -0.001, "ZZZUSDT": -0.001}
    for i, (sym, f) in enumerate(real.items()):
        _seed_carry(bybit, sym, days=60, funding=f, turnover=50_000_000.0, range_frac=0.01, idx=i)
    for j in range(10):
        sign = 1.0 if j % 2 == 0 else -1.0
        _seed_carry(bybit, f"N{j:02d}USDT", days=60, funding=sign * 0.0008, turnover=500_000.0, idx=100 + j)
    bybit.close()


def _patch(monkeypatch, tmp_path):
    dsn = f"sqlite:///{tmp_path / 'op.db'}"
    monkeypatch.setenv("FXHNT_OPERATIONAL_DSN", dsn)
    from fxhnt import cli as climod
    climod.get_settings.cache_clear()
    _seed(dsn)
    return dsn


def test_cli_default_report(monkeypatch, tmp_path):
    _patch(monkeypatch, tmp_path)
    res = CliRunner().invoke(app, ["bybit-carry-revalidate"])
    assert res.exit_code == 0, res.output
    assert "Bybit (fee 5.5bp)" in res.output
    assert "Binance" not in res.output


def test_cli_trustworthy_two_row(monkeypatch, tmp_path):
    _patch(monkeypatch, tmp_path)
    res = CliRunner().invoke(app, ["bybit-carry-revalidate", "--trustworthy"])
    assert res.exit_code == 0, res.output
    assert "TRUSTWORTHY" in res.output
    assert "Bybit-naive" in res.output
    assert "Bybit-trustworthy" in res.output
    assert "Binance" not in res.output
    assert "Liquid universe size: 6 symbols" in res.output    # the 6 deep coins
    assert "VERDICT (trustworthy row)" in res.output
