"""Index versioned metadata and enforce a bounded admission rate.

Run with Python 3.10 or newer: python3 09-object-storage-search-rate-limits.py
Uses only local deterministic data. It creates neither cloud objects nor network calls.
"""

import re
from dataclasses import dataclass, field


def terms(text: str) -> set[str]:
    """Lowercase word tokens. Production analyzers have richer language rules."""
    return set(re.findall(r"\w+", text.casefold()))


@dataclass(frozen=True)
class Event:
    object_id: str
    revision: int
    title: str | None  # None means deleted.


@dataclass
class Index:
    revisions: dict[str, int] = field(default_factory=dict)
    by_document: dict[str, set[str]] = field(default_factory=dict)
    postings: dict[str, set[str]] = field(default_factory=dict)

    def apply(self, event: Event) -> bool:
        if event.revision <= self.revisions.get(event.object_id, 0):
            return False

        old_terms = self.by_document.pop(event.object_id, set())
        for token in old_terms:
            self.postings[token].remove(event.object_id)
            if not self.postings[token]:
                del self.postings[token]

        self.revisions[event.object_id] = event.revision
        if event.title is not None:
            new_terms = terms(event.title)
            self.by_document[event.object_id] = new_terms
            for token in new_terms:
                self.postings.setdefault(token, set()).add(event.object_id)
        return True

    def search_all(self, query: str) -> list[str]:
        query_terms = terms(query)
        if not query_terms:
            return []
        matches = set.intersection(*(self.postings.get(token, set()) for token in query_terms))
        return sorted(matches)


@dataclass
class Bucket:
    capacity: int
    refill_per_second: int
    now: int = 0
    tokens: int = field(init=False)

    def __post_init__(self) -> None:
        if self.capacity < 1 or self.refill_per_second < 1:
            raise ValueError("capacity and refill rate must be positive")
        self.tokens = self.capacity

    def admit(self, now: int, cost: int) -> bool:
        if now < self.now or not 1 <= cost <= self.capacity:
            raise ValueError("invalid time or cost")
        elapsed = now - self.now
        self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_per_second)
        self.now = now
        if cost > self.tokens:
            return False
        self.tokens -= cost
        return True


def main() -> None:
    index = Index()
    index.apply(Event("A", 1, "Intro storage design"))
    index.apply(Event("B", 1, "Storage systems"))
    index.apply(Event("C", 1, "Search design"))
    assert index.search_all("storage design") == ["A"]
    assert index.search_all("storage") == ["A", "B"]

    assert index.apply(Event("A", 3, None))
    assert not index.apply(Event("A", 2, "Storage design, revised"))
    assert not index.apply(Event("A", 3, None))
    assert index.search_all("storage") == ["B"]
    assert index.search_all("") == []

    bucket = Bucket(capacity=6, refill_per_second=2)
    assert bucket.admit(now=0, cost=5)
    assert not bucket.admit(now=1, cost=4)
    assert bucket.admit(now=2, cost=4)
    assert bucket.tokens == 1
    assert bucket.admit(now=20, cost=6)
    assert not bucket.admit(now=20, cost=1)
    print("Posting intersections, delete ordering, and token bucket checks passed.")

    # Try it yourself:
    # 1. Rebuild the projection by applying the same events in reverse order.
    # 2. Remove a tombstone and replay an older write. Observe resurrection.
    # 3. Give two replicas their own full buckets and compare the total burst.


if __name__ == "__main__":
    main()
