File size: 3,714 Bytes
c569f03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from smolagents.tools import Tool
import requests

class PrimeiraLigaTeamStatsTool(Tool):
    name = "get_primeira_liga_team_stats"
    description = "Retrieve standing and last 3 match scores for a given Primeira Liga team."
    inputs = {'team_name': {'type': 'string', 'description': 'Name of the team to search for'}}
    output_type = "string"

    def forward(self, team_name: str) -> str:
        def _determine_match_outcome(home_team: str, away_team: str, 
                                home_score: int, away_score: int, 
                                target_team: str) -> str:
            """
            Determine match outcome (W/D/L) from the perspective of the target team.
            """
            
            if home_team == target_team:
                if home_score > away_score:
                    return 'W'
                elif home_score < away_score:
                    return 'L'
                else:
                    return 'D'
            else:
                if away_score > home_score:
                    return 'W'
                elif away_score < home_score:
                    return 'L'
                else:
                    return 'D'

        # API Base URL
        BASE_URL = "https://www.thesportsdb.com/api/v1/json/3"
        
        # Hardcoded Primeira Liga League ID
        PRIMEIRA_LIGA_ID = 4344
        
        try:
            # Step 1: Search for the team to get its ID
            team_search_url = f"{BASE_URL}/searchteams.php?t={team_name.replace(' ', '%20')}"
            team_search_response = requests.get(team_search_url)
            team_search_data = team_search_response.json()
            
            if not team_search_data.get('teams'):
                return "Error: Team not found"
            
            # Get the first matching team's ID
            team_id = team_search_data['teams'][0]['idTeam']
            
            # Step 2: Get league table
            table_url = f"{BASE_URL}/lookuptable.php?l={PRIMEIRA_LIGA_ID}"
            table_response = requests.get(table_url)
            table_data = table_response.json()
            
            # Find team's standing
            standing = next(
                (int(entry['intRank']) for entry in table_data.get('table', []) 
                if entry['idTeam'] == team_id), 
                None
            )
            
            # Step 3: Get last 5 events for the team
            last_events_url = f"{BASE_URL}/eventslast.php?id={team_id}"
            last_events_response = requests.get(last_events_url)
            last_events_data = last_events_response.json()
            
            # Process last 3 matches
            last_3_matches = []
            for event in last_events_data.get('results', [])[:3]:
                match = {
                    'opponent': event['strAwayTeam'] if event['strHomeTeam'] == team_name else event['strHomeTeam'],
                    'result': f"{event['intHomeScore']} - {event['intAwayScore']}",
                    'outcome': _determine_match_outcome(
                        event['strHomeTeam'], event['strAwayTeam'], 
                        event['intHomeScore'], event['intAwayScore'], 
                        team_name
                    )
                }
                last_3_matches.append(match)
            
            return str({
                "team": team_name,
                "standing": standing,
                "last_3_matches": last_3_matches
            })
        
        except Exception as e:
            print(f"Error retrieving team stats: {e}")
            return str("Error retrieving team stats")

    def __init__(self, *args, **kwargs):
        self.is_initialized = False