from bs4 import BeautifulSoup
import collections


def parse_pass_rss(txt):
  """Parses a WSDOT pass summary block into a python ordered dict."""
  soup = BeautifulSoup(txt)
  lines = soup.contents

  # Indicies of heading lines
  strongs = [i for i, t in list(enumerate(lines))
             if getattr(t, 'name', None) == 'strong']

  # Chunkify lines based on heading lines
  chunk_bounds = zip(strongs, strongs[1:] + [len(lines)])
  chunks = [lines[start:end] for start,end in chunk_bounds]

  # Convert a chunk into a key value pair using fairly arbitary semicolon
  # parsing (silly wsdot...)
  def chunk_to_kv(c):
    head, tail = '', ''
    node_text = lambda n: str(getattr(n, 'text', n))
    if len(c) >= 1:
      s = node_text(c[0]).split(':')
      head += s[0]
      if len(s) > 1:
        tail += ' '.join(s[1:])
    if len(c) >= 2:
      tail += ' '.join(node_text(l) for l in c[1:])
    return head.upper().strip(), tail.strip()

  return collections.OrderedDict(chunk_to_kv(c) for c in chunks)