import copy


def get_state(system: "System") -> dict:
    """Export system state (inputs and outputs) into a dictionary
    for quick serialization, without type check.
    
    Returns:
    --------
    Recursive dictionary of the kind:
    {
        'ports: {
            port_name: {
                varname: value,
                ...
            },
            ...
        },
        'children': {
            child_name: {
                'ports': {...},
                'children: {...},
            },
            ...
        },
    }
    """
    from cosapp.base import System
    def recursive_search(system: "System", state: dict) -> None:
        state['ports'] = port_data = {}
        for port in system.ports():
            data = {
                var: copy.deepcopy(value)
                for var, value in port.items()
            }
            if data:
                port_data[port.name] = data
        if system.children:
            state['children'] = child_data = {}
            for child in system.children.values():
                child_data[child.name] = child_state = {}
                recursive_search(child, child_state)
    state = {}
    recursive_search(system, state)
    return state


def set_state(system: "System", state: dict) -> None:
    """Import system state (inputs and outputs) from
    a dictionary generated by `get_state`.
    """
    for name, values in state['ports'].items():
        port = getattr(system, name)
        for name, value in values.items():
            setattr(port, name, copy.deepcopy(value))
        # system[name].set_values(**copy.deepcopy(values))
    child_data = state.get('children', {})
    for name, child_state in child_data.items():
        set_state(system[name], child_state)
