"""Trie (prefix tree).

Idea
----
Store strings character by character in a tree, so words sharing a prefix
share a path. Each node maps a character to a child and records whether a
word ends there. Prefix queries ("which words start with 'ca'?") cost time
proportional to the prefix length, not the number of stored words.

Complexity
----------
insert / contains / starts_with: O(L) for a key of length L
Space: O(total characters stored) in the worst case

Used for autocomplete, spell checkers, IP routing (binary tries) and word
games.
"""

from collections.abc import Iterable, Iterator
from dataclasses import dataclass, field


@dataclass
class _Node:
    children: dict[str, "_Node"] = field(default_factory=dict)
    is_word: bool = False


class Trie:
    def __init__(self, words: Iterable[str] = ()) -> None:
        self._root = _Node()
        for w in words:
            self.insert(w)

    def insert(self, word: str) -> None:
        node = self._root
        for ch in word:
            node = node.children.setdefault(ch, _Node())
        node.is_word = True

    def _walk(self, prefix: str) -> _Node | None:
        node = self._root
        for ch in prefix:
            node = node.children.get(ch)  # type: ignore[assignment]
            if node is None:
                return None
        return node

    def __contains__(self, word: str) -> bool:
        node = self._walk(word)
        return node is not None and node.is_word

    def starts_with(self, prefix: str) -> bool:
        return self._walk(prefix) is not None

    def words_with_prefix(self, prefix: str) -> list[str]:
        """Return every stored word beginning with ``prefix``, sorted."""
        start = self._walk(prefix)
        if start is None:
            return []

        def collect(node: _Node, path: str) -> Iterator[str]:
            if node.is_word:
                yield path
            for ch in sorted(node.children):
                yield from collect(node.children[ch], path + ch)

        return list(collect(start, prefix))
