import requests


def create_opponents(
    teams_data: list, fixtures_uri="https://fantasy.premierleague.com/api/fixtures/", sort=False
) -> dict:
    """Return the fixtures list for each PL team.

    Args:
        teams_data (list): List holding teams data loaded from /api/boostrap-static dump
        fixtures_uri (str, optional): Path the FPL fixtures list.
            Defaults to "https://fantasy.premierleague.com/api/fixtures/".
        sort (boolean, optional): Sort opponents on gameweek. Defaults to False.

    Returns:
        dict: {team_name: [{team: str, difficulty: int, venue: str}]}
    """
    url = fixtures_uri
    fpl_json = requests.get(url).json()
    name_mapping = {i["id"]: i["name"] for i in teams_data}
    teams = set([i["team_a"] for i in fpl_json])
    all_teams = {}
    for y in teams:
        opponents = []
        for i in fpl_json:
            if i["team_h"] == y:
                opponents.append(
                    {
                        "team": name_mapping[i["team_a"]],
                        "difficulty": i["team_h_difficulty"],
                        "venue": "h",
                        "gameweek": i["event"],
                    }
                )
            if i["team_a"] == y:
                opponents.append(
                    {
                        "team": name_mapping[i["team_h"]],
                        "difficulty": i["team_a_difficulty"],
                        "venue": "a",
                        "gameweek": i["event"],
                    }
                )

        if sort:
            all_teams[name_mapping[y]] = sorted(
                opponents, key=lambda i: i["gameweek"] if i["gameweek"] else 99999
            )
        else:
            all_teams[name_mapping[y]] = opponents

    return all_teams