"""Plain table of the spaceship batch for the report (16 Oct 2026): per job = family, pen, minutes, card status, size, triangles,
MB, warnings, painted (views kept / tried, share of the outside repainted), Gemini list cost. usage: python3 tools/space/stats_space.py"""
import json, os, subprocess
from datetime import datetime
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
L = '/tmp/space-20261016'


def mins(jd):
    try:
        t = lambda f: datetime.fromisoformat(open(f'{jd}/{f}').read().strip().replace('Z', '+00:00'))
        return round((t('finished.txt') - t('started.txt')).total_seconds() / 60)
    except Exception:  # noqa: BLE001
        return None


rows, tot = [], {'astra': [0, 0, 0.0], 'gemini4': [0, 0, 0.0]}
for line in open(f'{L}/order.txt'):
    slug, pen = line.split()
    jd = f'{ROOT}/jobs/{slug}-v1'; j = json.load(open(f'{jd}/job.json'))
    ck = json.load(open(f'{jd}/check.json')) if os.path.exists(f'{jd}/check.json') else None
    pr = {}
    if os.path.exists(f'{jd}/painted-row.json'):
        try: pr = json.load(open(f'{jd}/painted-row.json'))
        except Exception: pr = {}  # noqa: E701
    cost = None
    relay = f'{jd}/agy-relay.log' if os.path.exists(f'{jd}/agy-relay.log') else f'/tmp/agy-author/{slug}-v1/agy-relay.log'
    if pen == 'gemini4' and os.path.exists(relay):
        r = subprocess.run(['python3', os.path.expanduser('~/forge-hub/agent/agy4_cost.py'), relay], capture_output=True, text=True)
        if r.returncode == 0: cost = json.loads(r.stdout)['usd_list']
    state = ('carded' if ck and ck['ok'] else 'check failed' if ck else 'built, not checked' if os.path.exists(f'{jd}/rc.txt')
             else 'running' if os.path.exists(f'{jd}/started.txt') else 'queued')
    m = mins(jd) if os.path.exists(f'{jd}/finished.txt') else None
    if m: tot[pen][0] += 1; tot[pen][1] += m; tot[pen][2] += cost or 0  # noqa: E701
    f = (ck or {}).get('facts', {})
    rows.append(dict(slug=slug, family=j['family'], pen='Astra xhigh' if pen == 'astra' else 'Gemini 4 high', state=state, minutes=m,
                     size=f.get('size'), tris=f.get('tris'), mb=f.get('mb'), warnings=len((ck or {}).get('warnings', [])),
                     painted=(f"{pr.get('kept')}/{pr.get('tried')} views, {round(100 * (pr.get('outside') or 0))}%" if pr.get('applied') else
                              ('failed: ' + str(pr.get('reason') or pr.get('error'))[:60]) if pr else ''),
                     cost=cost))
print(json.dumps({'rows': rows, 'totals': {k: {'done': v[0], 'avg_min': round(v[1] / v[0]) if v[0] else None, 'usd_list': round(v[2], 2)}
                                          for k, v in tot.items()}}, indent=1))
