"""DashboardService turns DB rows into view-models: a fleet overview (registry joined to summary) and a
per-strategy detail (summary + nav history)."""
from __future__ import annotations

import datetime as dt

from fxhnt.adapters.persistence.forward_nav import ForwardNavRepo
from fxhnt.application.dashboard_service import DashboardService
from fxhnt.application.forward_models import ForwardNavRow as Row
from fxhnt.application.forward_models import ForwardSummary


def _seeded() -> ForwardNavRepo:
    repo = ForwardNavRepo("sqlite://")
    repo.migrate()
    at = dt.datetime(2026, 6, 14, 23, 30)
    repo.upsert_rows([Row("combined", "2026-06-05", 0.01, 1.01),
                      Row("combined", "2026-06-06", 0.0099, 1.0201)], at)
    repo.upsert_summary(ForwardSummary("combined", "2026-06-06", 2, 1.0201, 0.0201, 1.2, -0.01),
                        "WAIT", "2/20 forward days", at)
    return repo


def test_fleet_joins_registry_to_summary() -> None:
    svc = DashboardService(_seeded())
    fleet = svc.fleet()
    combined = next(f for f in fleet if f.strategy_id == "combined")
    assert combined.display_name.startswith("Combined book")
    assert combined.days == 2 and combined.gate_status == "WAIT"
    assert round(combined.total_return_pct, 2) == 2.01


def test_fleet_includes_registry_entries_without_data() -> None:
    svc = DashboardService(_seeded())
    fleet = svc.fleet()
    funding = next(f for f in fleet if f.strategy_id == "funding")
    assert funding.days == 0 and funding.gate_status == "WAIT"   # no data yet -> shown, not errored


def test_detail_returns_summary_and_history() -> None:
    svc = DashboardService(_seeded())
    detail = svc.detail("combined")
    assert detail is not None
    assert detail.display_name.startswith("Combined book")
    assert [p.date for p in detail.history] == ["2026-06-05", "2026-06-06"]


def test_detail_includes_raw_period_aggregations() -> None:
    svc = DashboardService(_seeded())
    detail = svc.detail("combined")
    assert set(detail.periods) == {"daily", "weekly", "monthly"}
    assert [p.label for p in detail.periods["daily"]] == ["2026-06-05", "2026-06-06"]
    assert abs(detail.periods["daily"][0].ret - 0.01) < 1e-9   # raw, not normalized
    assert all(p.label.startswith("2026") for p in detail.periods["monthly"])


def test_detail_unknown_strategy_is_none() -> None:
    svc = DashboardService(_seeded())
    assert svc.detail("does-not-exist") is None
