from bs4 import BeautifulSoup


def scrape(html_file):
    """
    Scrapes an ESPN URL for schedule data
    Returns an array of dictionaries containing game details
    """
    soup = BeautifulSoup(open(html_file), 'lxml')
    tables = soup.find_all('table')
    games = []
    for table in tables:
        for row in table.find_all('tr'):
            # Convert generator object to list and remove ticket details
            game_details = [str(item) for item in row.stripped_strings]

            if 'matchup' not in game_details:  # Skip header rows
                # Normalize team info to RANK, TEAM
                if '#' not in game_details[0]:
                    game_details.insert(0, '')
                if '#' not in game_details[3]:
                    game_details.insert(3, '')
                # Just in case the  abbreviation is missing
                # ESPN is weird that way
                while len(game_details) < 6:
                    game_details.append('')

                game_dict = {}
                game_dict['away_rank'] = game_details[0]
                game_dict['away_team'] = game_details[1].replace('\'', '')
                game_dict['away_abbr'] = game_details[2]
                game_dict['home_rank'] = game_details[3]
                game_dict['home_team'] = game_details[4].replace('\'', '')
                game_dict['home_abbr'] = game_details[5]
                games.append(game_dict)
    return games