"""Checked-in registry of paper-forward trackers — maps each technical tracker to what the user sees plus
its Phase-1 gate thresholds. SINGLE SOURCE OF TRUTH for the cockpit: add a strategy = ONE entry here
(id, display_name, venue, tier, execution, gate_spec) [+ a state_reader case if a new state
shape]; the cockpit renders it automatically (deploy/research grouped by `tier`, paper/live badge by
`execution`).

Two SSOT fields drive the operational console grouping:
  tier        — "deploy" (the live fund: the Bybit 4-edge book + its standalone deploy sleeves) or
                "research" (paper trackers that are NOT the fund — shown dimmed/secondary).
  execution   — "paper" or "live": the execution mode badge shown on every track (all "paper" today)."""
from __future__ import annotations

from typing import Any

from fxhnt.domain.strategies.multistrat import FUND_INSTRUMENTS

# gate_spec keys:
#   gate_type           — "absolute" (legacy: WAIT min_days, then GO/NO_GO on return+Sharpe) or
#                         "reconciliation" (WAIT ~2wk, then PASS iff forward reconciles with the backtest +
#                         clean execution). The reconciliation gate REPLACES the blind 60-day calendar wait:
#                         a 5y backfill is in-sample, so the forward track is the only true OOS check, and the
#                         real signal (does forward track the backtest? did the pipeline run clean?) lands in
#                         ~2 weeks — 60 days add ~no statistical power.
#   absolute gate       — min_days, min_total_return (fraction), min_sharpe.
#   reconciliation gate — min_forward_days (~14), recon_tolerance_frac, recon_min_band, recon_min_corr.
STRATEGY_REGISTRY: dict[str, dict[str, Any]] = {
    # RETIRED 2026-07-11: "combined" (crypto-momentum vestigial trend overlay, venue legacy+glbx) — the
    # broad-legacy-venue-universe momentum book was a survivorship/microcap mirage (see
    # pearl_fxhnt_measured_cost_mirage_and_postgres); superseded by the isolated crypto_tstrend edge (clean
    # long/flat trend, gate PASS) + the bybit_4edge book. Removed from the nightly + registry; the DB
    # registry row auto-prunes via _seed_registry. CombinedBook modules retained (still used by the CLI +
    # migration_builders).
    # NOTE: the absolute-hurdle "funding" track was RETIRED 2026-06-20 (idle ~60% of days, flat 2022);
    # the canonical funding deploy is the cross-sectional "xsfunding" below (harvests dispersion, always
    # active, +71% in the 2022 backtest). The faithful-port harness stays in paper_strategies.py.
    # RETIRED 2026-06-20: multistrat/gd (futures premia — falsified, scale-gated) + poc (old crypto PoC,
    # superseded) + eqfactor_long/eqfactor_tilt (US-equity factors — weakly-held, edge never established;
    # kept only as a non-crypto experiment, now retired as unproven). Strategy classes stay in
    # equity_factor_strategy.py / paper_strategies.py. _seed_registry prunes stale rows automatically.
    # Cockpit now = 2 validated crypto edges (xsfunding, unlock) + crypto-momentum book + 60/40 benchmark.
    "sixtyforty": {
        "display_name": "60/40 baseline", "sleeve": "beta",
        "venue": "glbx",
        "tier": "research", "execution": "paper",
        "gate_spec": {"min_days": 20, "min_total_return": 0.0, "min_sharpe": 0.0},
        # DOCUMENTED spec §4 PIT exemption: this track is `record_mode="recompute"` but SixtyFortyStrategy
        # reads live Tiingo adjClose (retroactively revised on corporate actions), not a PIT snapshot. It is
        # a pure 60/40 BENCHMARK reference line (research tier, loose absolute gate, no capital) — not an
        # edge — so full PIT-snapshotting is out of scope; adjClose revisions are immaterial to the reference
        # line. This is a deliberate, documented exemption, not silent drift. See SixtyFortyStrategy docstring.
        "definition": {"params": {"weights": [["SPY", 0.6], ["IEF", 0.4]], "source": "tiingo-adjclose"},
                       "version": 1, "record_mode": "recompute", "backtest": {"kind": "none"}},
    },
    # Phase 0b venue consolidation: this track moved OFF the standalone legacy-venue `XsFundingForward`
    # construction onto its OWN Bybit single-sleeve forward track (venue-consistent
    # with where xsfunding is actually deployed — it already runs as a sleeve inside the `bybit_4edge` deploy
    # book, unchanged). Records the SINGLE xsfunding sleeve's daily return on `bybit_features` (the same
    # `sleeve_returns_from_store` runner the book uses) via `BybitFourEdgeStrategy(sleeves=["xsfunding"])` —
    # mirrors `positioning`'s single-sleeve construction exactly (`report`-kind ref from the weekly Bybit book
    # persist, `record_mode="recompute"` through the deterministic engine).
    "xsfunding": {
        "display_name": "Crypto funding harvest (cross-sectional, delta-neutral)", "sleeve": "crypto-funding",
        "venue": "bybit-perp",
        "tier": "research", "execution": "paper",
        # NO `promote_on_pass` (reverted 2026-07-16, plan `2026-07-16-book-representation-and-venue-cap.md`
        # Task A): this sleeve is a CONSTITUENT of the `bybit_4edge` deploy book, not a standalone deploy
        # edge — auto-promoting it would double-count the book.
        "gate_spec": {"gate_type": "reconciliation", "min_forward_days": 14},
        # cost_bps mirrors Settings.bybit_cost_bps; a cost change requires a definition_version bump
        # to re-inception (else the hashed audit silently diverges from the cost actually charged).
        # inception_t0 pins the pre-Phase-0b-re-home OOS start (recovered 2026-07-15) so a DB rebuild reproduces
        # the window from git, not today; version-scoped + NOT hashed — see forward_definition.inception_override.
        "definition": {"params": {"sleeve": "xsfunding", "cost_bps": 5.5}, "version": 2, "record_mode": "recompute",
                       "inception_t0": {"date": "2026-07-07", "version": 2}, "backtest": {"kind": "report"}},
    },
    # Phase 0b venue consolidation (Task 2): this track moved OFF the standalone legacy-venue
    # `UnlockShortForward` construction onto its OWN Bybit single-sleeve forward
    # track (venue-consistent with where unlock is actually deployed — it already runs as a sleeve inside
    # the `bybit_4edge` deploy book, unchanged). Records the SINGLE unlock sleeve's daily return on
    # `bybit_features` (the same `sleeve_returns_from_store` runner the book uses) via
    # `BybitFourEdgeStrategy(sleeves=["unlock"], unlock_events=...)` — mirrors `xsfunding`'s/`positioning`'s
    # single-sleeve construction exactly (`report`-kind ref from the weekly Bybit book persist,
    # `record_mode` was already "recompute" here, unlike xsfunding's pre-migration "observed").
    "unlock": {
        "display_name": "Token-unlock dilution shorts (market-neutral)", "sleeve": "crypto-event",
        "venue": "bybit-perp",
        "tier": "research", "execution": "paper",
        # NO `promote_on_pass` (reverted 2026-07-16, plan `2026-07-16-book-representation-and-venue-cap.md`
        # Task A): same constituent-of-the-book rationale as xsfunding above.
        "gate_spec": {"gate_type": "reconciliation", "min_forward_days": 14},
        # cost_bps mirrors Settings.bybit_cost_bps; a cost change requires a definition_version bump
        # to re-inception (else the hashed audit silently diverges from the cost actually charged).
        "definition": {"params": {"sleeve": "unlock", "cost_bps": 5.5}, "version": 2, "record_mode": "recompute",
                       "inception_t0": {"date": "2026-06-20", "version": 2},  # pre-re-home OOS start (see xsfunding)
                       "backtest": {"kind": "report"}},
    },
    # RETIRED 2026-07-13 (Phase 0b Task 4): "crypto_tstrend" standalone legacy-venue-perp TS-momentum forward
    # track — a −0.21 marginal-Sharpe drag/crash-amplifier as a standalone edge (see
    # pearl_fxhnt_measured_cost_mirage_and_postgres). The `crypto_tstrend` SLEEVE inside the `bybit_4edge`
    # deploy book (Bybit data, `_DEFAULT_BYBIT_SLEEVES`) is a SEPARATE live edge — untouched.
    # TradFi diversifier — UNCORRELATED to the crypto edges (that is its value: combining a modest-Sharpe
    # equity book with the crypto book raises the portfolio Sharpe). Tracked on Yahoo daily-adjusted NAV;
    # executes on IBKR paper (5 whole-share ETFs; the prior fractional-broker leg was decommissioned —
    # Phase 0b Task 5, IBKR is the sole equity executor). 20-day reconciliation gate.
    "multistrat": {
        "display_name": "ETF Portfolio",
        "sleeve": "tradfi-multistrat", "venue": "ibkr-equity",
        "tier": "research", "execution": "paper",
        # weekday-only equity NAV → Fri→Mon (3d) / holiday (≤4d) steps are NORMAL, not gaps.
        "gate_spec": {"gate_type": "reconciliation", "min_forward_days": 20, "max_gap_days": 4},
        # AUTO-PROMOTE research→deploy once the gate PASSes: its diversification vs the crypto book was
        # validated out-of-band (measured +0.284 daily-return corr over 437d → a real diversifier, combined
        # Sharpe ≈2.06 > 1.8). The nightly flips the tier on PASS (see forward_ingest.evaluate_promotions).
        "promote_on_pass": True,
        # instruments derive from multistrat.FUND_INSTRUMENTS (not a copy) — editing that list alone must
        # change the hash (and re-inception), not silently change forward returns under an unchanged hash.
        "definition": {"params": {"instruments": list(FUND_INSTRUMENTS), "maxlev": 1.0,
                                  "source": "yahoo-pit"}, "version": 1, "record_mode": "recompute",
                       "backtest": {"kind": "recompute-replay"}},
    },
    # OBSERVE-ONLY levered shadow of `multistrat`: the SAME risk-parity ETF book LEVERED to its own 10% vol
    # target (an unlevered 1x risk-parity book is bond-heavy and sits ~5.7% vol — under its target, leaving
    # return on the table), MINUS the honest financing drag on the borrowed leg. Return-defined, NEVER
    # executed, NO promote_on_pass — a what-if preview of levered risk-parity (cf. `bybit_4edge_levered`).
    # `financing_bps` = the annual USD financing rate charged on the (L-1) borrowed leg — GROUNDED in IBKR's
    # real USD margin schedule (verified 2026-07-18): Fed funds effective 3.63% + IBKR Pro's tiered spread →
    # ~5.83% tier-1 (<$100k), ~5.3% at $100k-1M; the account is ~$1M so 530 bps is the dominant-tier rate.
    # The cockpit shows the FULL sensitivity BAND (100..683 bps) + the break-even, so the verdict is never
    # hostage to this single number. The moat is CHEAP financing — deliberately modelled, not assumed free.
    "multistrat_levered": {
        "display_name": "ETF Portfolio (levered shadow)",
        "sleeve": "tradfi-multistrat", "venue": "ibkr-equity",
        "tier": "research", "execution": "paper",
        "gate_spec": {"gate_type": "reconciliation", "min_forward_days": 20, "max_gap_days": 4},
        "definition": {"params": {"base": "multistrat", "target_vol": 0.10, "max_leverage": 2.0,
                                  "financing_bps": 530.0, "source": "yahoo-pit"},
                       "version": 1, "record_mode": "recompute", "backtest": {"kind": "recompute-replay"}},
    },
    # The EXECUTED multistrat book (sub-project C1): the real IBKR-paper track — its daily return is the
    # executed book's envelope-basis P&L (fills + slippage + fees), recorded by `fxhnt execute-multistrat
    # --execute` (NOT a nightly nav asset). OBSERVED (fills are observed, not recomputable). Its reconciliation
    # gate reconciles the executed track against the MODELED multistrat's basis-matched backtest reference
    # (persisted under sid `multistrat` by the `multistrat_nav` asset) — execution decay shows as the executed
    # forward return falling short of the modeled book's expectation.
    "multistrat_exec": {
        "display_name": "Multi-strat book (EXECUTED, IBKR paper)", "sleeve": "tradfi-multistrat",
        "venue": "ibkr-equity",
        "tier": "research", "execution": "paper",
        "gate_spec": {"gate_type": "reconciliation", "min_forward_days": 20, "max_gap_days": 4},
        "definition": {"params": {"source": "ibkr-equity-fills", "models": "multistrat"},
                       "version": 1, "record_mode": "observed", "backtest": {"kind": "model-ref"}},
    },
    # RETIRED 2026-07-13 (Phase 0b Task 4): "stablecoin_rotation" (legacy-venue-spot peg-reversion forward
    # track) — FDUSD/USDP aren't listed on Bybit, doesn't port to the venue. `StableReversionRunner` itself
    # (stablecoin_runner.py) stays — it is still live via `bybit_stablecoin_eval.py` / `bybit_edges_eval.py`
    # / `bybit_book_eval.py` (Bybit-native stablecoin evaluation, a separate consumer of the runner core).
    # Forward PAPER TRACK for the 4-edge Bybit book — the OUT-OF-SAMPLE record on the venue we'll actually
    # trade. Records the NAIVE equal-weight 4-sleeve book (tstrend/unlock/xsfunding/positioning) on
    # `bybit_features` (the live risk overlay over-levers on Bybit; that is a separate re-tune, deliberately
    # NOT this track). RECONCILIATION gate: WAIT ~2 weeks, then PASS iff the forward track reconciles with
    # the backtest (does not diverge/contradict it) and executed cleanly.
    # DEPLOY TARGET again (reverted 2026-07-16, plan `2026-07-16-book-representation-and-venue-cap.md` Task
    # A): the fund's deployed crypto book — a risk-parity aggregate of its sleeves. An in-cluster measurement
    # showed the intervening per-sleeve allocation collapses to `positioning` alone (~18% deployed) while
    # this diversified book deploys 75% at LOWER risk (vol 0.0523, maxDD -0.0324, funding-stress-checked).
    # Its constituents (`positioning`/`xsfunding`/`unlock`) are tracked separately as research-tier reference
    # (gate_spec/definition/inception_t0 unchanged; only `tier` moved).
    "bybit_4edge": {
        "display_name": "Bybit 4-edge book", "sleeve": "crypto-bybit",
        "venue": "bybit-perp",
        "tier": "deploy", "execution": "paper",
        # min_forward_days 21 (not 14): this book's gains arrive in irregular clusters (median ~17 days between
        # big +days), so a lumpy edge needs a slightly longer window to be representative before the gate rules.
        "gate_spec": {"gate_type": "reconciliation", "min_forward_days": 21},
        # cost_bps mirrors Settings.bybit_cost_bps; a cost change requires a definition_version bump
        # to re-inception (else the hashed audit silently diverges from the cost actually charged).
        "definition": {"params": {"sleeves": ["tstrend", "unlock", "xsfunding", "positioning"], "weighting": "naive-eq",
                                  "cost_bps": 5.5}, "version": 3, "record_mode": "recompute",
                       "inception_t0": {"date": "2026-07-06", "version": 3},  # v3: coin_gross_cap=0.07 backfill
                       "backtest": {"kind": "report"}},
    },
    # The EXECUTED 4-edge book (sub-project C2): the real Bybit-TESTNET track — its daily return is the
    # executed book's envelope-basis P&L (fills + slippage + funding - fees), recorded by the
    # `execute-bybit` CLI command (run_bybit_testnet). OBSERVED (fills are observed, not recomputable). Its gate
    # reconciles the executed track against the MODELED bybit_4edge via the ref-provider alias (execution
    # decay shows as divergence). min_forward_days 21 mirrors the modeled book's window; crypto is 24/7 so
    # the default max_gap_days (1) applies.
    "bybit_4edge_exec": {
        "display_name": "Bybit 4-edge book (EXECUTED, testnet)", "sleeve": "crypto-bybit",
        "venue": "bybit-testnet",
        "tier": "research", "execution": "paper",
        "gate_spec": {"gate_type": "reconciliation", "min_forward_days": 21},
        "definition": {"params": {"source": "bybit-testnet-fills", "models": "bybit_4edge"},
                       "version": 1, "record_mode": "observed", "backtest": {"kind": "model-ref"}},
    },
    # OBSERVE-ONLY shadow of bybit_4edge under STATIC differentiated leverage (carry-weighted, book-gross
    # <= 1.5x). Records what the levered book WOULD do so we can validate it OOS before any capital rides it
    # (Phase 1 of the 2026-07-03 leverage spec). Same reconciliation gate as the naive book.
    "bybit_4edge_levered": {
        "display_name": "Bybit 4-edge book (levered shadow, <=1.5x)", "sleeve": "crypto-bybit",
        "venue": "bybit-perp",
        "tier": "research", "execution": "paper",
        "gate_spec": {"gate_type": "reconciliation", "min_forward_days": 21},
        # cost_bps mirrors Settings.bybit_cost_bps; a cost change requires a definition_version bump
        # to re-inception (else the hashed audit silently diverges from the cost actually charged).
        "definition": {"params": {"sleeves": ["tstrend", "unlock", "xsfunding", "positioning"],
                                  "weighting": "carry-static", "gross_max": 1.5, "cost_bps": 5.5},
                       "version": 3, "record_mode": "recompute",
                       "inception_t0": {"date": "2026-07-06", "version": 3},  # v3: coin_gross_cap=0.07 backfill
                       "backtest": {"kind": "report"}},
    },
    # The positioning sleeve (contrarian long/short-account-ratio) as its OWN forward-tracked edge — the
    # standout constituent of the Bybit 4-edge book (uncorrelated with the other three). Records the SINGLE
    # positioning sleeve's daily return on `bybit_features` (the same `sleeve_returns_from_store` runner the
    # book uses). RECONCILIATION gate (~2wk + reconciles-with-backtest + clean); starts its OOS record now.
    # `tier` reverted to `research` 2026-07-16 (plan `2026-07-16-book-representation-and-venue-cap.md` Task
    # A): a constituent of the `bybit_4edge` deploy book, not a standalone deploy edge — still forward-tracked
    # as reference.
    "positioning": {
        "display_name": "Positioning (contrarian long/short ratio)", "sleeve": "crypto-bybit",
        "venue": "bybit-perp",
        "tier": "research", "execution": "paper",
        "gate_spec": {"gate_type": "reconciliation", "min_forward_days": 14},
        # cost_bps mirrors Settings.bybit_cost_bps; a cost change requires a definition_version bump
        # to re-inception (else the hashed audit silently diverges from the cost actually charged).
        "definition": {"params": {"sleeve": "positioning", "cost_bps": 5.5}, "version": 3, "record_mode": "recompute",
                       "inception_t0": {"date": "2026-07-06", "version": 3},  # v3: coin_gross_cap=0.07 backfill
                       "backtest": {"kind": "report"}},
    },
    # NOTE: `xvenue_carry` (cross-venue Bybit↔Deribit static carry) was RETIRED from forward-tracking
    # 2026-07-07 — a validated-but-not-live edge with ~0 contribution in its current form, cluttering the
    # gate/cockpit. The cross_venue_carry_eval research lib + the deribit_funding_bars ingestion are KEPT
    # (data stays warm) so the edge can be revived if cross-venue execution is ever run.
    # See pearl_fxhnt_voltarget_overlay_is_reactive_desizing_rejected (same session's cleanup).
}
