import re


def parse_css_selector(spec):
    """
    Parse a CSS-style selector (similar to what jQuery and CSS use).
    Returns an dict with tag_, id, and class, and other key, value
    fields.
    """
    if spec is None:
        return {}

    # use regular expressions to parse the selector spec
    tagnames = re.findall(r'^(\w+)',      spec)
    classes  = re.findall(r'\.([\w\-]+)', spec)
    ids      = re.findall(r'\#([\w\-]+)', spec)
    attrs    = re.findall(r'\[([\w-]+=[^]]*)\]', spec)

    # make some basic assertions
    assert len(tagnames) <= 1
    assert len(ids) <= 1

    # construct the result dict
    atts = {}
    if ids:
        atts['id'] = ids[0]
    if classes:
        atts['class'] = ' '.join(classes)
    if tagnames:
        atts['_tag'] = tagnames[0]
    for a in attrs:
        k, v = a.split('=')
        atts[k] = v
    return atts