"""Background proxy/storyboard builder.

Builds the 720p30 playback proxy + scrub storyboard for every registered
VOD, newest first, ONE per cycle before re-scanning — so a freshly finished
recording always jumps the queue instead of waiting behind a backfill.
Builds are atomic (tmp + replace); killing the worker mid-build is safe.
"""
import os
import threading
import time

from clipshelf import problems
from clipshelf import config
from clipshelf import db, vod_assets

POLL_S = 300
SETTLE_S = 300


def _next_missing():
    conn = db.connect()
    try:
        vods = conn.execute(
            "SELECT id, filename FROM vods WHERE duration_ms > 0"
            " ORDER BY start_epoch DESC").fetchall()
    finally:
        conn.close()
    for v in vods:
        master = os.path.join(config.VOD_DIR, v["filename"])
        if not os.path.exists(master):
            continue
        if time.time() - os.path.getmtime(master) < SETTLE_S:
            continue    # still recording
        has_proxy = os.path.exists(vod_assets.proxy_path(v["filename"]))
        has_board = vod_assets.board_info(v["filename"]) is not None
        if not (has_proxy and has_board):
            return v["filename"]
    return None


def loop():
    time.sleep(60)
    while True:
        try:
            name = _next_missing()
            if name:
                vod_assets.build_all(name)
                continue    # immediately re-scan — a newer vod may have landed
        except Exception as e:
            problems.record("scrub proxies", e, "check free disk space")
        time.sleep(POLL_S)


def start():
    threading.Thread(target=loop, daemon=True).start()
