#!/usr/bin/env python3
"""Watch podium.md and rebuild standalone-podium.html + prep.html whenever it changes.
Runs in background; polls every 1.5 seconds; only rebuilds on mtime change."""
import os, sys, time, subprocess
from pathlib import Path

PREP_DIR = Path(__file__).resolve().parent
PODIUM = PREP_DIR / 'podium.md'
LOG = PREP_DIR / 'watch_podium.log'

def log(msg):
    ts = time.strftime('%H:%M:%S')
    line = f'[{ts}] {msg}'
    print(line, flush=True)
    with open(LOG, 'a') as f:
        f.write(line + '\n')

def rebuild():
    log('podium.md changed — rebuilding…')
    try:
        # 1. Re-render the podium HTML section
        subprocess.check_call(['python3', '/tmp/render_podium_from_md.py'], stdout=subprocess.DEVNULL)
        # 2. Re-render the standalone offline HTML
        subprocess.check_call(['python3', '/tmp/build_standalone.py'], stdout=subprocess.DEVNULL)
        # 3. Re-render the full prep.html (so Podium tab is fresh)
        subprocess.check_call(['python3', '/tmp/build_content.py'], stdout=subprocess.DEVNULL)
        log('  ✓ rebuilt standalone-podium.html and prep.html')
    except Exception as e:
        log(f'  ✗ rebuild failed: {e}')

def main():
    log(f'Watching {PODIUM}')
    last_mtime = PODIUM.stat().st_mtime if PODIUM.exists() else 0
    # Build once at start to make sure things are fresh
    rebuild()
    while True:
        try:
            mtime = PODIUM.stat().st_mtime if PODIUM.exists() else 0
            if mtime != last_mtime:
                last_mtime = mtime
                rebuild()
            time.sleep(1.5)
        except KeyboardInterrupt:
            log('stopping')
            sys.exit(0)
        except Exception as e:
            log(f'watch loop error: {e}')
            time.sleep(3)

if __name__ == '__main__':
    main()
