"""Pattern 20: Trie (prefix tree).

Signals: many words sharing prefixes, "starts with", autocomplete, wildcard
search, or searching a grid for many words at once. Each node is a dict of
children plus an end-of-word flag.
"""

from __future__ import annotations


class TrieNode:
    __slots__ = ("children", "word")

    def __init__(self) -> None:
        self.children: dict[str, TrieNode] = {}
        self.word: str | None = None  # the full word ending here, if any


class Trie:
    def __init__(self) -> None:
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        node = self.root
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
        node.word = word

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

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

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

    def search_wildcard(self, pattern: str) -> bool:
        """'.' matches any single letter (add-and-search-words)."""

        def dfs(node: TrieNode, i: int) -> bool:
            if i == len(pattern):
                return node.word is not None
            ch = pattern[i]
            if ch == ".":
                return any(dfs(child, i + 1) for child in node.children.values())
            child = node.children.get(ch)
            return child is not None and dfs(child, i + 1)

        return dfs(self.root, 0)


def replace_words(roots: list[str], sentence: str) -> str:
    """Replace each word by its shortest root found in the trie."""
    trie = Trie()
    for r in roots:
        trie.insert(r)
    out = []
    for word in sentence.split():
        node = trie.root
        replacement = word
        for ch in word:
            node = node.children.get(ch)  # type: ignore[assignment]
            if node is None:
                break
            if node.word is not None:
                replacement = node.word
                break
        out.append(replacement)
    return " ".join(out)


def find_words(board: list[list[str]], words: list[str]) -> list[str]:
    """Word search II: walk the grid and the trie together."""
    trie = Trie()
    for w in words:
        trie.insert(w)
    rows, cols = len(board), len(board[0])
    found: set[str] = set()

    def dfs(r: int, c: int, node: TrieNode) -> None:
        ch = board[r][c]
        child = node.children.get(ch)
        if child is None:
            return
        if child.word is not None:
            found.add(child.word)
        board[r][c] = "#"
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#":
                dfs(nr, nc, child)
        board[r][c] = ch

    for r in range(rows):
        for c in range(cols):
            dfs(r, c, trie.root)
    return sorted(found)
