# Reads the installed ROM and writes ../teams.json for the website (rosters, ratings, lines).
import json, struct, os, re, unicodedata, glob
here = os.path.dirname(os.path.abspath(__file__))
ROM = os.path.expanduser('~/.config/retroarch/roms/claude/NHL 2026 - 94 Edition v5.1W.bin')
d = open(ROM, 'rb').read()
AB = ['ANA','BOS','BUF','CGY','CAR','CHI','COL','CBJ','DAL','DET','EDM','FLA','LAK','MIN','MTL','NSH',
      'NJD','NYI','NYR','OTT','PHI','PIT','SJS','SEA','STL','TBL','TOR','UTA','VAN','VGK','WSH','WPG']
def norm(s): s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode().lower(); return re.sub(r'[^a-z]', '', s)
POS = {}
for f in glob.glob(os.path.join(here, 'data', 'roster_*.json')) + glob.glob(os.path.join(here, 'data', 'prosp_*.json')):
    r = json.load(open(f))
    for g in ('forwards', 'defensemen', 'goalies'):
        for p in r[g]: POS.setdefault(norm(p['firstName']['default'] + p['lastName']['default']), p['positionCode'])
for f in glob.glob(os.path.join(here, 'data', 'sk_bios_*.json')):
    for p in json.load(open(f))['data']: POS.setdefault(norm(p['skaterFullName']), p['positionCode'])
teams = []
for t, ab in enumerate(AB):
    a = struct.unpack('>I', d[0x30E + 4 * t:0x312 + 4 * t])[0]; h = struct.unpack('>6H', d[a:a + 12])
    i = a + h[0]; pl = []
    while i < a + h[2] - 2:
        n = struct.unpack('>H', d[i:i + 2])[0]
        nm = d[i + 2:i + n].rstrip(b'\x00').decode('latin1'); b = d[i + n:i + n + 8]
        nib = [int(c, 16) for c in b[1:].hex()]
        pl.append(dict(name=nm.replace('_', ' '), jersey=b[:1].hex(), r=nib)); i += n + 8
    s = d[a + h[2]:a + h[2] + 100]; parts = []; k = 0
    for _ in range(4):
        L = struct.unpack('>H', s[k:k + 2])[0]; parts.append(s[k + 2:k + L].rstrip(b'\x00').decode('latin1')); k += L
    rj = os.path.join(here, 'rosters', ab + '.json')
    R = json.load(open(rj)) if os.path.exists(rj) else {}
    grp = ['G'] * len(R.get('goalies', [])) + ['F'] * len(R.get('forwards', [])) + ['D'] * len(R.get('defense', []))
    for p, g in zip(pl, grp):
        p['grp'] = g
        pc = POS.get(norm(p['name']))
        p['pos'] = {'C': 'C', 'L': 'LW', 'R': 'RW', 'D': 'D', 'G': 'G'}.get(pc, g)
        p['hand'] = 'R' if g != 'G' and p['r'][7] & 1 else 'L' if g != 'G' else ''
        p['fight'] = p['r'][7] >> 1 if g != 'G' else None
    L = d[a + h[3]:a + h[3] + 64]
    lines = [[pl[x - 1]['name'] for x in L[e * 8:e * 8 + 7]] for e in range(8)]
    notes = R.get('rating_notes', {})
    teams.append(dict(abbr=ab, city=parts[0], name=parts[2], arena=parts[3], players=pl,
                      lines=dict(zip(['X', 'Sc1', 'Sc2', 'Chk', 'PP1', 'PP2', 'PK1', 'PK2'], lines)),
                      new={k.replace('_', ' '): v for k, v in notes.items()}, note=R.get('note', ''),
                      left_out=R.get('left_out', []), manual=R.get('manual', False)))
SEASON = os.path.expanduser('~/.config/retroarch/roms/claude/MEGAdriveHARDJOB/NHL94-season.bin')
smd5 = __import__('hashlib').md5(open(SEASON, 'rb').read()).hexdigest() if os.path.exists(SEASON) else ''
json.dump(dict(rom_md5=smd5 or __import__('hashlib').md5(d).hexdigest(), plain_md5=__import__('hashlib').md5(d).hexdigest(), teams=teams), open(os.path.join(here, '..', 'teams.json'), 'w'))
print('teams.json', len(teams))
