import re
from typing import Dict
from .utils.formula_tools import parse_formula_recursive

def parse_chemical_formula(formula: str) -> Dict[str, int]:
    """
    Parse a chemical formula and return a dictionary of atom counts.
    Handles parentheses, brackets, coefficients, and hydrates.
    """
    # Handle hydrate notation
    if '·' in formula:
        parts = formula.split('·')
        if len(parts) != 2:
            raise ValueError("Invalid hydrate notation")
        main_formula = parts[0]
        hydrate_part = parts[1]
        # Parse hydrate part, assuming it's like 5H2O
        hydrate_atoms = parse_formula_recursive(hydrate_part)
        main_atoms = parse_formula_recursive(main_formula)
        # Combine
        atoms = {}
        for el, count in main_atoms.items():
            atoms[el] = atoms.get(el, 0) + count
        for el, count in hydrate_atoms.items():
            atoms[el] = atoms.get(el, 0) + count
        return atoms
    else:
        return parse_formula_recursive(formula)