import subprocess, sys, time, xml.etree.ElementTree as ET

with open('/tmp/.bggkey') as f:
    bgg_key = f.read().strip()

HEADER = 'Authorization: Bearer ' + bgg_key
BASE_URL = 'https://boardgamegeek.com/xmlapi2/search'

def search_bgg(query_word):
    url = BASE_URL + '?query=' + query_word + '&type=boardgame'
    result = subprocess.run(['curl', '-s', '-H', HEADER, url], capture_output=True, text=True, timeout=30)
    if result.returncode != 0:
        return []
    xml_text = result.stdout.strip()
    if not xml_text:
        return []
    try:
        root = ET.fromstring(xml_text)
    except ET.ParseError:
        return []
    items = []
    for item in root.findall('item'):
        if item.get('type', '') != 'boardgame':
            continue
        name_el = item.find('name')
        name_val = name_el.get('value', '') if name_el is not None else ''
        year_el = item.find('yearpublished')
        year_val = year_el.get('value', '') if year_el is not None else ''
        items.append((item.get('id', ''), name_val, year_val))
    return items

# 1. Aeon (no apostrophe)
print('=== Aeon ===', file=sys.stderr)
items = search_bgg('Aeon')
print('  Got ' + str(len(items)) + ' results', file=sys.stderr)
for i, (item_id, name, year) in enumerate(items[:30]):
    print('  [' + str(i) + '] id=' + item_id + ' name=' + repr(name) + ' year=' + year, file=sys.stderr)
for item_id, name, year in items:
    if 'system overload' in name.lower():
        print('  FOUND: ' + item_id + ' ' + name + ' ' + year, file=sys.stderr)
time.sleep(3)

# 2. feast
print('\n=== feast ===', file=sys.stderr)
items = search_bgg('feast')
print('  Got ' + str(len(items)) + ' results', file=sys.stderr)
for i, (item_id, name, year) in enumerate(items[:20]):
    print('  [' + str(i) + '] id=' + item_id + ' name=' + repr(name) + ' year=' + year, file=sys.stderr)
for item_id, name, year in items:
    if 'wilderfeast' in name.lower():
        print('  FOUND: ' + item_id + ' ' + name + ' ' + year, file=sys.stderr)
time.sleep(3)

# 3. Wilderfeast retry
print('\n=== Wilderfeast retry ===', file=sys.stderr)
items = search_bgg('Wilderfeast')
print('  Got ' + str(len(items)) + ' results', file=sys.stderr)
for i, (item_id, name, year) in enumerate(items[:20]):
    print('  [' + str(i) + '] id=' + item_id + ' name=' + repr(name) + ' year=' + year, file=sys.stderr)
