"""Build the offline comparison dataset with Python 3.8+ (standard library).

Usage: python3 build_data.py [path/to/games.csv] [--out dist/data.json]
With no input, fetches the nflverse schedules release. Pass a saved CSV to
reproduce a particular snapshot; meta.sourceSha256 identifies the source bytes.
"""
import argparse
import csv
import hashlib
import io
import json
from collections import Counter
from fractions import Fraction
from pathlib import Path
from urllib.request import urlopen

START, END = 2000, 2025
SOURCE = 'https://github.com/nflverse/nflverse-data/releases/download/schedules/games.csv'
RELEASE = 'https://github.com/nflverse/nflverse-data/releases/tag/schedules'
LICENSE = 'https://creativecommons.org/licenses/by/4.0/'
TEAMS = {
    'ARI': 'Arizona Cardinals', 'ATL': 'Atlanta Falcons', 'BAL': 'Baltimore Ravens',
    'BUF': 'Buffalo Bills', 'CAR': 'Carolina Panthers', 'CHI': 'Chicago Bears',
    'CIN': 'Cincinnati Bengals', 'CLE': 'Cleveland Browns', 'DAL': 'Dallas Cowboys',
    'DEN': 'Denver Broncos', 'DET': 'Detroit Lions', 'GB': 'Green Bay Packers',
    'HOU': 'Houston Texans', 'IND': 'Indianapolis Colts', 'JAX': 'Jacksonville Jaguars',
    'KC': 'Kansas City Chiefs', 'LAC': 'Los Angeles Chargers', 'LAR': 'Los Angeles Rams',
    'LV': 'Las Vegas Raiders', 'MIA': 'Miami Dolphins', 'MIN': 'Minnesota Vikings',
    'NE': 'New England Patriots', 'NO': 'New Orleans Saints', 'NYG': 'New York Giants',
    'NYJ': 'New York Jets', 'PHI': 'Philadelphia Eagles', 'PIT': 'Pittsburgh Steelers',
    'SEA': 'Seattle Seahawks', 'SF': 'San Francisco 49ers', 'TB': 'Tampa Bay Buccaneers',
    'TEN': 'Tennessee Titans', 'WAS': 'Washington Commanders',
}
ALIASES = {'OAK': 'LV', 'SD': 'LAC', 'STL': 'LAR', 'LA': 'LAR'}
ROUNDS = {'WC': 'Wild Card', 'DIV': 'Divisional', 'CON': 'Conference championship', 'SB': 'Super Bowl'}
COUNTS = ('w', 'l', 't', 'regularNarrowLosses', 'playoffLosses',
          'highHopeLosses', 'playoffNarrowLosses', 'points')


def require(condition, message):
    if not condition:
        raise ValueError(message)


def franchise(code):
    key = ALIASES.get(code, code)
    require(key in TEAMS, f'Unknown franchise code: {code}')
    return key


def record(year):
    return dict(year=year, **dict.fromkeys(COUNTS, 0), playoffs=[], superBowlWin=False)


def ratio(value, denominator):
    return value / denominator if denominator else None


def rank_rows(entries):
    """Standard competition ranking. Fraction comparisons preserve exact ties."""
    frequencies = Counter(key for key, _ in entries)
    ranks = {}
    position = 1
    for key in sorted(frequencies, reverse=True):
        ranks[key] = position
        position += frequencies[key]
    for key, row in entries:
        row.update(rank=ranks[key], rankTiedTeams=frequencies[key], rankOutOf=len(entries))


def build(raw):
    reader = csv.DictReader(io.StringIO(raw.decode('utf-8-sig'), newline=''))
    rows = sorted((g for g in reader if START <= int(g['season']) <= END),
                  key=lambda g: (g['gameday'], g['game_id']))
    data = {k: {} for k in TEAMS}
    seen, game_counts = set(), Counter()
    for game in rows:
        year, kind = int(game['season']), game['game_type']
        if kind not in {'REG', *ROUNDS}:
            continue
        gid = game['game_id']
        require(gid not in seen, f'Duplicate game: {gid}')
        seen.add(gid)
        require(game['home_score'] and game['away_score'], f'Missing final score: {gid}')
        game_counts[year, kind] += 1
        for side, other in (('home', 'away'), ('away', 'home')):
            key = franchise(game[side + '_team'])
            row = data[key].setdefault(year, record(year))
            scored, allowed = int(game[side + '_score']), int(game[other + '_score'])
            margin = scored - allowed
            result = 'W' if margin > 0 else ('L' if margin < 0 else 'T')
            if kind == 'REG':
                row[result.lower()] += 1
                row['regularNarrowLosses'] += int(-8 <= margin < 0)
                continue
            require(result != 'T', f'Tied postseason game: {gid}')
            venue = 'neutral' if game['location'] == 'Neutral' else side
            row['playoffs'].append(dict(gameId=gid, date=game['gameday'], round=kind,
                                        opponent=franchise(game[other + '_team']),
                                        opponentAtGame=game[other + '_team'], teamScore=scored,
                                        oppScore=allowed, result=result, venue=venue,
                                        stadium=game['stadium']))
            row['playoffLosses'] += int(margin < 0)
            row['playoffNarrowLosses'] += int(-8 <= margin < 0)
            if kind == 'SB' and result == 'W':
                row['superBowlWin'] = True

    teams = []
    for key, seasons in data.items():
        first = 2002 if key == 'HOU' else START
        require(set(seasons) == set(range(first, END + 1)), f'Missing franchise season: {key}')
        ordered = [seasons[y] for y in sorted(seasons)]
        for row in ordered:
            n = row['w'] + row['l'] + row['t']
            expected = 16 if row['year'] <= 2020 else 17
            if row['year'] == 2022 and key in ('BUF', 'CIN'):
                expected = 16  # Buffalo at Cincinnati was declared a no-contest.
            require(n == expected, f'Unexpected regular-season game count: {key} {row["year"]} {n}')
            credit = Fraction(2 * row['w'] + row['t'], 2 * n)
            row['regularGames'] = n
            row['winPct'] = float(credit)
            row['regularNarrowLossRate'] = row['regularNarrowLosses'] / n
            row['highHopeLosses'] = row['playoffLosses'] if credit >= Fraction(7, 10) else 0
            row['points'] = (3 * row['playoffLosses'] + 2 * row['highHopeLosses'] +
                             row['playoffNarrowLosses'] + row['regularNarrowLosses'])
            require(row['playoffLosses'] <= 1, 'Elimination counted twice')
        summary = {field: sum(row[field] for row in ordered) for field in COUNTS}
        n = summary['w'] + summary['l'] + summary['t']
        summary.update(seasonsPlayed=len(ordered), pointsPerSeason=summary['points']/len(ordered),
                       regularGames=n, winPct=(summary['w']+summary['t']/2)/n,
                       regularNarrowLossRate=summary['regularNarrowLosses']/n,
                       playoffSeasons=sum(bool(row['playoffs']) for row in ordered),
                       playoffGames=sum(len(row['playoffs']) for row in ordered),
                       playoffWins=sum(g['result']=='W' for row in ordered for g in row['playoffs']),
                       superBowlWins=sum(row['superBowlWin'] for row in ordered))
        summary['playoffNarrowLossRate'] = ratio(summary['playoffNarrowLosses'], summary['playoffLosses'])
        summary['highHopeLossRate'] = ratio(summary['highHopeLosses'], summary['playoffLosses'])
        teams.append(dict(id=key, name=TEAMS[key], seasons=ordered, summary=summary))

    for year in range(START, END + 1):
        entries = [seasons[year] for seasons in data.values() if year in seasons]
        rank_rows([(row['points'], row) for row in entries])
        require(sum(row['superBowlWin'] for row in entries) == 1, f'Missing title: {year}')
        require(game_counts[year,'SB'] == 1 and game_counts[year,'CON'] == 2 and
                game_counts[year,'DIV'] == 4 and game_counts[year,'WC'] == (6 if year>=2020 else 4),
                f'Incomplete playoffs: {year}')
    rank_rows([(Fraction(t['summary']['points'],t['summary']['seasonsPlayed']), t['summary']) for t in teams])
    meta = dict(firstSeason=START, lastSeason=END, regularGames=sum(v for (_,k),v in game_counts.items() if k=='REG'),
                playoffGames=sum(v for (_,k),v in game_counts.items() if k in ROUNDS),
                source='NFL schedules and scores by Lee Sharpe and nflverse', sourceUrl=RELEASE,
                sourceFile=SOURCE, sourceSha256=hashlib.sha256(raw).hexdigest(),
                license='CC BY 4.0', licenseUrl=LICENSE,
                changes='Filtered completed seasons; unified franchises, calculated records, points, shares and ranks.',
                weights={'regularNarrowLosses':1, 'playoffLosses':3, 'highHopeLosses':2, 'playoffNarrowLosses':1},
                roundLabels=ROUNDS, franchiseAliases=ALIASES,
                scope='NFL season year includes its following January and February playoffs. Houston starts in 2002. All other franchises span 26 seasons.',
                interpretation='Higher means more events in this deliberately subjective frustration index. A one-score defeat is a final margin of 1–8 points. Bonuses stack. A high-hope defeat follows a regular-season winning percentage of at least .700, counting a tie as half a win. Titles are shown separately.',
                rankings='Season ranks compare points among active franchises in that year. All-years ranks compare exact points per season played. Ties share rank and skip the following places.',
                limitations='Scores do not measure fandom, playoff expectations, blown leads, win probability, or off-field news. Missing the playoffs earns no playoff-loss points. Longer seasons and deeper playoff runs change exposure.',
                rateDenominators='Regular narrow-loss share uses all regular games. Playoff narrow-loss and high-hope shares use playoff defeats.')
    return dict(schemaVersion=1, meta=meta, teams=teams)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('csv', nargs='?', type=Path)
    parser.add_argument('--out', type=Path, default=Path(__file__).parent/'dist'/'data.json')
    args=parser.parse_args()
    if args.csv:
        raw = args.csv.read_bytes()
    else:
        with urlopen(SOURCE, timeout=40) as response:
            raw = response.read()
    dataset = build(raw)
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(json.dumps(dataset, ensure_ascii=False, separators=(',',':'), allow_nan=False)+'\n', encoding='utf-8')
    print(f'{len(dataset["teams"])} franchises, {dataset["meta"]["regularGames"]} regular games and {dataset["meta"]["playoffGames"]} playoff games.')


if __name__ == '__main__':
    main()
