"""DashboardService — reads the cockpit DB into view-models. Every registry entry appears in the fleet even
with no data yet (shown as 0 days / WAIT), so the cockpit never hides a tracker just because its first
ingest has not landed."""
from __future__ import annotations

from fxhnt.adapters.persistence.forward_nav import ForwardNavRepo
from fxhnt.application.periods import PERIODS, aggregate
from fxhnt.ports.dashboard import FleetRow, StrategyDetail


class DashboardService:
    def __init__(self, repo: ForwardNavRepo) -> None:
        self._repo = repo

    def fleet(self) -> list[FleetRow]:
        summaries = {r.strategy_id: r for r in self._repo.all_summaries()}
        out: list[FleetRow] = []
        for reg in self._repo.registry():
            s = summaries.get(reg.strategy_id)
            out.append(FleetRow(
                strategy_id=reg.strategy_id, display_name=reg.display_name, sleeve=reg.sleeve,
                days=s.days if s else 0,
                total_return_pct=100.0 * s.total_return if s else 0.0,
                sharpe=s.sharpe if s else 0.0, maxdd=s.maxdd if s else 0.0,
                gate_status=s.gate_status if s else "WAIT",
                gate_reason=s.gate_reason if s else "no data yet",
                as_of=s.as_of if s else "",
            ))
        return out

    def detail(self, strategy_id: str) -> StrategyDetail | None:
        reg = {r.strategy_id: r for r in self._repo.registry()}.get(strategy_id)
        if reg is None:
            return None
        s = {r.strategy_id: r for r in self._repo.all_summaries()}.get(strategy_id)
        history = self._repo.nav_history(strategy_id)
        dates = [p.date for p in history]
        rets = [p.ret for p in history]
        periods = {p: aggregate(dates, rets, p) for p in PERIODS}   # raw daily/weekly/monthly, no normalization
        return StrategyDetail(
            strategy_id=strategy_id, display_name=reg.display_name, sleeve=reg.sleeve, venue=reg.venue,
            days=s.days if s else 0, total_return_pct=100.0 * s.total_return if s else 0.0,
            sharpe=s.sharpe if s else 0.0, maxdd=s.maxdd if s else 0.0,
            gate_status=s.gate_status if s else "WAIT",
            gate_reason=s.gate_reason if s else "no data yet", as_of=s.as_of if s else "",
            history=history, periods=periods,
        )
