"""night_describe.py -- piece descriptions, written slowly at night (Ivy, Oct 23 2026: "Have the description go slow at night").
One Haiku call every 30 s from 4 AM, stopping by 8 AM, and waiting while a game is running so it never competes with play.
Run by the systemd user timer reef-describe.timer. Written by Iris."""
import json, os, sys, time, urllib.request
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
os.environ.setdefault('HIP_VISIBLE_DEVICES', ''); os.environ.setdefault('CUDA_VISIBLE_DEVICES', '')
import partbin, play
def busy():
    try: return json.load(urllib.request.urlopen('http://127.0.0.1:8767/api/status', timeout=5)).get('busy', False)
    except Exception: return False
done = 0
for part in play.PALETTE:
    if time.localtime().tm_hour >= 8: break
    if part in partbin._desc_all() or not os.path.exists(os.path.join(HERE, 'parts', f'{part}_w.png')): continue
    while busy() and time.localtime().tm_hour < 8: time.sleep(120)
    if partbin.describe(part, play.CX.NAMES.get(part)): done += 1; print('described', part, flush=True)
    time.sleep(30)
print('night done:', done, 'described;', len(partbin._desc_all()), 'have descriptions', flush=True)
