import requests
from bs4 import BeautifulSoup
import json


def scrape_script_data(match_id):
    """Web scrape the match info and return the Beautiful object and a dictionary for the home and away team's data."""
    url = 'https://understat.com/match/{}'.format(match_id)

    response = requests.get(url)
    soup_object = BeautifulSoup(response.content, 'lxml')

    # Retrieve all data with a <script> tag - Field data are in the second <script> group
    script_data = soup_object.find_all('script')
    field_stats = script_data[1].string

    # Strip unnecessary symbols and get only JSON data
    ind_start = field_stats.index("('") + 2
    ind_end = field_stats.index("')")

    json_data = field_stats[ind_start:ind_end]
    json_data = json_data.encode('utf8').decode('unicode_escape')

    # Convert string to json format
    data_dict = json.loads(json_data)

    return soup_object, data_dict