from typing import Dict, Any, Optional
import copy

class FractalStateManager:
    def __init__(self):
        self._state_trees: Dict[str, Dict[str, Any]] = {}

    def track_tree(self, root_id: str, state_dict: Dict[str, Any]):
        """
        Tracks a hierarchical state tree.
        """
        if root_id not in self._state_trees:
            self._state_trees[root_id] = copy.deepcopy(state_dict)
        else:
            self._merge_dicts(self._state_trees[root_id], state_dict)

    def get_tree_status(self, root_id: str) -> Optional[Dict[str, Any]]:
        """
        Retrieves the hierarchical state tree of agent statuses.
        """
        if root_id in self._state_trees:
            return copy.deepcopy(self._state_trees[root_id])
        return None
        
    def _merge_dicts(self, d1: dict, d2: dict):
        for k, v in d2.items():
            if k in d1 and isinstance(d1[k], dict) and isinstance(v, dict):
                self._merge_dicts(d1[k], v)
            else:
                d1[k] = copy.deepcopy(v)
