#!/usr/bin/env python3
from __future__ import annotations

import argparse
from io import StringIO
from pathlib import Path

import pandas as pd
import requests

REPO_ROOT = Path(__file__).resolve().parents[1]
OUT_DIR = REPO_ROOT / 'historical_data'
BASE_URL = 'https://www.football-data.co.uk/mmz4281/{season}/{league}.csv'
LEAGUE_MAP = {
    'e2': 'E1',  # Championship
    'e3': 'E3',  # League Two
}


def season_tokens(start_year: int = 2005, end_year: int = 2025):
    for y in range(start_year, end_year + 1):
        yield y, f'{str(y)[-2:]}{str(y+1)[-2:]}'


def download_one(code: str) -> Path:
    league_token = LEAGUE_MAP[code]
    dfs = []
    session = requests.Session()
    for start_year, token in season_tokens():
        url = BASE_URL.format(season=token, league=league_token)
        r = session.get(url, timeout=60)
        if r.status_code != 200 or 'Date,HomeTeam,AwayTeam' not in r.text[:500] and 'Div,Date,Time,HomeTeam' not in r.text[:500]:
            continue
        df = pd.read_csv(StringIO(r.text))
        df['season'] = start_year
        dfs.append(df)
    if not dfs:
        raise RuntimeError(f'no data downloaded for {code}')
    combo = pd.concat(dfs, ignore_index=True, sort=False)
    out_path = OUT_DIR / f'{code}_history.csv'
    combo.to_csv(out_path, index=False, encoding='utf-8-sig')
    return out_path


def main():
    parser = argparse.ArgumentParser(description='Download England league history from football-data.co.uk')
    parser.add_argument('--codes', nargs='+', default=['e2', 'e3'])
    args = parser.parse_args()
    for code in args.codes:
        path = download_one(code)
        print(code, path)


if __name__ == '__main__':
    main()
