"""Strategy-lifecycle store: upsert/get/list by status & regime, status transitions, global trial count."""
from __future__ import annotations

import datetime as dt

from fxhnt.adapters.persistence import SqlStrategyStore
from fxhnt.domain.factory import RegimeFit, StrategyRecord, StrategyStatus, strategy_id
from fxhnt.domain.models import AssetClass, StrategySpec

_NOW = dt.datetime(2026, 6, 9, tzinfo=dt.timezone.utc)


def _record(markets: list[str], regimes_passed: list[str]) -> StrategyRecord:
    spec = StrategySpec(kind="trend", params={"window": 200.0})
    fits = [RegimeFit(regime=r, dsr=0.97, is_sharpe=1.3, oos_sharpe=0.9, passed=True) for r in regimes_passed]
    fits.append(RegimeFit(regime="range|low_vol", dsr=0.6, is_sharpe=0.5, oos_sharpe=0.2, passed=False))
    return StrategyRecord(
        strategy_id=strategy_id(markets, AssetClass.FUTURE, spec), markets=markets,
        asset_class=AssetClass.FUTURE, spec=spec, regime_fits=fits,
        discovered_at=_NOW, updated_at=_NOW, n_trials_at_discovery=12, source="trend-hunter",
    )


def test_upsert_get_roundtrip_and_specialist_regimes(tmp_path) -> None:
    store = SqlStrategyStore(f"sqlite:///{tmp_path / 'factory.db'}")
    rec = _record(["NQ", "6E"], ["trend_up|low_vol"])
    store.upsert(rec)
    got = store.get(rec.strategy_id)
    assert got is not None
    assert got.markets == ["NQ", "6E"] and got.spec.kind == "trend"
    assert got.specialist_regimes() == ["trend_up|low_vol"]   # only the passing regime
    assert got.status is StrategyStatus.DISCOVERED


def test_list_by_status_and_regime_plus_transitions(tmp_path) -> None:
    store = SqlStrategyStore(f"sqlite:///{tmp_path / 'factory.db'}")
    a = _record(["NQ", "6E"], ["trend_up|low_vol"])
    b = _record(["GC", "CL"], ["trend_down|high_vol"])
    store.upsert(a)
    store.upsert(b)

    assert len(store.list()) == 2
    assert {r.strategy_id for r in store.list(regime="trend_up|low_vol")} == {a.strategy_id}

    store.set_status(a.strategy_id, StrategyStatus.DEPLOYED)
    deployed = store.list(status=StrategyStatus.DEPLOYED)
    assert [r.strategy_id for r in deployed] == [a.strategy_id]


def test_global_trial_counter(tmp_path) -> None:
    store = SqlStrategyStore(f"sqlite:///{tmp_path / 'factory.db'}")
    assert store.total_trials() == 0
    store.add_trials(10)
    store.add_trials(5)
    assert store.total_trials() == 15
