import re
from typing import Dict, Tuple

def parse_formula_recursive(formula: str) -> Dict[str, int]:
    """
    Recursively parse a chemical formula and return atom counts.
    Handles parentheses, brackets, and coefficients.
    """
    atoms = {}
    i = 0
    while i < len(formula):
        if formula[i].isupper():
            # Start of element
            element = formula[i]
            i += 1
            while i < len(formula) and formula[i].islower():
                element += formula[i]
                i += 1
            # Now get coefficient
            coeff = 0
            while i < len(formula) and formula[i].isdigit():
                coeff = coeff * 10 + int(formula[i])
                i += 1
            if coeff == 0:
                coeff = 1
            atoms[element] = atoms.get(element, 0) + coeff
        elif formula[i] in '([':
            # Start of group
            start = i
            i += 1
            level = 1
            while i < len(formula) and level > 0:
                if formula[i] in '([':
                    level += 1
                elif formula[i] in ')]':
                    level -= 1
                i += 1
            group_formula = formula[start+1:i-1]
            # Get coefficient after closing
            coeff = 0
            while i < len(formula) and formula[i].isdigit():
                coeff = coeff * 10 + int(formula[i])
                i += 1
            if coeff == 0:
                coeff = 1
            group_atoms = parse_formula_recursive(group_formula)
            for el, count in group_atoms.items():
                atoms[el] = atoms.get(el, 0) + count * coeff
        else:
            i += 1  # Skip invalid characters
    return atoms