import logging
import os

from fxhnt.application.bybit_forward_track import (
    POSITIONING_COIN_GROSS_CAP,
    POSITIONING_TAIL_CAP_K,
    bybit_4edge_backtest_summary,
    bybit_report_sid_kwargs,
)
from fxhnt.application.bybit_liquidity import liquid_universe
from fxhnt.application.unlock_calendar_loader import load_unlock_events, operational_unlock_repo
from fxhnt.config import get_settings

log = logging.getLogger(__name__)


def _data_dir() -> str:
    return os.environ.get("FXHNT_SURFER_DATA_DIR", "/data/surfer")


# The three report-kind sids and how they differ — identity kwargs single-sourced from
# `bybit_report_sid_kwargs` (bybit_forward_track.py), shared with cli.py's `_persist_bybit_book`.
_REPORT_SIDS = ("bybit_4edge", "bybit_4edge_levered", "positioning")


def report_backtest_summary(strategy_id, store):  # -> BacktestSummary | None
    """Backtest ref for a `report`-kind bybit strategy: dispatch to the real book engine
    `bybit_4edge_backtest_summary` with the per-sid kwargs. Reconstructs the liquid universe, unlock
    calendar, and positioning capturability haircuts + per-coin gross cap internally (from the store +
    settings) so the ref reconciles against the SAME capturable book the forward track records. cost_bps=5.5
    matches the live BybitFourEdge basis and the `sleeve` kind. Built from the store (sleeve_returns=None) so
    the positioning haircut + coin_gross_cap kwargs are applied by the engine."""
    if strategy_id not in _REPORT_SIDS:
        raise ValueError(f"report_backtest_summary: {strategy_id!r} is not a report-kind sid {_REPORT_SIDS}")
    settings = get_settings()
    universe = liquid_universe(store, min_dollar_vol=10_000_000.0) or None
    try:
        unlock_events = load_unlock_events(
            operational_unlock_repo(settings), f"{_data_dir()}/unlock_calendar.json")
    except Exception as exc:  # noqa: BLE001 — absent calendar → unlock sleeve omitted, never fabricated
        log.warning("report_backtest_summary(%s): could not load unlock calendar: %s", strategy_id, exc)
        unlock_events = []
    common = dict(
        universe=universe, cost_bps=5.5,
        positioning_capacity_capital=settings.paper_capital,
        positioning_tail_cap_k=POSITIONING_TAIL_CAP_K,
        positioning_coin_gross_cap=POSITIONING_COIN_GROSS_CAP)
    # unlock_events is always passed: the positioning sleeve construction (both here and in
    # `_persist_bybit_book`) ignores it entirely, so unifying to always-pass is a no-op for that sid — see
    # `bybit_report_sid_kwargs`.
    return bybit_4edge_backtest_summary(
        store, unlock_events=unlock_events, **common, **bybit_report_sid_kwargs(strategy_id))
