"""Fleet orchestrator: a hunter searches a territory, evaluates regime-conditionally, and persists the
regime-specialists it finds — with honest global trial accounting."""
from __future__ import annotations

import numpy as np

from fxhnt.adapters.persistence import DuckDbAnalyticalStore, SqlStrategyStore
from fxhnt.application import FleetOrchestrator, Territory
from fxhnt.config import Settings
from fxhnt.domain.models import AssetClass, Market, PriceSeries


class FakeData:
    name = "fake"

    def fetch(self, market: Market, start=None, end=None) -> PriceSeries:
        rng = np.random.default_rng(sum(ord(c) for c in market.symbol))  # deterministic, uncorrelated
        close = 100.0 * np.cumprod(1.0 + rng.normal(0.001, 0.01, 1600))  # steady uptrend -> trend specialist
        return PriceSeries(market=market, dates=tuple(str(i) for i in range(1600)), close=close)


def test_fleet_finds_persists_specialist_and_counts_trials(tmp_path) -> None:
    settings = Settings(analytical_path=str(tmp_path / "an.duckdb"), operational_dsn=f"sqlite:///{tmp_path / 'f.db'}")
    store = SqlStrategyStore(settings.operational_dsn)
    fleet = FleetOrchestrator(FakeData(), DuckDbAnalyticalStore(settings.analytical_path), store, settings)

    territories = [Territory(name="trend-hunter", kind="trend", markets=["AAA", "BBB"],
                             asset_class=AssetClass.FUTURE, param_grid=[{"window": 100.0}])]
    report = fleet.hunt(territories)

    assert report.candidates_tested == 2
    assert report.global_trials == 2                    # honest accounting
    assert report.specialists_found >= 1                # a steady uptrend yields a trend specialist
    saved = store.list()
    assert saved and saved[0].spec.kind == "trend"
    assert saved[0].specialist_regimes()                # tagged with the regime(s) it works in
    assert any("trend_up" in r for r in saved[0].specialist_regimes())
