"""Bug A end-to-end: xsfunding is reconciliation-gated but had NO backtest_summary ref, so the gate returned
the permanent 'no backtest reference to reconcile against' WAIT forever. Tasks 2/6 wired the ref. This proves
the un-sticking at the REAL seam the nightly ingest uses: CockpitBacktestRefProvider (reads backtest_summary
rows) -> evaluate_reconciliation_gate. Ref present => the gate reconciles; ref absent => the no-ref WAIT."""
import datetime as dt

from fxhnt.adapters.persistence.forward_nav import ForwardNavRepo
from fxhnt.application.forward_ingest import CockpitBacktestRefProvider
from fxhnt.application.forward_models import BacktestSummary, ForwardNavRow, ForwardSummary
from fxhnt.application.gate_policy import POLICY
from fxhnt.application.gate_policy_resolve import resolve_policy
from fxhnt.application.reconciliation_gate import evaluate_reconciliation_gate
from fxhnt.registry import STRATEGY_REGISTRY

_NO_REF = "no backtest reference to reconcile against"


def _policy():
    return resolve_policy(POLICY, STRATEGY_REGISTRY["xsfunding"]["gate_spec"])   # reconciliation, min 14d


def _xsfunding_forward(days: int):
    """A mature (>= min_forward_days), continuous (no gaps), modestly-positive xsfunding forward record."""
    start = dt.date(2026, 6, 1)
    rows = [ForwardNavRow(strategy_id="xsfunding", date=(start + dt.timedelta(days=i)).isoformat(),
                          ret=0.001, nav=1.001 ** (i + 1)) for i in range(days)]
    nav = rows[-1].nav
    summary = ForwardSummary(strategy_id="xsfunding", as_of=rows[-1].date, days=days, nav=nav,
                             total_return=nav - 1.0, sharpe=1.0, maxdd=0.0)
    return summary, rows


def test_xsfunding_gate_stuck_without_ref(tmp_path):
    """Pre-fix state: no backtest_summary row -> provider yields None -> the permanent no-ref WAIT."""
    repo = ForwardNavRepo(f"sqlite:///{tmp_path / 'c.db'}")
    repo.migrate()
    policy = _policy()
    summary, rows = _xsfunding_forward(policy.min_forward_days + 3)
    ref = CockpitBacktestRefProvider(repo).reference("xsfunding", summary.days)
    assert ref is None
    verdict = evaluate_reconciliation_gate(summary, rows, ref, policy)
    assert verdict.status == "WAIT" and _NO_REF in verdict.reason


def test_xsfunding_gate_unsticks_with_ref(tmp_path):
    """Post-fix (Tasks 2/6): a persisted xsfunding backtest_summary -> provider yields a ref -> the gate
    RECONCILES (leaves the no-ref branch entirely; a PASS or a divergence-WAIT both mean 'reconciling')."""
    repo = ForwardNavRepo(f"sqlite:///{tmp_path / 'c.db'}")
    repo.migrate()
    repo.upsert_backtest_summary(
        BacktestSummary(strategy_id="xsfunding", as_of="2026-06-20", cagr=0.35, ann_vol=0.2, sharpe=1.2,
                        max_drawdown=-0.06, passed=True, dsr=0.9, is_sharpe=1.3, oos_sharpe=1.1, pvalue=0.02),
        at=dt.datetime(2026, 6, 20))
    policy = _policy()
    summary, rows = _xsfunding_forward(policy.min_forward_days + 3)
    ref = CockpitBacktestRefProvider(repo).reference("xsfunding", summary.days)
    assert ref is not None and ref.expected_window_return > 0.0
    verdict = evaluate_reconciliation_gate(summary, rows, ref, policy)
    assert _NO_REF not in verdict.reason   # the un-sticking: no longer stuck on a missing backtest ref
