"""Stage 8: Trees (problems 65-80)."""
from __future__ import annotations

from collections import deque
from typing import List, Optional

from .structures import TreeNode


def invert_tree(root: Optional[TreeNode]) -> Optional[TreeNode]:
    """LC 226. Swap children at every node (any traversal order works)."""
    if root:
        root.left, root.right = invert_tree(root.right), invert_tree(root.left)
    return root


def max_depth(root: Optional[TreeNode]) -> int:
    """LC 104. Depth = 1 + deeper child."""
    return 0 if not root else 1 + max(max_depth(root.left), max_depth(root.right))


def diameter_of_binary_tree(root: Optional[TreeNode]) -> int:
    """LC 543. At each node the longest path through it is left height + right height."""
    best = 0

    def height(node: Optional[TreeNode]) -> int:
        nonlocal best
        if not node:
            return 0
        lh, rh = height(node.left), height(node.right)
        best = max(best, lh + rh)
        return 1 + max(lh, rh)

    height(root)
    return best


def is_balanced(root: Optional[TreeNode]) -> bool:
    """LC 110. Return -1 as an 'unbalanced' signal so each node is visited once."""

    def height(node: Optional[TreeNode]) -> int:
        if not node:
            return 0
        lh, rh = height(node.left), height(node.right)
        if lh < 0 or rh < 0 or abs(lh - rh) > 1:
            return -1
        return 1 + max(lh, rh)

    return height(root) >= 0


def is_same_tree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
    """LC 100. Same value and both subtrees the same."""
    if not p or not q:
        return p is q
    return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)


def is_subtree(root: Optional[TreeNode], sub: Optional[TreeNode]) -> bool:
    """LC 572. Try is_same_tree at every node of root."""
    if not sub:
        return True
    if not root:
        return False
    return is_same_tree(root, sub) or is_subtree(root.left, sub) or is_subtree(root.right, sub)


def lowest_common_ancestor_bst(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
    """LC 235. Walk down until p and q fall on different sides (or one equals the node)."""
    node = root
    while node:
        if p.val < node.val and q.val < node.val:
            node = node.left
        elif p.val > node.val and q.val > node.val:
            node = node.right
        else:
            return node
    raise ValueError("p and q must be in the tree")


def level_order(root: Optional[TreeNode]) -> List[List[int]]:
    """LC 102. BFS; process exactly len(queue) nodes per level."""
    out: List[List[int]] = []
    queue = deque([root] if root else [])
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        out.append(level)
    return out


def right_side_view(root: Optional[TreeNode]) -> List[int]:
    """LC 199. Last node of each BFS level."""
    return [level[-1] for level in level_order(root)]


def good_nodes(root: Optional[TreeNode]) -> int:
    """LC 1448. Carry the max value seen on the path from the root."""

    def dfs(node: Optional[TreeNode], best: int) -> int:
        if not node:
            return 0
        good = 1 if node.val >= best else 0
        best = max(best, node.val)
        return good + dfs(node.left, best) + dfs(node.right, best)

    return dfs(root, float("-inf"))  # type: ignore[arg-type]


def is_valid_bst(root: Optional[TreeNode]) -> bool:
    """LC 98. Pass down an open (low, high) range; checking only children is not enough."""

    def ok(node: Optional[TreeNode], low: float, high: float) -> bool:
        if not node:
            return True
        if not low < node.val < high:
            return False
        return ok(node.left, low, node.val) and ok(node.right, node.val, high)

    return ok(root, float("-inf"), float("inf"))


def kth_smallest(root: Optional[TreeNode], k: int) -> int:
    """LC 230. Iterative in-order traversal visits BST values in sorted order."""
    stack: List[TreeNode] = []
    node = root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        k -= 1
        if k == 0:
            return node.val
        node = node.right
    raise ValueError("k is larger than the tree")


def build_tree_pre_in(preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
    """LC 105. preorder[0] is the root; its inorder index splits left and right subtrees."""
    index = {v: i for i, v in enumerate(inorder)}
    pre = iter(preorder)

    def build(lo: int, hi: int) -> Optional[TreeNode]:
        if lo > hi:
            return None
        val = next(pre)
        node = TreeNode(val)
        node.left = build(lo, index[val] - 1)
        node.right = build(index[val] + 1, hi)
        return node

    return build(0, len(inorder) - 1)


def max_path_sum(root: Optional[TreeNode]) -> int:
    """LC 124. Return the best one-sided gain upward; update the answer with the two-sided path."""
    best = float("-inf")

    def gain(node: Optional[TreeNode]) -> int:
        nonlocal best
        if not node:
            return 0
        left = max(gain(node.left), 0)
        right = max(gain(node.right), 0)
        best = max(best, node.val + left + right)
        return node.val + max(left, right)

    gain(root)
    return int(best)


class Codec:
    """LC 297. Preorder with '#' for null; deserialize consumes the same order."""

    def serialize(self, root: Optional[TreeNode]) -> str:
        out: List[str] = []

        def walk(node: Optional[TreeNode]) -> None:
            if not node:
                out.append("#")
                return
            out.append(str(node.val))
            walk(node.left)
            walk(node.right)

        walk(root)
        return ",".join(out)

    def deserialize(self, data: str) -> Optional[TreeNode]:
        tokens = iter(data.split(","))

        def build() -> Optional[TreeNode]:
            tok = next(tokens)
            if tok == "#":
                return None
            node = TreeNode(int(tok))
            node.left = build()
            node.right = build()
            return node

        return build()


def lowest_common_ancestor(root: Optional[TreeNode], p: TreeNode, q: TreeNode) -> Optional[TreeNode]:
    """LC 236. If p and q are found in different subtrees, the current node is the LCA."""
    if root is None or root is p or root is q:
        return root
    left = lowest_common_ancestor(root.left, p, q)
    right = lowest_common_ancestor(root.right, p, q)
    if left and right:
        return root
    return left or right
