from collections.abc import Mapping

from bundlewrap.exceptions import BundleError
from bundlewrap.utils.text import bold, green
from bundlewrap.utils.ui import io


def test_underscore_vs_dash(node, metadata, path=[]):
    for k, v in metadata.items():
        if not isinstance(k, str):
            continue

        all_dashes = k.replace('_', '-')
        all_underscores = k.replace('-', '_')

        if k != all_dashes and all_dashes in metadata:
            raise BundleError('{n} metadata contains both {k} and {p}'.format(
                n=node.name,
                k='/'.join(path + [k]),
                p='/'.join(path + [all_dashes]),
            ))

        if k != all_underscores and all_underscores in metadata:
            raise BundleError('{n} metadata contains both {k} and {p}'.format(
                n=node.name,
                k='/'.join(path + [k]),
                p='/'.join(path + [all_underscores]),
            ))

        if isinstance(v, Mapping):
            test_underscore_vs_dash(
                node,
                v,
                path + [k],
            )

def test_node(repo, node, **kwargs):
    test_underscore_vs_dash(
        node,
        node.metadata.get(tuple()),
    )

    io.stdout('{x} {node}  metadata contains no dashes-vs-underscores errors'.format(
        x=green("✓"),
        node=bold(node.name),
    ))