"""refresh_nav_summary — MATERIALIZE the bybit book's headline nav-summary (the stats + the pre-rendered curve).

The cockpit Overview + `/paper` headline is the bybit paper book's multi-year backfill record: the figures
`nav_backfill_stats` returns plus the pre-rendered multi-year curve SVG. Those change ONLY when the nav
changes (nightly), yet `_overview_headline` re-read the full ~3650-row paper_nav series and re-ran
stats+curve on EVERY request — a read that spikes under shared-DB contention.

This computes them ONCE, reusing the EXACT same helpers `_overview_headline` uses (`nav_backfill_stats` +
`nav_sparkline`), so the stored headline + curve are byte-for-byte identical to the live compute, and upserts
the result keyed by the nav's latest run_date (the version). The read path serves the stored row when its
version matches the live latest run_date (NO full-nav read), and self-heals — calls this — when it is
missing/stale. The nightly nav-write path also calls this proactively so the first request after a nav
update is already fast.

Materialization (authoritative, refresh-on-data-change + read-path self-heal), NOT a TTL cache."""
from __future__ import annotations

import datetime as dt
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from fxhnt.adapters.persistence.paper_repo import PaperRepo


def refresh_nav_summary(repo: PaperRepo) -> dict[str, Any]:
    """Read `repo`'s full paper_nav series (the bybit book — the repo's sole paper book), compute the headline
    stats + render the multi-year curve via the EXACT helpers `_overview_headline` uses (`nav_backfill_stats`
    + `nav_sparkline`), upsert the result keyed by the nav's latest run_date (the version), and return the
    summary dict.

    This is the ONE place that reads the full nav to build the headline — the read path serves the stored row
    instead. Reused by the read-path self-heal AND the nightly nav-write proactive refresh, so both produce
    identical output. Pure given the repo apart from the single upsert it performs."""
    from fxhnt.adapters.web.charts import nav_sparkline
    from fxhnt.application.nav_stats import nav_backfill_stats

    nav = repo.nav_history()
    equities = [p.equity for p in nav]
    stats = nav_backfill_stats(equities)
    # The SAME multi-year curve _overview_headline renders today (width=600, height=160), byte-for-byte.
    curve = nav_sparkline(equities, width=600, height=160) if len(equities) > 1 else ""
    payload: dict[str, Any] = {
        "nav_run_date": nav[-1].run_date if nav else "",   # the version: the nav's latest run_date
        "final_equity": stats.final_equity,
        "total_return_pct": stats.total_return_pct,
        "sharpe": stats.sharpe,
        "max_dd_pct": stats.max_dd_pct,
        "since": nav[0].run_date[:4] if nav else "",        # the backfill's first year, e.g. "2021"
        "has_record": len(equities) >= 2,
        "curve_svg": curve,
    }
    repo.upsert_nav_summary(payload, at=dt.datetime.now(dt.UTC))
    return payload
