"""Daily word-count tracking — derived from the existing transcripts index.

We don't keep a separate usage database. Every dictation already saves an entry
in transcripts/index.json with the full `text` field. `words_used_today()` walks
today's entries, splits each on whitespace, and sums. Cheap (~ms) for thousands
of entries, no schema migration, no second source of truth that can drift.

Reset is at local midnight: an entry's day is `entry["day"]` which is already
"YYYY-MM-DD" in local time (Store.append_transcript uses datetime.now()).
"""

from __future__ import annotations

import re
from datetime import datetime

from .store import Store

_WORD_RE = re.compile(r"\S+")


def count_words(text: str) -> int:
    """Whitespace-separated token count. Matches how most dictation tools count
    (Wispr, Aqua) — punctuation attached to a word doesn't split it, but standalone
    punctuation also doesn't count as a word. Good enough for cap enforcement."""
    if not text:
        return 0
    return len(_WORD_RE.findall(text))


def words_used_today(store: Store, today: str | None = None) -> int:
    """Sum word counts from all transcript entries dated today (local).
    Pass `today` (YYYY-MM-DD) to override the date, e.g. for tests."""
    today = today or datetime.now().strftime("%Y-%m-%d")
    total = 0
    for entry in store.index():
        if entry.get("day") != today:
            continue
        total += count_words(entry.get("text", ""))
    return total
