"""Visitor-facing changelog.

Reads the YAML source at `site-ng/data/changelog.yml` and serves the
windowed view to the /changelog route.

The YAML is the source of truth (commits = version history; the repo
push to pair.com = offsite backup). This module's only jobs are:

  1. Load + parse the file (cached on mtime so live edits during dev
     show up without bouncing the server).
  2. Apply the display window: last 30 days OR the 3 most recent
     dates with entries, whichever is more. Prevents the page from
     looking abandoned during a quiet week without truncating real
     recent activity during a busy one.
  3. Expose `newest_date()` / `badge_active()` for the home-page
     "What's new" pill (lights for 48h after a new entry, auto-quiets).

NOT a CMS. Authoring = edit changelog.yml + commit + push, same as
every other source file in this repo.
"""

import hashlib
import json
from datetime import date, timedelta
from pathlib import Path
from typing import Optional

import yaml

_PATH = Path(__file__).resolve().parent.parent / "data" / "changelog.yml"

# Rolling display window — 30 days.
WINDOW_DAYS = 30
# Floor for slow weeks: always show at least this many DATES (not
# calendar days) with content, so a 45-day quiet stretch with one
# recent entry still renders three entries instead of one lonely
# bullet. Counted from `entries` newest-first.
MIN_DATES = 3
# How long the home-page "What's new" pill stays visible after the
# newest entry. 48h is short enough to feel like a real signal (not
# perpetual chrome), long enough that someone who visits daily has
# multiple chances to see it. Per-user dismissal happens client-side
# via localStorage in base.html — once dismissed for a given date,
# the pill stays off for THAT date even if it returns later.
BADGE_DAYS = 2

# In-process cache keyed on file mtime — fast enough that we don't
# need an explicit invalidate hook; saving the file in an editor
# bumps mtime which triggers the reload on the next request.
_cache = {"mtime": 0.0, "entries": []}


def _load():
    """Parse the YAML, normalize bullet shapes, sort newest-first.
    Returns a list of dicts with shape:
      {"date": datetime.date, "changes": [{"tag": str|None, "text": str}, ...]}
    """
    if not _PATH.exists():
        return []
    mtime = _PATH.stat().st_mtime
    if mtime == _cache["mtime"]:
        return _cache["entries"]
    raw = yaml.safe_load(_PATH.read_text()) or []
    out = []
    for entry in raw:
        d = entry.get("date")
        # PyYAML parses bare `date: 2026-05-27` to datetime.date
        # directly; this str fallback is for hand-quoted dates.
        if isinstance(d, str):
            d = date.fromisoformat(d)
        if not isinstance(d, date):
            continue        # skip malformed; don't crash the page
        bullets = []
        for b in (entry.get("changes") or []):
            if isinstance(b, str):
                bullets.append({"tag": None, "text": b})
            elif isinstance(b, dict):
                bullets.append({"tag": (b.get("tag") or None),
                                "text": b.get("text", "")})
        if bullets:        # skip days with no actual content
            # Display newest-first within each day, matching the
            # day-level ordering. Editors still append naturally at the
            # bottom of a day's `changes:` list in the YAML; the loader
            # reverses on read so what you see on /changelog is always
            # "most recent first" all the way down. Mike 2026-05-29:
            # without this, a returning visitor scanning the top of
            # today's section can miss bullets added later in the day.
            bullets.reverse()
            out.append({"date": d, "changes": bullets})
    out.sort(key=lambda e: e["date"], reverse=True)
    _cache["mtime"] = mtime
    _cache["entries"] = out
    return out


def windowed():
    """Entries to render on the public /changelog page.

    Returns the union of (a) everything in the last WINDOW_DAYS days
    and (b) the MIN_DATES most recent entries. In practice for a
    healthy site (a) ⊇ (b); the second clause only matters during
    sustained quiet weeks.
    """
    entries = _load()
    if not entries:
        return []
    cutoff = date.today() - timedelta(days=WINDOW_DAYS)
    in_window = [e for e in entries if e["date"] >= cutoff]
    if len(in_window) >= MIN_DATES:
        return in_window
    return entries[:MIN_DATES]


def newest_date() -> Optional[date]:
    """Newest date in the changelog, or None if empty."""
    entries = _load()
    return entries[0]["date"] if entries else None


def badge_active() -> bool:
    """True for BADGE_DAYS after the newest entry's date — used by
    the home-page "What's new" pill. Client-side localStorage then
    decides whether THIS user has already seen this entry."""
    nd = newest_date()
    if not nd:
        return False
    return (date.today() - nd) <= timedelta(days=BADGE_DAYS)


def badge_token() -> str:
    """Fingerprint of the RECENT changelog content — the value the home-page
    pill stores in localStorage as 'changelog_seen'.

    A bare date can't tell two entries made the SAME day apart, and our
    authoring style folds same-day fixes into the existing bullets in place
    (so neither the date nor an entry count changes). A content hash of the
    entries inside the BADGE_DAYS window does: add a same-day bullet or edit a
    recent one and the token changes, so the pill re-appears. Stable while that
    recent content is unchanged (the badge_active() gate quiets it once it ages
    out). Empty string when there are no entries."""
    if not newest_date():
        return ""
    cutoff = date.today() - timedelta(days=BADGE_DAYS)
    recent = [e for e in _load() if e["date"] >= cutoff]
    payload = [[e["date"].isoformat(),
                [[c.get("tag"), c.get("text")] for c in e["changes"]]]
               for e in recent]
    blob = json.dumps(payload, ensure_ascii=False)
    return hashlib.sha1(blob.encode("utf-8")).hexdigest()[:12]
