"""B3b: `backtest-equity --persist-cockpit` also upserts each construction's verdict into the
cockpit operational DB (FXHNT_OPERATIONAL_DSN) so the dashboard can read it. No network: a
synthetic backtest warehouse + a temp-file sqlite cockpit DSN."""
from __future__ import annotations

import datetime as dt

from typer.testing import CliRunner

from fxhnt.adapters.persistence.forward_nav import ForwardNavRepo
from fxhnt.adapters.warehouse.duckdb_feature_store import DuckDbFeatureStore

_SPD = 86_400


def _build_warehouse(path: str) -> DuckDbFeatureStore:
    store = DuckDbFeatureStore(path)
    start = dt.date(2022, 1, 3)
    n = 520
    drifts = {"AAA": 0.0015, "BBB": 0.0003, "CCC": -0.0010}
    items = []
    members = []
    for sym, dr in drifts.items():
        rows = []
        px = 100.0
        for i in range(n):
            day = start + dt.timedelta(days=i)
            px *= (1.0 + dr)
            ts = (day - dt.date(1970, 1, 1)).days * _SPD
            rows.append((ts, {"adjclose": px, "close": px, "volume": 1_000_000.0}))
        items.append((sym, rows))
        members.append((sym, "NYSE", "2000-01-01", "2026-06-01"))
    store.write_features_bulk(items)
    store.upsert_membership(members)
    return store


def test_cli_persist_cockpit_writes_backtest_summary_rows(tmp_path, monkeypatch) -> None:
    import fxhnt.cli as cli

    wh = str(tmp_path / "wh.duckdb")
    _build_warehouse(wh).close()
    out = tmp_path / "report.json"
    cockpit_dsn = f"sqlite:///{tmp_path / 'cockpit.db'}"

    monkeypatch.setenv("FXHNT_BACKTEST_WAREHOUSE_PATH", wh)
    monkeypatch.setenv("FXHNT_OPERATIONAL_DSN", cockpit_dsn)
    cli.get_settings.cache_clear()
    res = CliRunner().invoke(
        cli.app, ["backtest-equity", "--n", "10", "--out", str(out), "--persist-cockpit"]
    )
    cli.get_settings.cache_clear()

    assert res.exit_code == 0, res.output
    assert out.exists(), "JSON report must still be written"

    # a fresh repo on the same on-disk sqlite file sees the persisted rows
    repo = ForwardNavRepo(cockpit_dsn)
    rows = {r.strategy_id: r for r in repo.all_backtest_summaries()}
    assert set(rows) == {"eqfactor_long", "eqfactor_ls", "eqfactor_tilt"}
    for r in rows.values():
        assert isinstance(r.passed, bool)
        assert isinstance(r.sharpe, float)
