import pandas as pd
from functools import lru_cache
from .config import MATCH_STATS_URL

@lru_cache(maxsize=1)
def _load_matches():
    df = pd.read_csv(MATCH_STATS_URL)
    # Nettoyage
    df['home_team'] = df['home_team'].astype(str).str.strip()
    df['away_team'] = df['away_team'].astype(str).str.strip()
    df['home_team_form'] = df['home_team_form'].astype(str).str.strip()
    return df

@lru_cache(maxsize=1)
def get_home_teams():
    df = _load_matches()
    return sorted(df['home_team'].dropna().unique())

def get_teams_by_home_team_form(home_team: str):
    df = _load_matches()
    home_team = home_team.strip()
    if home_team not in df['home_team'].values:
        raise ValueError(f"{home_team} is not a valid home team")

    home_forms = df.loc[df['home_team'] == home_team, 'home_team_form'].dropna().unique()
    all_teams = pd.Series(dtype=str)
    for form in home_forms:
        teams = pd.concat([
            df.loc[df['home_team_form'] == form, 'home_team'],
            df.loc[df['home_team_form'] == form, 'away_team']
        ])
        all_teams = pd.concat([all_teams, teams])
    return sorted(all_teams.dropna().str.strip().unique())
