"""Rebuild dashboard.html locally. No git, no upload.

WHY THIS EXISTS SEPARATELY FROM publish_dashboard.py. That script did two jobs:
it rebuilt the page (resolve_live_data.py, then dashboard.py --quiet) and then
pushed the result to GitHub Pages. The push is what got the account suspended,
so its scheduled task is disabled -- and disabling it silently took the REBUILD
with it, leaving the served page frozen at whatever it last wrote.

This is the rebuild half on its own. serve_dashboard.py shells out to it for the
Refresh button, and a scheduled task runs it periodically, so the two paths
cannot drift.

Exit codes: 0 built, 1 build failed. resolve_live_data failing is not fatal --
it only backfills results already present in the data file, and a stale result
column beats no dashboard at all.
"""
import subprocess
import sys
import time
from pathlib import Path

ROOT = Path(r'E:\soccer')
DASH = ROOT / 'dashboard.html'
PY = sys.executable


def _run(script, fatal):
    """Run one build step. Returns True on success."""
    t0 = time.time()
    p = subprocess.run([PY, str(ROOT / 'main' / script)] +
                       (['--quiet'] if script == 'dashboard.py' else []),
                       cwd=str(ROOT), capture_output=True, text=True,
                       encoding='utf-8', errors='replace')
    took = time.time() - t0
    if p.returncode == 0:
        print(f'  {script}: ok in {took:.1f}s')
        return True
    tail = (p.stdout or '') + (p.stderr or '')
    print(f'  {script}: rc={p.returncode} in {took:.1f}s\n{tail[-800:]}')
    return not fatal


def main():
    stamp = time.strftime('%Y-%m-%d %H:%M:%S')
    print(f'[{stamp}] rebuilding dashboard')
    before = DASH.stat().st_mtime if DASH.exists() else 0

    _run('resolve_live_data.py', fatal=False)
    if not _run('dashboard.py', fatal=True):
        return 1

    if not DASH.exists():
        print('  dashboard.py exited cleanly but wrote no dashboard.html')
        return 1
    if DASH.stat().st_mtime <= before:
        # a silent no-write is the failure mode that leaves a stale page up
        # looking healthy, which is the whole thing this guards against
        print('  dashboard.html was not rewritten')
        return 1
    print(f'  wrote {DASH.stat().st_size:,} bytes')
    return 0


if __name__ == '__main__':
    sys.exit(main())
