import argparse
import time
import requests
import subprocess
import os
import re
import shutil
import threading
import sys
import platform
import json
import signal
import zipfile
import tarfile
import gzip
import traceback
import ctypes
import hashlib
from datetime import datetime, timedelta

# Textual TUI (optional — install with: pip install textual)
# Minimum required version: 0.20 (RichLog, ModalScreen, Binding, DataTable etc.)
_TEXTUAL_MIN_VERSION = (0, 20)

_VENV_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.worker_venv')

def _bootstrap_textual():
    """Auto-install/upgrade textual if missing or too old, then re-exec.

    Strategy:
      1. Try plain pip install into the current interpreter (works on most systems).
      2. If pip rejects it (externally-managed-environment / PEP 668), create a
         local venv at _VENV_DIR and install there, then re-exec with that Python.
    """
    try:
        import textual as _t
        try:
            from importlib.metadata import version as _pkg_version
            _tv_str = _pkg_version('textual')
        except Exception:
            _tv_str = getattr(_t, '__version__', '0.0')
        if tuple(int(x) for x in _tv_str.split('.')[:2]) >= _TEXTUAL_MIN_VERSION:
            return  # already fine
        reason = f"textual {_tv_str} is too old (>= {'.'.join(str(x) for x in _TEXTUAL_MIN_VERSION)} required)"
    except ImportError:
        reason = "textual not found"
    print(f"[*] {reason} — attempting automatic install...")

    # Attempt 1: plain pip upgrade into current interpreter
    result = subprocess.run(
        [sys.executable, '-m', 'pip', 'install', '--upgrade', 'textual'],
        capture_output=True, text=True,
    )
    if result.returncode == 0:
        print("[*] textual installed — restarting...")
        os.execv(sys.executable, [sys.executable] + sys.argv)

    # Attempt 2: create/reuse a local venv and install there
    print("[*] pip install failed (system-managed env?) — trying local venv...")
    try:
        import venv as _venv
        if not os.path.isdir(_VENV_DIR):
            print(f"[*] Creating venv at {_VENV_DIR} ...")
            try:
                _venv.create(_VENV_DIR, with_pip=True)
            except BaseException as _ce:
                # Debian/Ubuntu without python3-venv: their venv module prints
                # an explanation and calls sys.exit(1), which is not an
                # Exception. Without this the whole worker exited here. Remove
                # the half-made folder so a later run can try again.
                import shutil as _sh
                _sh.rmtree(_VENV_DIR, ignore_errors=True)
                if isinstance(_ce, KeyboardInterrupt):
                    raise
                raise RuntimeError(f"could not create a virtual environment ({_ce or 'python3-venv missing?'})")
        venv_python = (
            os.path.join(_VENV_DIR, 'Scripts', 'python.exe')  # Windows
            if sys.platform == 'win32' else
            os.path.join(_VENV_DIR, 'bin', 'python')
        )
        result2 = subprocess.run(
            [venv_python, '-m', 'pip', 'install', '--upgrade', 'textual', 'requests'],
            capture_output=True, text=True,
        )
        if result2.returncode == 0:
            print(f"[*] textual installed in venv — restarting under {venv_python} ...")
            os.execv(venv_python, [venv_python] + sys.argv)
        else:
            print(f"[!] venv pip install failed:\n{result2.stderr.strip()}")
    except Exception as _ve:
        print(f"[!] venv setup failed: {_ve}")

    print("[!] Could not install textual automatically — continuing without TUI.")

def _tui_wanted():
    """The full-screen UI is only used on a terminal and without --no-tui, so
    there is nothing to install for a service, a log file or a cloud startup
    script. (Same rule as the later choice of display mode.)"""
    if '--no-tui' in sys.argv:
        return False
    if '--force-tui' in sys.argv:
        return True
    try:
        return sys.stdout.isatty()
    except Exception:
        return False

if _tui_wanted():
    _bootstrap_textual()

try:
    import textual as _textual_mod
    try:
        from importlib.metadata import version as _pkg_version
        _tv_str = _pkg_version('textual')
    except Exception:
        _tv_str = getattr(_textual_mod, '__version__', '0.0')
    _tv = tuple(int(x) for x in _tv_str.split('.')[:2])
    if _tv < _TEXTUAL_MIN_VERSION:
        raise ImportError(
            f"textual {_tv_str} is too old; "
            f">= {'.'.join(str(x) for x in _TEXTUAL_MIN_VERSION)} required"
        )
    from textual.app import App, ComposeResult
    from textual.widgets import Header, Footer, RichLog, DataTable, Button, Label
    from textual.screen import ModalScreen
    from textual.containers import Horizontal, Vertical
    from textual.binding import Binding
    HAS_TEXTUAL = True
    _TEXTUAL_UNAVAIL_REASON = ""
except ImportError as _e:
    HAS_TEXTUAL = False
    _TEXTUAL_UNAVAIL_REASON = str(_e)

# ==============================================================================
# CONFIGURATION
# ==============================================================================
DEFAULT_MANAGER_URL = "https://encode.fractumseraph.net/"
DEFAULT_USERNAME = "Anonymous"
DEFAULT_WORKERNAME = f"Node-{int(time.time())}"
WORKER_VERSION = "3.14.0"
WORKER_SECRET = os.environ.get("WORKER_SECRET", "DefaultInsecureSecret")

SHUTDOWN_EVENT = threading.Event()
# Set whenever the encoders are killed (Stop, a signal, a forced update). With
# SHUTDOWN_EVENT alone the worker is draining: active work is allowed to finish.
ABORT_EVENT = threading.Event()
UPDATE_AVAILABLE = False
LAST_UPDATE_CHECK = 0
CHECK_LOCK = threading.Lock()
CONSOLE_LOCK = threading.Lock()
PROGRESS_LOCK = threading.Lock()
MONITOR_PAUSED = threading.Event()
WORKER_PROGRESS = {} 
PAUSE_REQUESTED = False
ACTIVE_PROCS = {}
PROC_LOCK = threading.Lock()
TUI_APP = None  # Set to WorkerApp instance when running in TUI mode
_TUI_WAS_RUNNING = False  # Set True before app.run(), never cleared; guards safe_print post-TUI

def _plain_log():
    """True when output is not a terminal (a file, a pipe, the systemd
    journal). There, lines redrawn in place with '\\r' never end, so the
    journal received one enormous line; progress is written as ordinary,
    occasional lines instead."""
    try:
        return not sys.stdout.isatty()
    except Exception:
        return True
def _download_progress(pct):
    """Progress of the one-off FFmpeg download. On a terminal the line is
    redrawn in place. Anywhere else it is an ordinary line every 25%: one
    update per 8 KB block with no line ending added up to a single line of
    several hundred kilobytes, and Google Cloud's startup-script runner
    stops a script whose output line is longer than 64 KB."""
    try:
        if not _plain_log():
            sys.stdout.write(f"\r    Downloading... {pct}%")
            sys.stdout.flush()
            return
        step = pct // 25
        if _PLAIN_LAST.get('ffmpeg-download') != step:
            _PLAIN_LAST['ffmpeg-download'] = step
            if step:
                sys.stdout.write(f"    Downloading... {step * 25}%\n")
                sys.stdout.flush()
    except Exception:
        pass
_PLAIN_LAST = {}   # (worker_id, prefix) -> last percentage logged / last status line
_TUI_SIGNAL = None  # Set to 'pause' or 'quit' by signal handler, polled by app timer

# Per-worker rich state, polled by the TUI every 0.5s
# {"file": str, "phase": str, "pct": int, "job_start": float, "jobs_done": int}
WORKER_DETAILS = {}
SESSION_STATS = {"jobs_done": 0, "bytes_uploaded": 0, "start": 0.0}
STATS_LOCK = threading.Lock()
# How much CPU the video encodes of this session actually used (Linux only):
# total ffmpeg CPU-seconds, total encode wall-seconds, number of encodes.
ENC_USAGE = {"cpu": 0.0, "wall": 0.0, "n": 0, "slots": 1, "hinted": False}

# Chunked encoding: set to False once the manager responds 404 to /get_chunk
# (older manager) so we stop asking. Shared across worker threads.
_CHUNK_SUPPORT = {"ok": True}

# Global paths for executables
FFMPEG_CMD = "ffmpeg"
FFPROBE_CMD = "ffprobe"
_FFMPEG_META_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.ffmpeg_meta.json')

# Detect OS to handle Fonts
_script_dir = os.path.dirname(os.path.abspath(__file__))

ENCODING_CONFIG = {
    "VIDEO_CODEC": "libsvtav1",
    "VIDEO_PRESET": "2",
    "VIDEO_CRF": "57",           # one value for every video (no per-profile adjustment)
    "VIDEO_PIX_FMT": "yuv420p",
    "VIDEO_SCALE": "scale=-2:480",
    "AUDIO_CODEC": "libopus",
    "AUDIO_BITRATE": "24k",      # Perfect for Mono Speech
    "AUDIO_CHANNELS": "1",       # CHANGED: 2 -> 1 (Mono) for better quality
    "SUBTITLE_CODEC": "mov_text", 
    "OUTPUT_EXT": ".mp4"
}


class QuotaTracker:
    def __init__(self, limit_gb, worker_name):
        self.limit_bytes = int(limit_gb * 1024**3) if limit_gb > 0 else 0
        self.filename = f"usage_{re.sub(r'[^a-zA-Z0-9]', '', worker_name)}.json"
        self.lock = threading.Lock()
        self.current_usage = 0
        self.last_save = 0
        self._load()

    def _load(self):
        today = datetime.now().strftime("%Y-%m-%d")
        if os.path.exists(self.filename):
            try:
                with open(self.filename, 'r') as f:
                    data = json.load(f)
                    if data.get('date') == today:
                        self.current_usage = data.get('bytes', 0)
                    else:
                        self.current_usage = 0
                        self._save()
            except:
                self.current_usage = 0
        else:
            self.current_usage = 0

    def _save(self):
        today = datetime.now().strftime("%Y-%m-%d")
        try:
            # Atomic write (temp + rename) so a concurrent reader — e.g. another
            # worker process sharing this --workername, or check_cap() mid-write —
            # never sees a half-written file and mis-parses it as "under quota".
            tmp = f"{self.filename}.{os.getpid()}.tmp"
            with open(tmp, 'w') as f:
                json.dump({"date": today, "bytes": self.current_usage}, f)
            os.replace(tmp, self.filename)
        except: pass

    def check_cap(self):
        if self.limit_bytes <= 0: return False
        today = datetime.now().strftime("%Y-%m-%d")
        if os.path.exists(self.filename):
            try:
                with open(self.filename, 'r') as f:
                    data = json.load(f)
                    if data.get('date') != today:
                        with self.lock:
                            self.current_usage = 0
                            self._save()
                        return False
            except: pass
        with self.lock:
            return self.current_usage >= self.limit_bytes

    def add_usage(self, num_bytes):
        if self.limit_bytes <= 0: return
        with self.lock:
            self.current_usage += num_bytes
            if time.time() - self.last_save > 30:
                self._save()
                self.last_save = time.time()
    
    def force_save(self):
        with self.lock: self._save()

    def get_remaining_str(self):
        if self.limit_bytes <= 0: return "Unlimited"
        rem = self.limit_bytes - self.current_usage
        if rem < 0: rem = 0
        return f"{rem / 1024**3:.2f} GB"
    
    def get_wait_time(self):
        now = datetime.now()
        tomorrow = now + timedelta(days=1)
        midnight = datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=0, minute=0, second=1)
        return (midnight - now).total_seconds()


# ==============================================================================
# TEXTUAL TUI
# ==============================================================================

if HAS_TEXTUAL:
    from rich.text import Text

    # ---------------------------------------------------------------------------
    # Helpers
    # ---------------------------------------------------------------------------

    def _phase_style(phase: str) -> str:
        return {
            "Idle":       "dim",
            "Starting":   "dim",
            "Probe":      "cyan",
            "Opening":    "bold cyan",
            "Stalled":    "bold orange3",
            "Verifying":  "cyan",
            "DL":         "bold cyan",
            "Encoding":   "bold yellow",
            "Uploading":  "bold green",
            "Done":       "bright_green",
            "Failed":     "bold red",
            "Perm Error": "bold red",
            "Paused":     "bold orange3",
            "Quota":      "orange_red1",
            "Retrying":   "bold orange3",
        }.get(phase, "white")

    def _make_bar(pct: int, width: int = 10) -> str:
        pct = max(0, min(100, pct))
        filled = int(width * pct / 100)
        return "▓" * filled + "░" * (width - filled) + f" {pct:3d}%"

    def _fit_name(name: str, width: int) -> str:
        """Middle-truncate a display name: the START identifies the movie/show
        and the END carries the chunk tag ('... [3/12]'), so keep both and
        drop the release-group boilerplate in the middle."""
        if width < 8 or len(name) <= width:
            return name if len(name) <= width else name[:max(0, width)]
        # A trailing "[chunk 3]" / "[audio]" tag is kept whole: cut into, it
        # read as "…hunk 3]".
        _m = re.search(r'\s(\[[^\[\]]{1,16}\])$', name)
        if _m and len(_m.group(1)) + 5 <= width:
            tag = _m.group(1)
            room = width - len(tag) - 2          # "…" and the space before the tag
            return name[:room] + "… " + tag
        head = (width - 1) * 2 // 3
        tail = width - 1 - head
        return name[:head] + "…" + name[-tail:]

    def _fmt_elapsed(seconds: float) -> str:
        if seconds <= 0:
            return "-"
        s = int(seconds)
        h, r = divmod(s, 3600)
        m, sec = divmod(r, 60)
        return f"{h}:{m:02d}:{sec:02d}" if h else f"{m}:{sec:02d}"

    # ---------------------------------------------------------------------------
    # Pause modal
    # ---------------------------------------------------------------------------

    class PauseModal(ModalScreen):
        """Modal dialog shown when the worker is paused."""

        BINDINGS = [  # type: ignore[assignment]
            Binding("c", "choose_continue", show=False),
            Binding("f", "choose_finish", show=False),
            Binding("s", "choose_stop", show=False),
            Binding("escape", "choose_continue", show=False),
        ]

        def compose(self) -> ComposeResult:
            on_windows = platform.system() == 'Windows'
            subtitle = "FFmpeg has been suspended." if not on_windows else "FFmpeg has been suspended (Windows)."
            with Vertical(id="pause-dialog"):
                yield Label("\u23f8  WORKER PAUSED", id="pause-title")
                yield Label(subtitle, id="pause-subtitle")
                # Text(), not str: "[C]" in a plain string is parsed as markup
                # and vanished, so the buttons gave no hint of their keys.
                yield Label(Text("C  Continue   carry on encoding"), classes="pause-help")
                yield Label(Text("F  Finish     complete the current work, then exit"), classes="pause-help")
                yield Label(Text("S  Stop       stop now and hand the work back"), classes="pause-help")
                with Horizontal(id="pause-buttons"):
                    yield Button(Text("[C] Continue"), id="btn-continue", variant="success")
                    yield Button(Text("[F] Finish"), id="btn-finish", variant="warning")
                    yield Button(Text("[S] Stop"), id="btn-stop", variant="error")

        def action_choose_continue(self) -> None: self.dismiss("continue")
        def action_choose_finish(self) -> None: self.dismiss("finish")
        def action_choose_stop(self) -> None: self.dismiss("stop")

        def on_key(self, event) -> None:
            """Explicit key handler — belt-and-suspenders in case BINDINGS
            don't fire (known issue in some Textual versions over SSH/tmux)."""
            key = event.key
            if key in ('c', 'escape'): self.dismiss("continue")
            elif key == 'f':           self.dismiss("finish")
            elif key == 's':           self.dismiss("stop")

        def on_button_pressed(self, event: Button.Pressed) -> None:
            choices = {"btn-continue": "continue", "btn-finish": "finish", "btn-stop": "stop"}
            if event.button.id in choices:
                self.dismiss(choices[event.button.id])

    # ---------------------------------------------------------------------------
    # Main application
    # ---------------------------------------------------------------------------

    class WorkerApp(App):
        """Fractum Distributed Worker \u2014 Textual TUI."""

        CSS = """
        Screen {
            background: $background;
        }
        #workers-table {
            height: auto;
            max-height: 16;
            margin: 1 1 0 1;
            border: solid $primary;
        }
        #stats-bar {
            height: 1;
            margin: 0 2;
            background: $surface-darken-1;
            color: $text-muted;
            padding: 0 1;
        }
        #log-panel {
            height: 1fr;
            margin: 0 1 1 1;
            border: solid $primary-darken-2;
        }
        PauseModal {
            align: center middle;
            background: $background 75%;
        }
        #pause-dialog {
            background: $surface;
            border: thick $warning;
            padding: 1 3;
            width: 66;
            max-width: 100%;
            height: auto;
        }
        #pause-title {
            width: 100%;
            text-align: center;
            color: $warning;
            text-style: bold;
            padding-bottom: 1;
        }
        #pause-subtitle {
            width: 100%;
            text-align: center;
            color: $text-muted;
            padding-bottom: 1;
        }
        .pause-help {
            width: 100%;
            color: $text;
        }
        #pause-buttons {
            height: auto;
            width: 100%;
            padding-top: 1;
        }
        /* Equal shares of the row: with fixed-width buttons the third one
           was pushed past the edge of the dialog and cut off. */
        #pause-buttons Button { width: 1fr; min-width: 10; margin: 0 1; }
        """

        BINDINGS = [  # type: ignore[assignment]
            Binding("p", "request_pause", "Pause", show=True, priority=True),
            Binding("q", "request_quit",  "Quit", show=True, priority=True),
        ]
        # Textual's command palette (ctrl+p) has nothing useful here and its
        # footer hint sat next to the real keys.
        ENABLE_COMMAND_PALETTE = False

        def __init__(self, worker_ids: list, threads: list,
                     quota_tracker=None, manager_url: str = "", **kwargs):
            super().__init__(**kwargs)
            self._worker_ids = worker_ids
            self._threads = threads
            self._quota_tracker = quota_tracker
            self._manager_url = manager_url
            # Column keys assigned in on_mount
            self._col_file = self._col_phase = self._col_bar = None
            self._col_elapsed = self._col_done = self._col_eta = None
            self._file_w = 32  # real value computed from terminal width in on_mount
            # Monotonic timestamp recorded when the pause modal is first shown.
            # Used by _check_signals to distinguish a genuine second press (force-stop)
            # from the race-condition echo of the *same* keypress handled by both
            # Textual's binding and the _tty_key_reader fallback simultaneously.
            self._pause_requested_at = 0.0

        def compose(self) -> ComposeResult:
            yield Header()
            # can_focus=False here (not just in on_mount) prevents the DataTable from
            # receiving keyboard focus before on_mount runs.  In recent Textual versions
            # DataTable captures unrecognised keys for its internal row-search feature
            # instead of bubbling them, so focus on startup caused the first 'p' press
            # to be swallowed and the second press to actually trigger the App binding.
            yield DataTable(id="workers-table", show_cursor=False)
            yield Label("", id="stats-bar", markup=False)
            # wrap: long lines (file names) used to run off the right edge
            # behind a horizontal scrollbar. highlight off: it coloured stray
            # numbers inside file names ("2019", "1080") for no reason.
            yield RichLog(id="log-panel", highlight=False, markup=False, wrap=True, max_lines=1000)
            yield Footer()

        def on_mount(self) -> None:
            table = self.query_one("#workers-table", DataTable)
            # Explicit column widths. Without them, DataTable sizes each column
            # to its header + the initial '-' placeholder and update_width=False
            # freezes that forever — "Current File" was stuck at 12 cells and
            # "ETA" at 3, clipping everything written into them later.
            # Every row belongs to the same user, so the "username-" prefix is
            # dropped from the row labels (it is in the title bar instead).
            # With it, an 18-cell column showed "FractumSera…sair-1": the user
            # name twice over and the worker name cut in half.
            _prefix = ""
            if self._worker_ids and '-' in self._worker_ids[0]:
                _cand = self._worker_ids[0].split('-', 1)[0] + '-'
                if all(w.startswith(_cand) and len(w) > len(_cand) for w in self._worker_ids):
                    _prefix = _cand
            self._row_labels = {w: w[len(_prefix):] for w in self._worker_ids}
            w_worker = max(6, min(22, max((len(l) for l in self._row_labels.values()), default=6)))
            # Fixed columns + per-cell padding + table chrome; whatever is left
            # of the terminal goes to the file name column.
            fixed = w_worker + 10 + 21 + 7 + 6 + 7 + (2 * 7) + 6
            self._file_w = max(16, min(64, get_term_width() - fixed))
            _cw               = table.add_column("Worker",       width=w_worker)
            self._col_file    = table.add_column("Current File", width=self._file_w)
            self._col_phase   = table.add_column("Phase",        width=10)
            self._col_bar     = table.add_column("Progress",     width=21)
            self._col_elapsed = table.add_column("Elapsed",      width=7)
            self._col_done    = table.add_column("Done",         width=6)
            self._col_eta     = table.add_column("ETA",          width=7)
            for wid in self._worker_ids:
                # Long worker ids get middle-truncated for display; the row KEY
                # stays the full id, so updates and lookups are unaffected. The
                # thread suffix (-1/-2) survives at the end.
                # Text(), not str: a plain string is parsed as Rich markup, and
                # anything in [square brackets] silently disappears.
                table.add_row(Text(_fit_name(self._row_labels[wid], w_worker)), "-", "Starting",
                              _make_bar(0), "-", "0", "-", key=wid)
            self.title = "Fractum Distributed Worker"
            url_display = self._manager_url or "no manager"
            _who = _prefix.rstrip('-')
            _n = len(self._worker_ids)
            self.sub_title = (f"v{WORKER_VERSION}"
                              + (f"  \u2502  {_who}" if _who else "")
                              + f"  \u2502  {_n} job slot{'s' if _n != 1 else ''}  \u2502  {url_display}")
            self.set_interval(0.5, self._tick)
            self.set_interval(0.25, self._check_signals)
            self.set_interval(1.5, self._check_all_done)
            # Prevent these widgets from stealing focus and swallowing key events.
            # Belt-and-suspenders: can_focus=False is also set in the constructor,
            # but re-set here for safety in case Textual ever resets it internally.
            self.query_one("#workers-table").can_focus = False
            self.query_one("#log-panel").can_focus = False
            # Drop focus from any widget so the App (and its BINDINGS) receives
            # key events directly from the first keypress, not the second.
            self.set_focus(None)
            # NOTE: do NOT write raw escape sequences to sys.stdout here.
            # Textual owns the terminal once on_mount fires; writing outside its
            # rendering pipeline corrupts its cursor-position tracking and causes
            # subsequent renders to land at wrong positions (e.g. on the stats bar).
            # Mouse-tracking cleanup is handled exclusively by the atexit handler
            # and the reset block that runs after app.run() returns.
            # Start a fallback key reader on /dev/tty.  On some SSH/tmux setups
            # Textual's own input driver receives no key events; reading /dev/tty
            # directly bypasses that entirely.  We only read p/q here so we
            # don't conflict with Textual's normal key handling in healthy envs.
            threading.Thread(target=self._tty_key_reader, daemon=True).start()

        def _tty_key_reader(self) -> None:
            """Read single chars from /dev/tty to set _TUI_SIGNAL as a fallback
            for environments where Textual's input driver is broken (SSH/tmux)."""
            global _TUI_SIGNAL
            try:
                import tty, termios, atexit
                tty_fd = open('/dev/tty', 'rb', buffering=0)
                old = termios.tcgetattr(tty_fd)
                # Register atexit BEFORE entering cbreak mode so the terminal is
                # always restored even if the daemon thread is killed mid-read on
                # program exit (blocking read(1) won't unblock for the finally).
                def _restore_tty():
                    try:
                        termios.tcsetattr(tty_fd, termios.TCSADRAIN, old)
                        tty_fd.close()
                    except Exception:
                        pass
                atexit.register(_restore_tty)
                tty.setcbreak(tty_fd)
                try:
                    while not SHUTDOWN_EVENT.is_set():
                        ch = tty_fd.read(1)
                        if not ch:
                            break
                        c = ch.decode('utf-8', errors='ignore').lower()
                        if PAUSE_REQUESTED:
                            # While paused, route c/f/s as pause-choice signals
                            if c == 'c':
                                _TUI_SIGNAL = 'choice:continue'
                            elif c == 'f':
                                _TUI_SIGNAL = 'choice:finish'
                            elif c == 's':
                                _TUI_SIGNAL = 'choice:stop'
                        else:
                            if c == 'p' and _TUI_SIGNAL is None:
                                _TUI_SIGNAL = 'pause'
                            elif c == 'q' and _TUI_SIGNAL is None:
                                _TUI_SIGNAL = 'quit'
                finally:
                    # Normal clean exit — unregister the atexit handler and
                    # restore immediately so it doesn't run a second time.
                    atexit.unregister(_restore_tty)
                    _restore_tty()
            except Exception:
                pass  # Not available on Windows or if /dev/tty is inaccessible

        # ------------------------------------------------------------------
        # Periodic refresh
        # ------------------------------------------------------------------

        def _tick(self) -> None:
            """Refresh the workers table and stats bar from shared state."""
            table = self.query_one("#workers-table", DataTable)
            now = time.time()

            for wid in self._worker_ids:
                d = WORKER_DETAILS.get(wid, {})
                phase     = d.get("phase", "Starting")
                pct       = d.get("pct", 0)
                filename  = d.get("file", "-")
                job_start = d.get("job_start", 0.0)
                jobs_done = d.get("jobs_done", 0)
                jobs_failed = d.get("jobs_failed", 0)

                idle_phases = {"Idle", "Starting", "Quota", "Done", "Failed", "Perm Error"}
                elapsed = (now - job_start) if job_start > 0 and phase not in idle_phases else 0.0

                # ETA: estimate remaining time from elapsed and progress
                if pct > 5 and elapsed > 0 and phase == "Encoding":
                    eta_sec = elapsed * (100 - pct) / pct
                else:
                    eta_sec = 0.0

                style = _phase_style(phase)
                phase_text = Text(phase, style=style)
                # "Opening" has no percentage to show - ffmpeg is still pulling
                # the header and seeking - so the bar is replaced by a ticking
                # clock. A frozen 0% bar is exactly what made a slow link look
                # like a hung worker.
                note = d.get("note", "")
                if phase == "Opening":
                    spin = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"[int(now * 8) % 10]
                    bar_body = f"{spin} reading src {note}"
                elif phase in {"Idle", "Starting"}:
                    bar_body = ""
                else:
                    bar_body = _make_bar(pct)
                    speed = d.get("speed", "")
                    if phase == "Stalled" and note:
                        bar_body += f" {note}"
                    elif speed:
                        bar_body += f" {speed}"
                bar_text = Text(bar_body.ljust(21)[:21], style=style)

                # Middle truncation: keep the identifying start AND the chunk
                # tag at the end (previously only the tail was kept, so every
                # row read '\u20261080p.BluRay.x264-OFT.mkv').
                fn_display = _fit_name(filename, self._file_w)
                done_display = f"{jobs_done}" if not jobs_failed else f"{jobs_done} \u2717{jobs_failed}"

                try:
                    # Text(): "[chunk 3/31]" in a plain string is taken for
                    # markup and dropped, so chunk rows showed only the file.
                    table.update_cell(wid, self._col_file,    Text(fn_display),        update_width=False)
                    table.update_cell(wid, self._col_phase,   phase_text,              update_width=False)
                    table.update_cell(wid, self._col_bar,     bar_text,                update_width=False)
                    table.update_cell(wid, self._col_elapsed, _fmt_elapsed(elapsed),   update_width=False)
                    table.update_cell(wid, self._col_done,    done_display,            update_width=False)
                    table.update_cell(wid, self._col_eta,     _fmt_elapsed(eta_sec),   update_width=False)
                except Exception:
                    pass

            # Stats bar
            with STATS_LOCK:
                jd = SESSION_STATS.get("jobs_done", 0)
                bu = SESSION_STATS.get("bytes_uploaded", 0)
                st = SESSION_STATS.get("start", now)
            uptime_str = _fmt_elapsed(now - st)
            gb_str = f"{bu / 1024 ** 3:.2f} GB"
            quota_str = ""
            if self._quota_tracker:
                quota_str = f"  \u2502  Quota Remaining: {self._quota_tracker.get_remaining_str()}"
            stats = (
                f"  Jobs Completed: {jd}"
                f"  \u2502  Uploaded: {gb_str}"
                f"  \u2502  Uptime: {uptime_str}"
                f"{quota_str}"
            )
            try:
                self.query_one("#stats-bar", Label).update(stats)
            except Exception:
                pass

        async def _check_signals(self) -> None:
            """Poll the signal flag set by the OS signal handler or tty key reader."""
            global _TUI_SIGNAL
            sig = _TUI_SIGNAL
            if sig is None:
                return
            _TUI_SIGNAL = None
            if sig == 'pause':
                if not PAUSE_REQUESTED:
                    await self.action_request_pause()
                else:
                    # Second Ctrl+C / P while already paused = force stop.
                    # Debounce: if the modal was shown less than 0.5 s ago, this
                    # signal is almost certainly the same keypress being handled by
                    # both Textual's binding and the _tty_key_reader fallback at the
                    # same time (race condition).  Ignore it; the modal stays open.
                    if time.monotonic() - self._pause_requested_at < 0.5:
                        return
                    if isinstance(self.screen, PauseModal):
                        self.screen.dismiss("stop")
                    else:
                        self._handle_pause_result('stop')
            elif sig == 'quit':
                self.action_request_quit()
            elif sig.startswith('choice:'):
                choice = sig[len('choice:'):]
                # SSH/tmux keyboard fallback: dismiss the modal so the callback
                # fires automatically, rather than calling _handle_pause_result
                # directly (which would leave the modal open on screen).
                if isinstance(self.screen, PauseModal):
                    self.screen.dismiss(choice)
                else:
                    self._handle_pause_result(choice)

        def _check_all_done(self) -> None:
            if SHUTDOWN_EVENT.is_set() and all(not t.is_alive() for t in self._threads):
                self.exit()

        # ------------------------------------------------------------------
        # Thread-safe log write (called via call_from_thread)
        # ------------------------------------------------------------------

        def write_log(self, message: str) -> None:
            try:
                self.query_one("#log-panel", RichLog).write(message)
            except Exception:
                pass

        def update_worker_status(self, worker_id: str, status: str) -> None:
            # Status is now driven by WORKER_DETAILS polling in _tick; this is a no-op.
            pass

        # ------------------------------------------------------------------
        # Pause / quit actions
        # ------------------------------------------------------------------

        async def action_request_pause(self) -> None:
            global PAUSE_REQUESTED
            if PAUSE_REQUESTED:
                return
            PAUSE_REQUESTED = True
            self._pause_requested_at = time.monotonic()
            threading.Thread(target=lambda: toggle_processes(suspend=True),
                             daemon=True).start()
            # Show the popup modal — buttons are mouse-clickable on Windows;
            # keyboard C/F/S work via Textual bindings or the _tty_key_reader
            # fallback for SSH/tmux (which dismisses the modal via _check_signals).
            self.push_screen(PauseModal(), callback=self._handle_pause_result)

        def _handle_pause_result(self, choice) -> None:
            global PAUSE_REQUESTED
            if choice == "continue":
                PAUSE_REQUESTED = False
                threading.Thread(target=lambda: toggle_processes(suspend=False),
                                 daemon=True).start()
                self.write_log("[*] Encoding resumed.")
            elif choice == "finish":
                PAUSE_REQUESTED = False
                threading.Thread(target=lambda: toggle_processes(suspend=False),
                                 daemon=True).start()
                SHUTDOWN_EVENT.set()
                self.write_log("[*] Finishing active jobs, then stopping...")
            elif choice == "stop":
                threading.Thread(target=lambda: toggle_processes(suspend=False),
                                 daemon=True).start()
                kill_processes()
                SHUTDOWN_EVENT.set()
                PAUSE_REQUESTED = False
                self.write_log("[*] Stopping immediately...")
                self.set_timer(1.5, self.exit)

        def action_request_quit(self) -> None:
            SHUTDOWN_EVENT.set()
            kill_processes()
            self.exit()


def _run_text_pause_menu() -> str:
    """Synchronous text pause menu shown when the TUI is suspended.

    Reads directly from /dev/tty so it works even when stdin is piped.
    Returns 'continue', 'finish', or 'stop'.
    """
    src = None
    if not sys.stdin.isatty():
        try:
            src = open('/dev/tty', 'r')
        except Exception:
            pass
    try:
        sys.stdout.write("\n" + "="*40 + "\n")
        sys.stdout.write(" [!] WORKER PAUSED\n")
        sys.stdout.write("="*40 + "\n")
        sys.stdout.write(" [C]ontinue  - Resume encoding\n")
        sys.stdout.write(" [F]inish    - Finish active, then stop\n")
        sys.stdout.write(" [S]top      - Abort immediately\n")
        sys.stdout.write(" Ctrl+C      - Force abort\n")
        sys.stdout.flush()
        while True:
            try:
                prompt_src = src if src else sys.stdin
                sys.stdout.write("Select [c/f/s]: ")
                sys.stdout.flush()
                line = prompt_src.readline()
                if not line:
                    return 'stop'
                ch = line.strip().lower()
                if ch in ('c', ''):
                    return 'continue'
                if ch == 'f':
                    return 'finish'
                if ch == 's':
                    return 'stop'
            except KeyboardInterrupt:
                sys.stdout.write("\n[*] Force abort.\n")
                sys.stdout.flush()
                return 'stop'
            except EOFError:
                return 'stop'
    finally:
        if src:
            try:
                src.close()
            except Exception:
                pass


def get_auth_headers():
    headers = {'User-Agent': f'FractumWorker/{WORKER_VERSION}'}
    if WORKER_SECRET:
        headers['X-Worker-Token'] = WORKER_SECRET
    return headers

def get_term_width():
    try: return shutil.get_terminal_size((80, 20)).columns
    except: return 80

def safe_print(message):
    # During interpreter shutdown daemon threads can't safely acquire the
    # internal C-level lock on BufferedWriter, causing a Fatal Python error.
    # Bail out early — nobody is reading stdout at that point anyway.
    if sys.is_finalizing():
        return
    if TUI_APP is not None:
        try:
            TUI_APP.call_from_thread(TUI_APP.write_log, message)
        except Exception:
            pass
        # Never fall through to direct stdout writes while the TUI owns the
        # terminal — writing raw bytes into Textual's alternate screen places
        # stray characters wherever the cursor happens to be (often top-left
        # during a render cycle).
        return
    # After the TUI exits (TUI_APP set back to None) but before Python fully
    # finalizes, daemon threads can briefly reach sys.stdout.write().  The
    # C-level BufferedWriter lock may already be destroyed by then, causing
    # "Fatal Python error: _enter_buffered_busy" which cannot be caught.
    # sys.is_finalizing() has a race window — SHUTDOWN_EVENT closes it.
    if _TUI_WAS_RUNNING and SHUTDOWN_EVENT.is_set():
        return
    if not CONSOLE_LOCK.acquire(timeout=2):
        return
    try:
        if _plain_log():
            sys.stdout.write(message + '\n')
            sys.stdout.flush()
            return
        # Long messages are no longer cut to the terminal width: that took
        # the chunk tag off the end of every "Chunk job" line, and under a
        # service (no terminal, width assumed 80) it cut every line in the
        # journal. A long line simply wraps.
        # \033[K (Erase to End of Line) clears any leftover chars from a
        # previously longer line drawn at the same position — avoids the
        # padding-width-mismatch flicker that occurred on terminal resize.
        sys.stdout.write(f'\r{message}\033[K\n')
        sys.stdout.flush()
    except Exception:
        # Absolute fallback
        try: print(message)
        except Exception: pass
    finally:
        CONSOLE_LOCK.release()

def log(worker_id, message, level="INFO"):
    timestamp = datetime.now().strftime("%H:%M:%S")
    safe_print(f"[{timestamp}] [{worker_id}] [{level}] {message}")

def signal_handler(sig, frame):
    global PAUSE_REQUESTED, _TUI_SIGNAL
    if platform.system() == 'Windows':
        SHUTDOWN_EVENT.set()
        try: kill_processes()
        except: pass
        if TUI_APP is not None:
            # Route through the TUI's quit action so Textual can restore the
            # Windows console mode (echo, VT processing, cursor visibility)
            # before the process exits.  sys.exit() here skips that cleanup.
            _TUI_SIGNAL = 'quit'
        else:
            try:
                sys.stdout.write('\n[!] Shutdown initiated...\n')
                sys.stdout.flush()
            except Exception:
                pass
        return  # Let app.run() / join loop exit naturally
    else:
        if TUI_APP is not None:
            # In TUI mode, Ctrl+C opens the pause menu so the user can choose
            # Continue / Finish / Stop.  SIGTERM still shuts down cleanly.
            if sig == signal.SIGTERM:
                SHUTDOWN_EVENT.set()
                try: kill_processes()
                except: pass
                _TUI_SIGNAL = 'quit'
            else:
                # SIGINT (Ctrl+C) → request pause via flag; the app's polling
                # timer picks this up on the event loop thread (call_from_thread
                # cannot be used from a signal handler — same thread as the loop).
                _TUI_SIGNAL = 'pause'
        elif sig == signal.SIGTERM:
            # "systemctl stop" / "kill": nobody is there to answer a pause
            # menu. Stop the encoders and exit; the threads hand their work
            # back and a whole-file encode keeps its partial file to resume.
            # (This used to open the pause menu, fail to read an answer, and
            # only then abort.)
            SHUTDOWN_EVENT.set()
            try: kill_processes()
            except: pass
            try:
                sys.stdout.write('\n[!] Stop requested (SIGTERM). Shutting down...\n')
                sys.stdout.flush()
            except: pass
        elif not PAUSE_REQUESTED:
            PAUSE_REQUESTED = True
            try:
                sys.stdout.write('\n\n[!] PAUSE REQUESTED (Stopping gracefully...)\n')
                sys.stdout.flush()
            except: pass
        else:
            # Second Ctrl+C while already pausing = force abort, as the pause
            # menu advertises. A custom SIGINT handler means readline never
            # raises KeyboardInterrupt, so abort here directly. os._exit is
            # abrupt by design (that's what "force" means); ffmpeg children are
            # killed first.
            try: kill_processes()
            except: pass
            try:
                sys.stdout.write('\n[!] Force abort.\n')
                sys.stdout.flush()
            except: pass
            os._exit(1)

def toggle_processes(suspend=True):
    if platform.system() == 'Windows':
        # Windows has no SIGSTOP/SIGCONT, but NtSuspendProcess / NtResumeProcess
        # (ntdll.dll) achieve the identical effect: all threads in the target
        # process are frozen atomically.  ctypes is stdlib — no extra deps.
        try:
            ntdll    = ctypes.windll.ntdll
            kernel32 = ctypes.windll.kernel32
            PROCESS_ALL_ACCESS = 0x1F0FFF
            with PROC_LOCK:
                for wid, proc in ACTIVE_PROCS.items():
                    if proc.poll() is None:
                        try:
                            h = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, proc.pid)
                            if h:
                                if suspend:
                                    ntdll.NtSuspendProcess(h)
                                else:
                                    ntdll.NtResumeProcess(h)
                                kernel32.CloseHandle(h)
                        except Exception as _e:
                            safe_print(f"[!] Could not {'suspend' if suspend else 'resume'} PID {proc.pid}: {_e}")
        except Exception as _e:
            if suspend:
                safe_print(f"[!] WARNING: Windows process suspension unavailable: {_e}")
        return
    with PROC_LOCK:
        for wid, proc in ACTIVE_PROCS.items():
            if proc.poll() is None:
                try:
                    sig = signal.SIGSTOP if suspend else signal.SIGCONT  # type: ignore[attr-defined]
                    os.kill(proc.pid, sig)
                except: pass

def kill_processes():
    ABORT_EVENT.set()
    with PROC_LOCK:
        for wid, proc in ACTIVE_PROCS.items():
            try:
                if proc.poll() is None: proc.kill()
            except: pass

# The update that check_version() found and vetted, held for apply_update().
_PENDING_UPDATE = {"body": None, "version": None}
# Set (and inherited across the re-exec) when installing a version failed, so
# the worker does not stop its work every ten minutes to fail the same way.
_UPDATE_FAILED_ENV = "FRACTUM_UPDATE_FAILED"

def _vet_update(body):
    """Return the version string of a downloaded worker script, or None when
    the download is not a complete, valid worker (an error page served with a
    200, a truncated transfer). Installing such a file would leave a worker
    that cannot start, and nothing would ever repair it."""
    try:
        text = body.decode('utf-8')
    except (UnicodeDecodeError, AttributeError):
        return None
    match = re.search(r'^WORKER_VERSION\s*=\s*"([^"]+)"', text, re.M)
    if not match or 'def run_worker(' not in text or '__main__' not in text:
        return None
    try:
        compile(text, 'worker.py', 'exec')
    except (SyntaxError, ValueError):
        return None
    return match.group(1)

def check_version(manager_url):
    global LAST_UPDATE_CHECK
    with CHECK_LOCK:
        if time.time() - LAST_UPDATE_CHECK < 600: return False
        LAST_UPDATE_CHECK = time.time()
    try:
        url = f"{manager_url}/dl/worker"
        r = requests.get(url, headers=get_auth_headers(), timeout=30)
        if r.status_code == 200:
            # Bytes, not r.text: the script is written back exactly as served,
            # whatever charset the response claims.
            body = r.content
            match = re.search(rb'^WORKER_VERSION\s*=\s*"([^"]+)"', body, re.M)
            if not match: return False
            new_version = match.group(1).decode('ascii', 'replace')
            if new_version == WORKER_VERSION: return False
            if os.environ.get(_UPDATE_FAILED_ENV) == new_version: return False
            if _vet_update(body) != new_version:
                safe_print(f"[!] Update {new_version} offered by the manager is incomplete or invalid. Ignoring it.")
                return False
            _PENDING_UPDATE["body"] = body; _PENDING_UPDATE["version"] = new_version
            safe_print(f"[!] Update found: {WORKER_VERSION} -> {new_version}")
            return True
    except: pass
    return False

def apply_update(manager_url):
    safe_print("[*] Downloading and applying update...")
    tmp_path = None
    target_path = os.path.abspath(sys.argv[0])
    version = _PENDING_UPDATE.get("version") or "?"
    try:
        body = _PENDING_UPDATE.get("body")
        if body is None:
            r = requests.get(f"{manager_url}/dl/worker", headers=get_auth_headers(), timeout=30)
            if r.status_code != 200:
                raise RuntimeError(f"HTTP {r.status_code}")
            body = r.content
            version = _vet_update(body)
            if version is None:
                raise RuntimeError("downloaded script is incomplete or invalid")
        tmp_path = target_path + '.tmp'
        with open(tmp_path, 'wb') as f:
            f.write(body)
        os.replace(tmp_path, target_path)
    except Exception as e:
        safe_print(f"[!] Failed to apply update: {e}")
        if tmp_path:
            try:
                if os.path.exists(tmp_path): os.remove(tmp_path)
            except: pass
        # Carry on with the current version rather than exit: a worker that
        # quits here stays down until someone notices.
        os.environ[_UPDATE_FAILED_ENV] = str(version)
        safe_print("[*] Continuing on the current version.")
    safe_print("[*] Restarting worker...")
    try:
        os.execv(sys.executable, [sys.executable] + sys.argv)
    except Exception as e:
        safe_print(f"[!] Could not restart the worker: {e}")

def print_progress(worker_id, current, total, prefix='', suffix=''):
    if total <= 0: return
    percent = min(100, int(100 * current / float(total)))
    if TUI_APP is not None:
        # Update WORKER_DETAILS so the polling _tick() picks it up
        d = WORKER_DETAILS.get(worker_id)
        if d is not None:
            phase_map = {'DL': 'DL', 'Enc': 'Encoding', 'Up': 'Uploading'}
            d["phase"] = phase_map.get(prefix, prefix)
            d["pct"]   = percent
        return
    if sys.is_finalizing():
        return
    if _plain_log():
        # One ordinary line each time another 10% is reached.
        step = percent // 10
        key = (worker_id, prefix)
        if _PLAIN_LAST.get(key) != step:
            _PLAIN_LAST[key] = step
            if step > 0 or current >= total:
                names = {'Enc': 'Encoding', 'Up': 'Uploading', 'DL': 'Downloading'}
                log(worker_id, f"{names.get(prefix, prefix)} {percent}%")
        if current >= total:
            _PLAIN_LAST.pop(key, None)
        return
    width = get_term_width()
    overhead = 12 + len(worker_id) + len(prefix) + 10 + len(suffix)
    bar_length = width - overhead - 5
    if bar_length < 10: bar_length = 10
    filled_length = int(bar_length * current // total)
    
    block_char = '█'
    fill_char = '-'
    
    try:
        bar = block_char * filled_length + fill_char * (bar_length - filled_length)
        line = f'[{datetime.now().strftime("%H:%M:%S")}] [{worker_id}] {prefix} |{bar}| {percent}% {suffix}'
        if len(line) > width - 1:
            line = line[:width - 1]
        with CONSOLE_LOCK:
            sys.stdout.write(f'\r{line}\033[K')
            sys.stdout.flush()
            
    except UnicodeEncodeError:
        block_char = '='
        fill_char = '-'
        try:
            bar = block_char * filled_length + fill_char * (bar_length - filled_length)
            line = f'[{datetime.now().strftime("%H:%M:%S")}] [{worker_id}] {prefix} |{bar}| {percent}% {suffix}'
            if len(line) > width - 1: line = line[:width - 1]
            with CONSOLE_LOCK:
                sys.stdout.write(f'\r{line}\033[K')
                sys.stdout.flush()
        except: pass 

    if current >= total: 
        try: sys.stdout.write('\n')
        except: pass

def monitor_status_loop(worker_ids):
    while not SHUTDOWN_EVENT.is_set():
        # Daemon threads writing to stdout after interpreter shutdown started
        # will crash Python at the C level — bail out early.
        if sys.is_finalizing():
            return
        if TUI_APP is not None:
            time.sleep(1); continue  # TUI handles all status display
        if PAUSE_REQUESTED or MONITOR_PAUSED.is_set():
             time.sleep(0.5); continue
        parts = []
        with PROGRESS_LOCK:
            for wid in sorted(worker_ids, key=lambda x: x.split('-')[-1]):
                try: short_id = wid.split('-')[-1]
                except: short_id = wid
                state = WORKER_PROGRESS.get(wid, "Idle")
                parts.append(f"[{short_id}: {state}]")
        if parts and _plain_log():
            # No in-place status line without a terminal: one ordinary line
            # a minute, and only when something changed.
            line = " ".join(parts)
            now = time.time()
            if line != _PLAIN_LAST.get('status') and now - _PLAIN_LAST.get('status_at', 0) >= 60:
                _PLAIN_LAST['status'] = line; _PLAIN_LAST['status_at'] = now
                safe_print(f"[{datetime.now().strftime('%H:%M:%S')}] Status: {line}")
            time.sleep(0.5)
            continue
        if parts:
            line = " ".join(parts)
            width = get_term_width()
            if len(line) > width - 4: line = line[:width-4] + "..."
            with CONSOLE_LOCK:
                try:
                    sys.stdout.write(f'\r{line}\033[K')
                    sys.stdout.flush()
                except: pass
        time.sleep(0.5)

def get_seconds(t):
    try:
        parts = t.split(':')
        h = int(parts[0]); m = int(parts[1]); s = float(parts[2])
        return h*3600 + m*60 + s
    except: return 0

# ==============================================================================
# ENCODE HEARTBEAT
# ==============================================================================

def _start_heartbeat(fn, interval=30):
    """Run fn() every `interval` seconds on a daemon thread until the returned
    Event is set. Used to keep sending status to the manager even while the
    encode loop is blocked in readline() (e.g. ffmpeg SIGSTOP'd during a pause),
    so a long pause doesn't get the job/chunk reassigned. Extra posts are
    harmless; the loop's own 10s posts continue when it's running."""
    stop = threading.Event()
    def _run():
        while not stop.wait(interval):
            try: fn()
            except Exception: pass
    threading.Thread(target=_run, daemon=True).start()
    return stop

# ==============================================================================
# RESUME / PARTIAL ENCODE HELPERS
# ==============================================================================

_RESUME_CHK_PREFIX = "resume_chk_"

def _media_duration(file_path):
    """Duration of a local media file in seconds, or None when it CANNOT be
    determined. None and 0.0 must stay distinguishable: chunk output is written
    as a fragmented MP4 (empty_moov), whose container duration some ffprobe
    builds report as absent — treating that "unknown" as "zero" made the
    post-encode self-check discard perfectly good chunks as truncated."""
    # 1. container duration (cheap, works for most files)
    try:
        res = subprocess.run(
            [FFPROBE_CMD, '-v', 'quiet', '-print_format', 'json',
             '-show_format', '-show_streams', file_path],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            encoding='utf-8', errors='replace', timeout=60)
        data = json.loads(res.stdout)
        dur = data.get('format', {}).get('duration')
        if dur and float(dur) > 0:
            return float(dur)
        # 2. per-stream duration (present when the container's is not)
        best = 0.0
        for st in data.get('streams', []):
            try: best = max(best, float(st.get('duration') or 0))
            except (TypeError, ValueError): pass
        if best > 0:
            return best
    except Exception:
        pass
    # 3. last resort for fragmented output: read the final packet timestamp.
    #    Only reached when the cheap paths gave nothing, so the cost is rare.
    try:
        res = subprocess.run(
            [FFPROBE_CMD, '-v', 'quiet', '-select_streams', 'v:0',
             '-show_entries', 'packet=pts_time', '-of', 'csv=p=0', file_path],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            encoding='utf-8', errors='replace', timeout=180)
        times = [float(x) for x in (res.stdout or '').split() if x.strip() and x.strip() != 'N/A']
        if times:
            return max(times)
    except Exception:
        pass
    return None

_PROGRESS_KEYS = ('frame=', 'fps=', 'stream_', 'bitrate=', 'total_size=', 'out_time=',
                  'out_time_us=', 'out_time_ms=', 'dup_frames=', 'drop_frames=',
                  'speed=', 'progress=')

def _error_tail(log_buffer, lines=25):
    """The ffmpeg lines worth reporting: '-progress pipe:1' emits a key=value
    block several times a second, so a raw tail of the buffer is pure progress
    noise and the actual error scrolls out of the report. Keep real messages."""
    real = [l.rstrip() for l in log_buffer
            if l.strip() and not l.strip().startswith(_PROGRESS_KEYS)]
    if not real:
        real = [l.rstrip() for l in log_buffer if l.strip()]
    return "\n".join(real[-lines:])

def _http_input_flags(headers):
    """ffmpeg input options for pulling a source over HTTPS.

    -reconnect_on_http_error is the important one: the source sits behind
    Cloudflare, and a 522 (origin unreachable) or a 429 on one Range request
    otherwise aborts the whole encode with "Server returned 5XX Server Error
    reply" - work thrown away over a blip. Reconnecting inside ffmpeg fixes it
    before the job ever notices. -rw_timeout turns a silently wedged socket
    into a reconnect instead of an encode that hangs until the lease expires,
    and -multiple_requests reuses the connection across chunk seeks."""
    return [
        '-headers', headers,
        '-reconnect', '1', '-reconnect_streamed', '1',
        '-reconnect_delay_max', '60', '-reconnect_on_network_error', '1',
        '-reconnect_on_http_error', '5xx,429',
        '-multiple_requests', '1',
        '-rw_timeout', '60000000',
    ]

# AVERROR values ffmpeg exits with, by their exact 32-bit value.
_AVERROR_NAMES = {
    -1094995529: "Invalid data found when processing input",
    -1482175992: "source server returned 5xx",
    -1482175736: "source server returned 4xx",
    -858797304:  "source server returned 403 Forbidden",
    -875574520:  "source server returned 404 Not Found",
    -541478725:  "End of file",
    -1313558101: "Unknown error",
    -22:         "Invalid argument",
    -5:          "Input/output error",
    -32:         "Broken pipe",
    -104:        "Connection reset by peer",
    -110:        "Connection timed out",
}
# POSIX exit() keeps only the low byte, so several AVERRORs collapse onto the
# same status. Only name the byte where the collapse is unambiguous enough to
# be worth saying; 8 covers every AVERROR_HTTP_* at once, so say that much.
_AVERROR_LOW_BYTE = {
    183: "Invalid data found when processing input",
    234: "Invalid argument",
    8:   "source/HTTP error",
    251: "Input/output error",
    224: "Broken pipe",
    152: "Connection reset by peer",
    146: "Connection timed out",
}

# A finished encode is hours of work. Three quick attempts used to be all it
# got, so a manager restart or a wedged manager threw the result away. Keep
# trying for roughly twenty minutes before giving up.
_UPLOAD_RETRY_DELAYS = (10, 30, 60, 120, 300, 300, 300)

def _upload_with_retry(url, open_file, upload_name, data, worker_id, what, keepalive=None):
    """POST a finished encode to the manager, retrying while it is unreachable.

    Returns (outcome, detail). outcome is 'ok', 'final' (the manager answered
    and has already settled the matter: do not report a failure on top), or
    'failed'. open_file() must return a context manager yielding a file object.
    keepalive(), when given, is called about every 30s while waiting so the
    manager does not hand the work to someone else in the meantime.
    """
    total = len(_UPLOAD_RETRY_DELAYS) + 1
    last = "no attempt made"
    for attempt in range(total):
        if attempt > 0:
            # A draining or stopping worker delivers once, without retries, so
            # a dead network cannot hold up the exit for twenty minutes.
            if SHUTDOWN_EVENT.is_set(): break
            delay = _UPLOAD_RETRY_DELAYS[attempt - 1]
            log(worker_id, f"{what} upload failed ({last}). Retrying in {delay}s "
                           f"(attempt {attempt + 1}/{total})...", "WARN")
            waited = 0
            while waited < delay and not SHUTDOWN_EVENT.is_set():
                time.sleep(1); waited += 1
                if keepalive and waited % 30 == 0:
                    try: keepalive()
                    except Exception: pass
            if SHUTDOWN_EVENT.is_set(): break
        try:
            with open_file() as f:
                r = requests.post(url, files={'file': (upload_name, f)}, data=data,
                                  headers=get_auth_headers(), timeout=300)
        except Exception as e:
            last = str(e)[:200] or e.__class__.__name__
            continue
        if r.status_code == 200:
            return 'ok', ''
        if r.status_code in (400, 404, 409):
            # 409: reassigned/reset while we encoded. 400: failed the manager's
            # verification, which it has already recorded. 404: job is gone.
            msg = ''
            try: msg = str(r.json().get('message', ''))
            except Exception: pass
            return 'final', f"HTTP {r.status_code} {msg}".strip()
        if r.status_code in (401, 403, 413):
            # Retrying cannot change these.
            hint = " (file exceeds the manager proxy's upload size limit)" if r.status_code == 413 else ""
            return 'failed', f"HTTP {r.status_code}{hint}"
        last = f"HTTP {r.status_code}"
    return 'failed', last

def _ffmpeg_rc_text(rc):
    """Human-readable form of an ffmpeg exit status.

    ffmpeg exits with the raw AVERROR it failed on. Windows keeps the whole
    32-bit value, POSIX truncates it to the low byte, so the SAME failure is
    reported as 3199971767 on one node and 183 on another and neither number
    means anything to someone reading the admin panel."""
    try:
        rc = int(rc)
    except (TypeError, ValueError):
        return str(rc)
    for signed, text in _AVERROR_NAMES.items():
        if rc == signed or rc == (signed & 0xFFFFFFFF):
            return f"{rc} ({text})"
    if rc == 3:
        # MSVCRT abort(); on our nodes that means an ffmpeg assertion fired.
        return f"{rc} (aborted \u2014 assertion failure)"
    if rc in _AVERROR_LOW_BYTE:
        return f"{rc} ({_AVERROR_LOW_BYTE[rc]})"
    return str(rc)

# Substrings that mean "we could not READ THE SOURCE", not "this encode is
# bad". The source is served over HTTPS through Cloudflare, so a 522 (origin
# unreachable) or a Range response cut short mid-transfer shows up as an
# ffmpeg failure even though nothing is wrong with the job. Those are worth
# waiting out: a chunk given up on here is a chunk another node has to redo.
# Deliberately excludes 4xx other than 429: a 403/404 is the source being
# permanently wrong, and backing off for minutes before failing anyway only
# delays the report.
_SOURCE_READ_ERRORS = (
    'server returned 5xx',
    'http error 5',
    'http error 429',
    'server returned 429',
    'cannot determine format of input',
    'connection reset by peer',
    'connection timed out',
    'error in the pull function',
    'i/o error',
    'input/output error',
    'stream ends prematurely',
    'error opening input: end of file',
)

def _is_source_read_failure(log_buffer):
    """True when the ffmpeg log blames reading the input, not the encode."""
    for line in log_buffer[-60:]:
        low = line.lower()
        if any(tok in low for tok in _SOURCE_READ_ERRORS):
            return True
    return False

# ---------------------------------------------------------------------------
# Source-read diagnostics. When FFmpeg cannot read the source, the error report
# used to carry only FFmpeg's version banner: an FFmpeg stuck while opening the
# file prints nothing else. These helpers record what the manager needs to tell
# a worker-side problem (network, FFmpeg build) from a source-host problem.
# ---------------------------------------------------------------------------
_FFMPEG_BUILD_INFO = None

def _ffmpeg_build_info():
    """FFmpeg's version and the TLS library it was built with (cached)."""
    global _FFMPEG_BUILD_INFO
    if _FFMPEG_BUILD_INFO is None:
        info = {"version": "?", "tls": "?"}
        try:
            out = subprocess.run([FFMPEG_CMD, '-hide_banner', '-version'], capture_output=True,
                                 text=True, errors='replace', timeout=20).stdout or ''
            first = out.splitlines()[0] if out else ''
            m = re.search(r'ffmpeg version (\S+)', first)
            if m: info["version"] = m.group(1)[:80]
            libs = [lib for lib in ('openssl', 'gnutls', 'mbedtls', 'libtls', 'schannel', 'securetransport')
                    if f'--enable-{lib}' in out]
            if libs:
                info["tls"] = ",".join(libs)
            elif sys.platform == 'win32':
                info["tls"] = "schannel (Windows default)"
            elif sys.platform == 'darwin':
                info["tls"] = "securetransport (macOS default)"
            else:
                info["tls"] = "none listed"
        except Exception:
            pass
        _FFMPEG_BUILD_INFO = info
    return _FFMPEG_BUILD_INFO

def _source_selftest(url, offset=0, seconds=8.0, max_bytes=16 * 1024 * 1024):
    """Download a little of the source from where the encode needed it, the way
    FFmpeg would (same URL, same token, a Range request). Returns a dict:
    resolved addresses, HTTP status, time to first byte, speed, or the error."""
    import socket
    from urllib.parse import urlsplit
    res = {"offset": int(max(0, offset))}
    try:
        parts = urlsplit(url)
        host = parts.hostname or ''
        port = parts.port or (443 if parts.scheme == 'https' else 80)
        res["host"] = host
        t = time.time()
        addrs = socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)
        res["dns_ms"] = int((time.time() - t) * 1000)
        res["ips"] = sorted({a[4][0] for a in addrs})[:4]
    except Exception as e:
        res["error"] = f"DNS lookup failed: {type(e).__name__}: {str(e)[:160]}"
        return res
    try:
        hdrs = get_auth_headers()
        hdrs['Range'] = f"bytes={res['offset']}-"
        t = time.time()
        r = requests.get(url, headers=hdrs, stream=True, timeout=(15, 30))
        res["status"] = r.status_code
        res["ttfb_ms"] = int((time.time() - t) * 1000)
        n = 0; t2 = time.time()
        try:
            if r.status_code in (200, 206):
                for blk in r.iter_content(256 * 1024):
                    n += len(blk)
                    if n >= max_bytes or time.time() - t2 >= seconds:
                        break
        finally:
            r.close()
        el = max(time.time() - t2, 0.001)
        res["bytes"] = n
        res["secs"] = round(el, 2)
        res["mb_s"] = round(n / el / 1e6, 2)
        if r.status_code not in (200, 206):
            res["error"] = f"HTTP {r.status_code}"
    except Exception as e:
        res["error"] = f"{type(e).__name__}: {str(e)[:200]}"
    return res

def _source_failure_diag(watch, url, is_local, offset=0):
    """Everything a source-read failure report should carry (see above)."""
    d = {"diag_version": 1, "worker_version": WORKER_VERSION,
         "os": f"{platform.system()} {platform.release()}"[:60],
         "ffmpeg": _ffmpeg_build_info(),
         "source": "local file" if is_local else "http"}
    if watch is not None:
        d.update(watch.diag())
    if not is_local:
        d["selftest"] = _source_selftest(url, offset)
    return d

def _diag_text(d):
    """The same diagnostics as readable lines, for the report's details."""
    out = ["", "--- Source-read diagnostics (worker) ---"]
    ff = d.get("ffmpeg") or {}
    out.append(f"Worker {d.get('worker_version')} on {d.get('os')}; FFmpeg {ff.get('version')} (TLS: {ff.get('tls')})")
    ph = d.get("phase")
    if ph == "probing":
        out.append("FFprobe could not read the source's stream information (3 attempts).")
    elif ph == "opening":
        out.append(f"FFmpeg never got past opening the source ({d.get('waited_s', 0)}s without a first frame).")
    elif ph == "encoding":
        out.append(f"Frames stopped at {d.get('pos_s', 0)}s into the encode ({d.get('pct', 0)}%); "
                   f"no progress for {d.get('stalled_s', 0)}s.")
    st = d.get("selftest")
    if st:
        if st.get("error"):
            out.append(f"Download test from this worker FAILED: {st['error']} "
                       f"(host {st.get('host')}, resolved {', '.join(st.get('ips') or []) or '-'})")
        else:
            out.append(f"Download test from this worker: HTTP {st.get('status')}, first byte {st.get('ttfb_ms')} ms, "
                       f"{st.get('mb_s')} MB/s over {st.get('secs')}s (resolved {', '.join(st.get('ips') or [])})")
    return "\n".join(out)

def _clean_stopped_output(path):
    """Make the output of an ffmpeg that was stopped mid-encode safe to use.

    Fragmented MP4 keeps everything already written, but the file ends in a
    half-written fragment: stream-copying it into the final assembly produced
    an unreadable file. Remux it, cutting just before the last readable frame.
    Returns the cleaned duration in seconds, or None if it could not be done
    (the caller then treats the encode as failed)."""
    try:
        res = subprocess.run([FFPROBE_CMD, '-v', 'error', '-select_streams', 'v:0',
                              '-show_entries', 'packet=pts_time', '-of', 'csv=p=0', path],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             encoding='utf-8', errors='replace', timeout=900)
        times = []
        for tok in (res.stdout or '').split():
            try: times.append(float(tok.strip(',')))
            except ValueError: pass
        if not times:
            return None
        keep = max(times) - 0.25
        if keep <= 0:
            return None
        tmp = path + '.clean.mp4'
        rc = subprocess.run([FFMPEG_CMD, '-v', 'error', '-y', '-i', path, '-map', '0', '-c', 'copy',
                             '-t', f'{keep:.3f}',
                             '-movflags', 'frag_keyframe+empty_moov+default_base_moof', tmp],
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1800)
        if rc.returncode != 0 or not os.path.exists(tmp) or os.path.getsize(tmp) == 0:
            try: os.remove(tmp)
            except OSError: pass
            return None
        os.replace(tmp, path)
        return keep
    except Exception:
        return None

class _ResumeDone(Exception):
    """Raised inside the resume block when the checkpoint needs no more work."""

class _StreamWatch:
    """Keeps the display honest while ffmpeg is quiet.

    There is no separate download step to put a progress bar on: the worker
    hands ffmpeg the URL and ffmpeg streams the source as it encodes. What
    looked like a frozen worker is the gap BEFORE the first frame - ffmpeg
    connecting, pulling the matroska header, then seeking to the chunk's
    offset over HTTP Range. On a slow link that is minutes long, and the read
    loop cannot tick the display through it because readline() is blocked
    waiting for output that has not been produced yet. So tick from here:
    count up while we wait for the source, and once frames are flowing, say
    so when they stop."""

    OPEN_GRACE_SEC = 3.0    # a fast open should not flash "reading src"
    STALL_SEC      = 120.0  # no progress for this long = say something
    BEAT_SEC       = 60.0   # keep the manager's stale-chunk sweeper off us
    # Encodes have been seen frozen within the last seconds of a source for
    # hours or days: ffmpeg keeps printing progress with the SAME out_time, so
    # the job heartbeats and nothing ever times it out. Past these limits the
    # watch stops ffmpeg; the caller then keeps the output if it is complete
    # to within a few seconds, or retries.
    STALL_KILL_SEC = 900.0   # frames were flowing, then none for 15 min
    OPEN_KILL_SEC  = 1800.0  # never produced a first frame in 30 min

    def __init__(self, update_status, single_mode=False, heartbeat=None, measure=False):
        self._update = update_status
        self._single = single_mode
        # measure: sample this ffmpeg's CPU time (video encodes only), to
        # learn how many CPU threads one encode really uses on this machine.
        self._measure = measure
        self._cpu_last = None       # (cpu seconds, wall time of that sample)
        self._cpu_first = None
        self._ticks = 0
        self._paused_ever = False
        # The chunk read loop only reports to the manager from inside its
        # out_time branch, so a long source-open sends NOTHING for its whole
        # duration and CHUNK_STALE_SECONDS can hand the chunk to another node
        # while this worker is still legitimately fetching it. Beat here too.
        self._heartbeat = heartbeat
        self._last_beat = time.time()
        self._lock = threading.Lock()
        self._started = time.time()
        self._last_progress = 0.0   # 0 = no frame has ever landed
        self._pct = 0
        self._stop = threading.Event()
        self._thread = None
        self._last_said = 0.0
        self._pos = -1.0
        self._proc = None
        self._was_paused = False
        self.stall_killed = False

    def attach(self, proc):
        """Let the watch stop this ffmpeg if it stalls for good."""
        self._proc = proc
        return self

    def note_progress(self, pct, pos=None):
        """Called from the read loop for each progress line. `pos` is the
        output position in seconds: ffmpeg repeats its progress block even
        when nothing new was encoded, so only an ADVANCING position counts —
        without it a frozen encode looked alive forever."""
        with self._lock:
            if pos is None or pos > self._pos + 0.001 or not self._last_progress:
                self._last_progress = time.time()
                if pos is not None:
                    self._pos = pos
            self._pct = pct

    def diag(self):
        """Where the read stopped, for a failure report: still opening the
        source, or partway through the encode (and since when)."""
        with self._lock:
            last, started, pos, pct = self._last_progress, self._started, self._pos, self._pct
        now = time.time()
        if not last:
            return {"phase": "opening", "waited_s": int(now - started),
                    "killed_by_watchdog": self.stall_killed}
        return {"phase": "encoding", "pos_s": round(max(pos, 0.0), 1), "pct": pct,
                "stalled_s": int(now - last), "killed_by_watchdog": self.stall_killed}

    def kill_reason(self):
        """Why the watch stopped ffmpeg, in words (only meaningful after a kill)."""
        if not self._last_progress:
            return f"FFmpeg could not open the source within {int(self.OPEN_KILL_SEC // 60) or 1} min"
        return f"Encode stalled with no progress for {int(self.STALL_KILL_SEC // 60) or 1} min"

    def start(self):
        self._thread = threading.Thread(target=self._run, daemon=True)
        self._thread.start()
        return self

    def stop(self):
        self._stop.set()
        first, last = self._cpu_first, self._cpu_last
        if first and last and not self._paused_ever and not self.stall_killed:
            wall = last[1] - first[1]
            if wall >= 60:
                with STATS_LOCK:
                    ENC_USAGE["cpu"] += last[0] - first[0]
                    ENC_USAGE["wall"] += wall
                    ENC_USAGE["n"] += 1

    def _sample_cpu(self):
        """CPU seconds used so far by the attached ffmpeg (Linux /proc)."""
        proc = self._proc
        if proc is None:
            return
        try:
            with open(f"/proc/{proc.pid}/stat", "r") as f:
                rest = f.read().rsplit(")", 1)[1].split()
            cpu = (int(rest[11]) + int(rest[12])) / float(os.sysconf("SC_CLK_TCK"))
        except Exception:
            self._measure = False       # not Linux, or the process is gone
            return
        self._cpu_last = (cpu, time.time())
        if self._cpu_first is None:
            self._cpu_first = self._cpu_last

    def _run(self):
        while not self._stop.wait(1.0):
            if SHUTDOWN_EVENT.is_set():
                continue
            if PAUSE_REQUESTED:
                self._was_paused = True
                self._paused_ever = True
                continue
            self._ticks += 1
            if self._measure and self._ticks % 5 == 0:
                self._sample_cpu()
            if self._was_paused:
                # Time spent paused is not a stall: restart both clocks.
                self._was_paused = False
                with self._lock:
                    self._started = time.time()
                    if self._last_progress:
                        self._last_progress = time.time()
            self._beat()
            with self._lock:
                last, pct, started = self._last_progress, self._pct, self._started
            now = time.time()
            if not last:
                waited = now - started
                if waited >= self.OPEN_GRACE_SEC:
                    self._say(f"Open {_fmt_mmss(waited)}",
                              f"waiting for source... {_fmt_mmss(waited)}")
                if waited >= self.OPEN_KILL_SEC:
                    self._kill()
            else:
                stalled = now - last
                if stalled >= self.STALL_SEC:
                    self._say(f"Stall {_fmt_mmss(stalled)}",
                              f"stalled {_fmt_mmss(stalled)} at {pct}%")
                if stalled >= self.STALL_KILL_SEC:
                    self._kill()

    def _kill(self):
        proc = self._proc
        if proc is None or self.stall_killed or proc.poll() is not None:
            return
        self.stall_killed = True
        try: proc.kill()
        except Exception: pass

    def _beat(self):
        if not self._heartbeat or time.time() - self._last_beat < self.BEAT_SEC:
            return
        self._last_beat = time.time()
        try:
            self._heartbeat()
        except Exception:
            pass

    def _say(self, status, single_line):
        if not self._single:
            self._update(status)
            return
        # No TUI row to update in single mode, and one line a second would
        # bury the log, so speak up only occasionally.
        now = time.time()
        if now - self._last_said >= 15.0:
            self._last_said = now
            safe_print(f"    ... {single_line}")

def _jobs_hint():
    """Once per session: if the video encodes so far left most of this
    machine's CPU idle, return a one-line note that more job slots are possible.
    Based on measured ffmpeg CPU time, not on the core count alone."""
    cores = os.cpu_count() or 1
    with STATS_LOCK:
        if ENC_USAGE["hinted"] or ENC_USAGE["n"] < 3 or ENC_USAGE["wall"] < 1200:
            return None
        per_encode = ENC_USAGE["cpu"] / ENC_USAGE["wall"]     # CPU threads one encode keeps busy
        slots = ENC_USAGE["slots"]
        if cores < 4 or per_encode < 0.5:
            return None
        in_use = per_encode * slots
        if in_use >= 0.6 * cores:
            return None
        better = min(32, cores // 2, int(0.85 * cores / per_encode))
        if better <= slots:
            return None
        ENC_USAGE["hinted"] = True
    # Running below full load is a perfectly good choice (heat, noise, the
    # power bill), so this only states what was measured and what the option is.
    return (f"Note: each encode has been using about {per_encode:.1f} of this machine's {cores} CPU "
            f"threads, with {slots} job slot{'s' if slots != 1 else ''} running. That is fine if you "
            f"want to keep heat and power use down. If you would rather use more of the machine, "
            f"--jobs {better} is the setting (it also needs more memory).")

def _set_speed(worker_id, line):
    """Stash ffmpeg's own 'speed=' figure for the display.

    On a slow link this is the number that explains everything: an encode
    creeping along at 0.2x is waiting on the network, not on the CPU, and
    without it the only visible symptom is a bar that barely moves."""
    try:
        val = line.split('=', 1)[1].strip()
        if not val or val == 'N/A':
            return
        # ffmpeg prints anything from "0.0578x" to "112x"; normalise so the
        # column cannot be cut mid-number (truncating "0.0578x" to six chars
        # produced a bare "0.0578" that read like a percentage).
        num = float(val.rstrip('xX'))
        if num >= 10:    txt = f"{num:.0f}x"
        elif num >= 1:   txt = f"{num:.1f}x"
        else:            txt = f"{num:.2f}x"
        d = WORKER_DETAILS.get(worker_id)
        if d is not None:
            d["speed"] = txt
    except Exception:
        pass

def _fmt_mmss(sec):
    sec = int(max(0, sec))
    return f"{sec // 60}:{sec % 60:02d}" if sec >= 60 else f"{sec}s"

def _probe_source_fps(src, is_local, http_headers):
    """Return the source video's r_frame_rate as an 'N/D' string, or None.
    Header-only probe: cheap even for a multi-GB remote source."""
    try:
        cmd = [FFPROBE_CMD, '-v', 'quiet']
        if not is_local and http_headers:
            cmd += ['-headers', http_headers]
        cmd += ['-select_streams', 'v:0', '-show_entries', 'stream=r_frame_rate',
                '-of', 'csv=p=0', src]
        res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             encoding='utf-8', errors='replace', timeout=60)
        val = (res.stdout or '').strip().splitlines()[0].strip() if res.stdout.strip() else ''
        return val if re.fullmatch(r'[1-9]\d*/[1-9]\d*', val) else None
    except Exception:
        return None

def _probe_local_duration(file_path):
    """Duration in seconds, or 0.0 when unknown (legacy callers)."""
    d = _media_duration(file_path)
    return d if d is not None else 0.0

def _save_resume_checkpoint(path, payload):
    """Atomically write a resume checkpoint JSON."""
    tmp = path + '.tmp'
    try:
        with open(tmp, 'w', encoding='utf-8') as f:
            json.dump(payload, f)
        os.replace(tmp, path)
    except Exception:
        try:
            if os.path.exists(tmp): os.remove(tmp)
        except Exception:
            pass

def _load_resume_checkpoints(temp_dir):
    """Return list of (path, data) for all resume checkpoints found in temp_dir."""
    results = []
    try:
        for fname in os.listdir(temp_dir):
            if fname.startswith(_RESUME_CHK_PREFIX) and fname.endswith('.json'):
                fpath = os.path.join(temp_dir, fname)
                try:
                    with open(fpath, 'r', encoding='utf-8') as f:
                        data = json.load(f)
                    results.append((fpath, data))
                except Exception:
                    pass
    except Exception:
        pass
    return results

# Number of bytes hashed for source-integrity check (must match server constant)
_HASH_BYTES = 4 * 1024 * 1024

def _compute_source_hash(dl_url, is_local):
    """Return MD5 hex digest of the first _HASH_BYTES of the source file.
    For local files the path is read directly; for remote URLs an HTTP Range
    request is used so we never need to download the whole file first.
    Returns None on any error so callers can skip the check gracefully."""
    h = hashlib.md5()
    try:
        if is_local:
            with open(dl_url, 'rb') as f:
                remaining = _HASH_BYTES
                while remaining > 0:
                    chunk = f.read(min(65536, remaining))
                    if not chunk:
                        break
                    h.update(chunk)
                    remaining -= len(chunk)
        else:
            headers = dict(get_auth_headers())
            headers['Range'] = f'bytes=0-{_HASH_BYTES - 1}'
            r = requests.get(dl_url, headers=headers, stream=True, timeout=30)
            # Accept both 206 Partial Content and 200 OK (some servers ignore Range)
            if r.status_code not in (200, 206):
                return None
            read = 0
            for chunk in r.iter_content(65536):
                if read >= _HASH_BYTES:
                    break
                if read + len(chunk) > _HASH_BYTES:
                    chunk = chunk[:_HASH_BYTES - read]
                h.update(chunk)
                read += len(chunk)
    except Exception:
        return None
    return h.hexdigest()

# ==============================================================================
# FFMPEG MANAGEMENT
# ==============================================================================

# Which FFmpeg the worker uses (README: "Which FFmpeg the worker uses").
#
# On Windows and Linux, x64 and arm64, the worker keeps its OWN copy of the
# newest FFmpeg RELEASE build from BtbN ("nX.Y-latest"), never "master-latest":
# master is a daily development snapshot, and nodes running snapshots hit real
# regressions (an mp4 muxer abort mid-encode, fragmented mp4 read back as
# 0-duration, and a build that hung on every HTTPS source it opened).
#
# - The newest release branch is found from BtbN's asset list; when that list
#   cannot be read (GitHub API rate limit, blocked page), newer branches are
#   found by asking whether the next version numbers exist.
# - A build is only used after a short test encode with libsvtav1 and libopus
#   on THIS machine: a build that cannot run here (CPU, OS, missing encoder) is
#   discarded and the next newest is tried; the build in use is kept until a
#   replacement has passed.
# - Each build lives in its own folder under ffmpeg_builds/. Switching only
#   changes which binary NEW encodes start, so encodes already running finish
#   on the build they started with and no file in use is ever replaced.
# - Checked at start and then every FFMPEG_BRANCH_CHECK_SEC while running; a
#   rebuild of the same release branch is picked up at most every
#   FFMPEG_REFRESH_SEC (each download is 100-200 MB).
_FFMPEG_FALLBACK_VERSIONS = ("9.0", "8.1")  # newest first; used only when discovery fails
_FFMPEG_DL_BASE = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/"
_FFMPEG_MIRROR = "https://vsv.fractumseraph.net/"   # Windows fallback when GitHub is unreachable
_FFMPEG_BUILDS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ffmpeg_builds')
FFMPEG_BRANCH_CHECK_SEC = 24 * 3600
FFMPEG_REFRESH_SEC = 7 * 24 * 3600
_FFMPEG_MGMT_LOCK = threading.Lock()
_FFMPEG_MANAGED = False      # True while the worker's own build is in use

def _windows_native_arch():
    """'x64', 'arm64' or 'x86' for the Windows MACHINE (not this Python: an
    x64 Python on an ARM64 PC runs emulated and reports AMD64)."""
    try:
        from ctypes import wintypes
        k = ctypes.windll.kernel32
        fn = getattr(k, 'IsWow64Process2', None)
        if fn is not None:
            k.GetCurrentProcess.restype = wintypes.HANDLE
            pm, nm = ctypes.c_ushort(0), ctypes.c_ushort(0)
            if fn(k.GetCurrentProcess(), ctypes.byref(pm), ctypes.byref(nm)):
                return {0xAA64: 'arm64', 0x8664: 'x64', 0x014C: 'x86'}.get(nm.value)
    except Exception:
        pass
    m = (os.environ.get('PROCESSOR_ARCHITEW6432') or os.environ.get('PROCESSOR_ARCHITECTURE')
         or platform.machine() or '').lower()
    if 'arm64' in m or 'aarch64' in m:
        return 'arm64'
    return 'x64' if m in ('amd64', 'x86_64') else (m or None)

def _ffmpeg_platform_tag():
    """(platform_tag, archive_ext) for BtbN asset names, or (None, None) when
    BtbN has no build for this OS/CPU (macOS, 32-bit, other architectures)."""
    system = platform.system()
    if system == "Windows":
        arch = _windows_native_arch()
        if arch == 'arm64': return "winarm64", "zip"
        if arch == 'x64':   return "win64", "zip"
        return None, None
    if system == "Linux":
        arch = platform.machine().lower()
        if arch in ('x86_64', 'amd64'):  return "linux64", "tar.xz"
        if arch in ('aarch64', 'arm64'): return "linuxarm64", "tar.xz"
    return None, None

def _vt(version):
    """'9.0' -> (9, 0) for comparisons."""
    try:
        a, b = str(version).split('.')[:2]
        return (int(a), int(b))
    except Exception:
        return (0, 0)

def _ffmpeg_asset_name(version):
    plat, ext = _ffmpeg_platform_tag()
    return f"ffmpeg-n{version}-latest-{plat}-gpl-{version}.{ext}"

def _ffmpeg_asset_exists(version):
    try:
        r = requests.head(_FFMPEG_DL_BASE + _ffmpeg_asset_name(version), allow_redirects=True, timeout=20,
                          headers={'User-Agent': f'FractumWorker/{WORKER_VERSION}'})
        return r.status_code == 200
    except Exception:
        return False

def _ffmpeg_release_versions():
    """Release branches BtbN publishes for this platform, newest first ('9.0')."""
    plat, ext = _ffmpeg_platform_tag()
    if not plat:
        return []
    hdrs = {'User-Agent': f'FractumWorker/{WORKER_VERSION}'}
    names = []
    try:
        r = requests.get("https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/latest",
                         headers=dict(hdrs, Accept='application/vnd.github+json'), timeout=20)
        if r.status_code == 200:
            names = [a.get('name', '') for a in r.json().get('assets', [])]
    except Exception:
        pass
    if not names:
        try:
            r = requests.get("https://github.com/BtbN/FFmpeg-Builds/releases/expanded_assets/latest",
                             headers=hdrs, timeout=20)
            if r.status_code == 200:
                names = re.findall(r'ffmpeg-n[\d.]+-latest-[a-z0-9]+-gpl-[\d.]+\.(?:zip|tar\.xz)', r.text)
        except Exception:
            pass
    pat = re.compile(rf'^ffmpeg-n(\d+)\.(\d+)-latest-{plat}-gpl-(\d+)\.(\d+)\.{re.escape(ext)}$')
    found = set()
    for n in set(names):
        m = pat.match(n)
        if m and m.group(1) == m.group(3) and m.group(2) == m.group(4):
            found.add(f"{m.group(1)}.{m.group(2)}")
    listed = bool(found)
    # Look past the newest known branch: the next minor and the next major.
    # This is what finds a new release when the list could not be read.
    newest = max((_vt(v) for v in (found or _FFMPEG_FALLBACK_VERSIONS)), default=(0, 0))
    for _ in range(4):
        step = None
        for cand in ((newest[0], newest[1] + 1), (newest[0] + 1, 0)):
            v = f"{cand[0]}.{cand[1]}"
            if v not in found and _ffmpeg_asset_exists(v):
                found.add(v); step = cand
                break
        if step is None:
            break
        newest = step
    if not listed:
        found.update(_FFMPEG_FALLBACK_VERSIONS)
    return sorted(found, key=_vt, reverse=True)

def _ffmpeg_selftest(ffmpeg, ffprobe):
    """(ok, reason): can this build do our encodes ON THIS MACHINE? Checks the
    encoders and version, then encodes one second with libsvtav1 + libopus and
    reads the result back with the matching ffprobe."""
    if not ffmpeg_is_capable(ffmpeg):
        return False, "missing libsvtav1 or libopus, or older than FFmpeg 7.1"
    os.makedirs(_FFMPEG_BUILDS_DIR, exist_ok=True)
    tmp = os.path.join(_FFMPEG_BUILDS_DIR, f"selftest_{os.getpid()}_{threading.get_ident()}.mkv")
    try:
        res = subprocess.run([ffmpeg, '-hide_banner', '-nostdin', '-v', 'error', '-y',
                              '-f', 'lavfi', '-i', 'testsrc2=size=320x240:rate=24',
                              '-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000',
                              '-t', '1', '-map', '0:v', '-map', '1:a',
                              '-c:v', 'libsvtav1', '-preset', '12', '-crf', '50', '-pix_fmt', 'yuv420p',
                              '-c:a', 'libopus', '-b:a', '24k', '-ac', '1', '-f', 'matroska', tmp],
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8',
                             errors='replace', timeout=180)
        if res.returncode != 0 or not os.path.exists(tmp) or os.path.getsize(tmp) == 0:
            return False, f"test encode failed (rc={res.returncode}): {(res.stdout or '').strip()[-200:]}"
        pr = subprocess.run([ffprobe, '-v', 'error', '-show_entries', 'stream=codec_name',
                             '-of', 'csv=p=0', tmp], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            encoding='utf-8', errors='replace', timeout=60)
        codecs = set((pr.stdout or '').split())
        if pr.returncode != 0 or not {'av1', 'opus'} <= codecs:
            return False, f"ffprobe could not read the test encode back ({' '.join(sorted(codecs)) or pr.returncode})"
        return True, ""
    except Exception as e:
        return False, f"{type(e).__name__}: {str(e)[:200]}"
    finally:
        try:
            if os.path.exists(tmp): os.remove(tmp)
        except OSError:
            pass

def _extract_ffmpeg_binaries(archive, dest):
    """Copy just ffmpeg and ffprobe out of a BtbN archive into dest."""
    os.makedirs(dest, exist_ok=True)
    exe = ".exe" if archive.endswith('.zip') else ""
    want = {f"ffmpeg{exe}", f"ffprobe{exe}"}
    got = set()
    if archive.endswith('.zip'):
        with zipfile.ZipFile(archive) as z:
            for n in z.namelist():
                base = n.rsplit('/', 1)[-1]
                if base in want and '/bin/' in f"/{n}":
                    with z.open(n) as src, open(os.path.join(dest, base), 'wb') as out:
                        shutil.copyfileobj(src, out)
                    got.add(base)
    else:
        with tarfile.open(archive, 'r:xz') as t:
            for m in t.getmembers():
                base = m.name.rsplit('/', 1)[-1]
                if m.isfile() and base in want and '/bin/' in f"/{m.name}":
                    src = t.extractfile(m)
                    with open(os.path.join(dest, base), 'wb') as out:
                        shutil.copyfileobj(src, out)
                    os.chmod(os.path.join(dest, base), 0o755)
                    got.add(base)
    return got == want

def _install_ffmpeg_build(version):
    """Download one release build into its own folder and test it here.
    Returns its state dict, or None (nothing is left behind on failure)."""
    plat, ext = _ffmpeg_platform_tag()
    if not plat:
        return None
    name = _ffmpeg_asset_name(version)
    urls = [_FFMPEG_DL_BASE + name]
    if platform.system() == "Windows":
        urls.append(_FFMPEG_MIRROR + name)
    os.makedirs(_FFMPEG_BUILDS_DIR, exist_ok=True)
    dest = os.path.join(_FFMPEG_BUILDS_DIR, f"n{version}-{time.strftime('%Y%m%d-%H%M%S')}")
    archive = dest + ".download"
    exe = ".exe" if platform.system() == "Windows" else ""
    for url in urls:
        try:
            print(f"[*] Downloading FFmpeg {version} ({plat}): {url}")
            with requests.get(url, stream=True, allow_redirects=True, timeout=180,
                              headers={'User-Agent': f'FractumWorker/{WORKER_VERSION}'}) as r:
                r.raise_for_status()
                etag, lm = r.headers.get('ETag', ''), r.headers.get('Last-Modified', '')
                total = int(r.headers.get('content-length', 0)); done = 0
                with open(archive, 'wb') as f:
                    for blk in r.iter_content(chunk_size=1 << 20):
                        f.write(blk); done += len(blk)
                        if total > 0:
                            _download_progress(int(done * 100 / total))
            print("\n[*] Extracting FFmpeg...")
            if not _extract_ffmpeg_binaries(archive, dest):
                raise RuntimeError("ffmpeg/ffprobe not found in the archive")
        except Exception as e:
            print(f"\n[!] FFmpeg download failed: {e}")
            shutil.rmtree(dest, ignore_errors=True)
            continue
        finally:
            try:
                if os.path.exists(archive): os.remove(archive)
            except OSError:
                pass
        ff, fp = os.path.join(dest, f"ffmpeg{exe}"), os.path.join(dest, f"ffprobe{exe}")
        print(f"[*] Testing FFmpeg {version} on this machine...")
        ok, why = _ffmpeg_selftest(ff, fp)
        if not ok:
            print(f"[!] FFmpeg {version} does not work on this machine ({why}); not using it.")
            shutil.rmtree(dest, ignore_errors=True)
            return None
        return {"managed": 2, "version": version, "url": url, "dir": dest, "ffmpeg": ff, "ffprobe": fp,
                "etag": etag, "last_modified": lm, "installed_at": time.time()}
    return None

def _load_ffmpeg_state():
    try:
        with open(_FFMPEG_META_FILE) as f:
            st = json.load(f)
        return st if isinstance(st, dict) else {}
    except Exception:
        return {}

def _save_ffmpeg_state(st):
    try:
        tmp = _FFMPEG_META_FILE + ".tmp"
        with open(tmp, 'w') as f:
            json.dump(st, f)
        os.replace(tmp, _FFMPEG_META_FILE)
    except Exception:
        pass

def _use_ffmpeg_build(st):
    """Point NEW encodes at this build. Running ones keep the binary they started."""
    global FFMPEG_CMD, FFPROBE_CMD, _FFMPEG_BUILD_INFO, _FFMPEG_MANAGED
    FFMPEG_CMD = st["ffmpeg"]
    FFPROBE_CMD = st["ffprobe"] if os.path.exists(st.get("ffprobe") or '') else _sibling_ffprobe(st["ffmpeg"])
    _FFMPEG_BUILD_INFO = None
    _FFMPEG_MANAGED = True

def _current_managed_build():
    """The worker's own build recorded in the state file, if it still exists and
    is still a release build. Adopts the single-binary layout used before
    worker 3.14.0 (./ffmpeg plus a record of its download URL)."""
    st = _load_ffmpeg_state()
    if st.get("managed") == 2:
        ff = st.get("ffmpeg") or ''
        return st if os.path.exists(ff) and _is_release_build(ff) else None
    legacy = os.path.abspath("ffmpeg.exe" if platform.system() == "Windows" else "./ffmpeg")
    m = re.search(r'ffmpeg-n(\d+\.\d+)-latest-', st.get("url") or '')
    if m and os.path.exists(legacy) and _is_release_build(legacy):
        lp = os.path.abspath("ffprobe.exe" if platform.system() == "Windows" else "./ffprobe")
        try:
            installed = os.path.getmtime(legacy)
        except OSError:
            installed = 0
        return {"managed": 2, "version": m.group(1), "url": st.get("url"), "dir": None,
                "ffmpeg": legacy, "ffprobe": lp, "etag": st.get("etag", ""),
                "last_modified": st.get("last_modified", ""), "installed_at": installed,
                "legacy": True}
    return None

def _is_release_build(ffmpeg):
    """True for a BtbN-style release build ("ffmpeg version n9.0.2-61-g...")."""
    try:
        out = subprocess.run([ffmpeg, "-version"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                             encoding='utf-8', errors='replace', timeout=15).stdout or ''
        return bool(re.match(r'ffmpeg version n\d+\.\d+', out))
    except Exception:
        return False

def _upstream_changed(st):
    """Has BtbN rebuilt this branch since we downloaded it?"""
    try:
        r = requests.head(_FFMPEG_DL_BASE + _ffmpeg_asset_name(st["version"]), allow_redirects=True,
                          timeout=20, headers={'User-Agent': f'FractumWorker/{WORKER_VERSION}'})
        if r.status_code != 200:
            return False
        et, lm = r.headers.get('ETag', ''), r.headers.get('Last-Modified', '')
        return bool((et and et != st.get("etag")) or (lm and lm != st.get("last_modified")))
    except Exception:
        return False

def _cleanup_old_ffmpeg_builds(keep_dir=None, legacy_too=False):
    """Remove builds other than the one in use. Files still running (another
    slot's encode on Windows) cannot be deleted; they go at the next start."""
    try:
        for d in os.listdir(_FFMPEG_BUILDS_DIR):
            p = os.path.join(_FFMPEG_BUILDS_DIR, d)
            if keep_dir and os.path.abspath(p) == os.path.abspath(keep_dir):
                continue
            if os.path.isdir(p):
                shutil.rmtree(p, ignore_errors=True)
            elif d.endswith('.download') or d.startswith('selftest_'):
                try: os.remove(p)
                except OSError: pass
    except OSError:
        pass
    if legacy_too:
        # The pre-3.14.0 layout kept one build next to the worker. Remove it
        # only if it is a release build (i.e. ours), never a hand-placed one.
        names = ("ffmpeg.exe", "ffprobe.exe") if platform.system() == "Windows" else ("ffmpeg", "ffprobe")
        legacy_ff = os.path.abspath(names[0])
        if os.path.exists(legacy_ff) and _is_release_build(legacy_ff):
            for n in names:
                try:
                    os.remove(os.path.abspath(n))
                except OSError:
                    pass

def _migrate_legacy_ffmpeg(cur, now):
    """Move a pre-3.14.0 build (./ffmpeg next to the worker) into its own
    folder instead of downloading the same version again. Runs at start,
    before any encode, so the files are not in use."""
    exe = ".exe" if platform.system() == "Windows" else ""
    dest = os.path.join(_FFMPEG_BUILDS_DIR, f"n{cur['version']}-{time.strftime('%Y%m%d-%H%M%S')}")
    try:
        os.makedirs(dest, exist_ok=True)
        ff, fp = os.path.join(dest, f"ffmpeg{exe}"), os.path.join(dest, f"ffprobe{exe}")
        shutil.move(cur["ffmpeg"], ff)
        if os.path.exists(cur.get("ffprobe") or ''):
            shutil.move(cur["ffprobe"], fp)
        ok, why = _ffmpeg_selftest(ff, fp)
        if not ok:
            print(f"[!] The existing FFmpeg build does not pass the test encode ({why}); replacing it.")
            shutil.rmtree(dest, ignore_errors=True)
            return None
    except Exception as e:
        print(f"[!] Could not move the existing FFmpeg build into {_FFMPEG_BUILDS_DIR}: {e}")
        return None
    new = dict(cur, dir=dest, ffmpeg=ff, ffprobe=fp, last_branch_check=now)
    new.pop("legacy", None)
    if not new.get("installed_at"):
        new["installed_at"] = now
    _save_ffmpeg_state(new)
    _use_ffmpeg_build(new)
    return new

def ensure_best_ffmpeg(force=False):
    """Make sure the newest release build that works here is in use. Returns
    True when a managed build is in use afterwards. Rate-limited to one
    version check per FFMPEG_BRANCH_CHECK_SEC unless force."""
    with _FFMPEG_MGMT_LOCK:
        cur = _current_managed_build()
        now = time.time()
        if cur and not force and now - float(cur.get("last_branch_check") or 0) < FFMPEG_BRANCH_CHECK_SEC:
            return True
        versions = _ffmpeg_release_versions()
        if cur:
            cur["last_branch_check"] = now
            if not cur.get("legacy"):
                _save_ffmpeg_state(cur)
        if not versions:
            return bool(cur)
        if cur and cur.get("legacy") and _vt(versions[0]) <= _vt(cur["version"]):
            moved = _migrate_legacy_ffmpeg(cur, now)
            if moved:
                return True
        if cur:
            if _vt(versions[0]) <= _vt(cur["version"]):
                # Already on the newest branch: take a rebuild of it (point
                # releases, fixes) at most every FFMPEG_REFRESH_SEC.
                if cur.get("legacy") is None and now - float(cur.get("installed_at") or 0) < FFMPEG_REFRESH_SEC:
                    return True
                if not cur.get("legacy") and not _upstream_changed(cur):
                    cur["installed_at"] = now
                    _save_ffmpeg_state(cur)
                    return True
                candidates = [cur["version"]]
            else:
                candidates = [v for v in versions if _vt(v) > _vt(cur["version"])]
        else:
            candidates = versions
        for v in candidates:
            new = _install_ffmpeg_build(v)
            if new:
                new["last_branch_check"] = now
                _save_ffmpeg_state(new)
                _use_ffmpeg_build(new)
                info = _ffmpeg_build_info()
                print(f"[*] Using FFmpeg {info.get('version')} (the worker's own build).")
                _cleanup_old_ffmpeg_builds(keep_dir=new["dir"], legacy_too=bool(cur and cur.get("legacy")))
                return True
        return bool(cur)

def _ffmpeg_update_loop():
    """While running, check for a newer FFmpeg release once a day."""
    while not SHUTDOWN_EVENT.wait(3600):
        if not _FFMPEG_MANAGED:
            return
        try:
            ensure_best_ffmpeg()
        except Exception as e:
            print(f"[!] FFmpeg update check failed: {e}")

def has_svtav1(cmd):
    """Checks if the given ffmpeg command supports libsvtav1"""
    try:
        res = subprocess.run([cmd, "-hide_banner", "-encoders"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                             encoding='utf-8', errors='replace', timeout=15)
        return "libsvtav1" in res.stdout
    except Exception:
        return False

# Minimum supported FFmpeg = 7.1, expressed as its libavformat version (61.7).
# The library version is the one signal every build reports identically —
# distro strings ("7.1.5-0+deb13u1"), BtbN names ("n7.1-latest") and git
# snapshots ("N-125708-g...") all differ, but the "libavformat 61. 7.100"
# banner line is universal.
_MIN_LAVF = (61, 7)

def ffmpeg_meets_min_version(cmd):
    """True when `cmd -version` reports libavformat >= 7.1's (61.7).
    Returns True on parse failure — an unreadable banner shouldn't brick a
    worker whose encoder support was already verified by has_svtav1()."""
    try:
        res = subprocess.run([cmd, "-version"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                             encoding='utf-8', errors='replace', timeout=15)
        out = res.stdout or ""
        m = re.search(r'libavformat\s+(\d+)\.\s*(\d+)', out)
        if not m:
            return True
        ver = (int(m.group(1)), int(m.group(2)))
        if ver < _MIN_LAVF:
            first = out.splitlines()[0] if out else cmd
            print(f"[!] {first.strip()}")
            print(f"[!] This FFmpeg is older than the supported minimum (7.1).")
            return False
        # Informational only: unreleased dev snapshots have caused real
        # encode/mux regressions in this swarm — recommend a release build.
        if re.search(r'^ffmpeg version [Nn]-\d+-g', out):
            print("[!] WARNING: this FFmpeg is a git development snapshot, not a release.")
            print("    Dev builds have caused broken uploads before — a stable release (7.1+) is recommended.")
        return True
    except Exception:
        return True

def has_libopus(cmd):
    """True when the given ffmpeg can encode Opus audio (libopus)."""
    try:
        res = subprocess.run([cmd, "-hide_banner", "-encoders"], stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT, encoding='utf-8', errors='replace', timeout=15)
        return "libopus" in res.stdout
    except Exception:
        return False

def ffmpeg_is_capable(cmd):
    """Everything the encodes need: SVT-AV1, Opus, and FFmpeg 7.1 or newer."""
    return has_svtav1(cmd) and has_libopus(cmd) and ffmpeg_meets_min_version(cmd)

def _sibling_ffprobe(ffmpeg_path):
    """The ffprobe next to a given ffmpeg, or plain 'ffprobe' from the PATH."""
    d = os.path.dirname(os.path.abspath(ffmpeg_path)) if os.path.dirname(ffmpeg_path) else ''
    if d:
        for name in ("ffprobe.exe", "ffprobe"):
            p = os.path.join(d, name)
            if os.path.exists(p):
                return p
    return "ffprobe"

def check_ffmpeg(override=None):
    """Pick the FFmpeg to use at start. Returns True when it is the worker's own
    managed build (which _ffmpeg_update_loop() then keeps current).

    Windows and Linux on x64/arm64: the worker's own newest working release
    build (see the policy comment above ensure_best_ffmpeg). A build found on
    the machine is only used when no managed build can be installed. --ffmpeg
    PATH chooses a specific binary deliberately. Other platforms (macOS) have
    no managed build and use the one installed (e.g. Homebrew)."""
    global FFMPEG_CMD, FFPROBE_CMD

    local_ffmpeg = os.path.abspath("ffmpeg.exe" if platform.system() == "Windows" else "./ffmpeg")
    local_ffprobe = os.path.abspath("ffprobe.exe" if platform.system() == "Windows" else "./ffprobe")

    if override:
        cmd = override if (os.path.dirname(override) or os.path.exists(override)) else (shutil.which(override) or override)
        if not (shutil.which(cmd) or os.path.exists(cmd)):
            print(f"[CRITICAL ERROR] --ffmpeg {override}: file not found.")
            sys.exit(1)
        if not ffmpeg_is_capable(cmd):
            print(f"[CRITICAL ERROR] --ffmpeg {override} cannot be used: it needs libsvtav1, libopus "
                  "and FFmpeg 7.1 or newer.")
            sys.exit(1)
        FFMPEG_CMD = os.path.abspath(cmd) if os.path.exists(cmd) else cmd
        FFPROBE_CMD = _sibling_ffprobe(FFMPEG_CMD)
        print(f"[*] Using the FFmpeg chosen with --ffmpeg: {FFMPEG_CMD}")
        return False

    plat, _ = _ffmpeg_platform_tag()
    if plat:
        cur = _current_managed_build()
        if cur:
            _use_ffmpeg_build(cur)
            if not cur.get("legacy"):
                _cleanup_old_ffmpeg_builds(keep_dir=cur.get("dir"))
        else:
            found = local_ffmpeg if os.path.exists(local_ffmpeg) else (shutil.which("ffmpeg") or None)
            if found:
                print(f"[*] Found an FFmpeg at {found}; installing the worker's own build (the newest FFmpeg "
                      "release that works on this machine) instead, so every worker encodes with a known-good version.")
                print("    To keep using that one, start the worker with --ffmpeg PATH.")
        if ensure_best_ffmpeg(force=cur is None or bool(cur.get("legacy"))):
            return True
        print("[!] Could not install the worker's own FFmpeg build; looking for one on this machine.")
        if os.path.exists(local_ffmpeg) and ffmpeg_is_capable(local_ffmpeg):
            FFMPEG_CMD = local_ffmpeg
            if os.path.exists(local_ffprobe): FFPROBE_CMD = local_ffprobe
            return False
        if shutil.which("ffmpeg") and ffmpeg_is_capable("ffmpeg"):
            FFMPEG_CMD = "ffmpeg"
            FFPROBE_CMD = "ffprobe"
            return False
        print("\n[CRITICAL ERROR] Could not find or download FFmpeg 7.1+ with libsvtav1 and libopus.")
        print("Please install FFmpeg 7.1 or newer with SVT-AV1 support manually, or pass --ffmpeg PATH.")
        sys.exit(1)

    # No managed build for this OS/CPU: use what is installed.
    if os.path.exists(local_ffmpeg) and ffmpeg_is_capable(local_ffmpeg):
        FFMPEG_CMD = local_ffmpeg
        if os.path.exists(local_ffprobe): FFPROBE_CMD = local_ffprobe
        return False
    if shutil.which("ffmpeg") and ffmpeg_is_capable("ffmpeg"):
        FFMPEG_CMD = "ffmpeg"
        FFPROBE_CMD = "ffprobe"
        return False
    print("\n[CRITICAL ERROR] No FFmpeg 7.1+ with libsvtav1 and libopus found.")
    if platform.system() == "Darwin":
        print("On macOS: brew install ffmpeg   (Homebrew's build includes SVT-AV1 and Opus).")
    else:
        print("Please install FFmpeg 7.1 or newer with SVT-AV1 and Opus support, or pass --ffmpeg PATH.")
    sys.exit(1)


def verify_connection(manager_url):
    try:
        if requests.get(manager_url, timeout=10).status_code < 400: return True
    except: pass
    print(f"[!] Could not connect to {manager_url}"); return False


def _ensure_temp_writable(temp_dir):
    """Return (usable_dir, None) or (None, error): make sure this worker has a
    usable temp dir, self-healing every variant of the common accident where a
    previous run as another user (e.g. via sudo) poisoned it:

      1. root-owned FILES inside a user-owned dir  -> delete the files
      2. user-owned dir with a broken mode         -> chmod it back
      3. root-owned dir that can be removed        -> delete + recreate
      4. root-owned dir that CANNOT be removed     -> use a deterministic
         per-user sibling dir (temp_encode_X_u<uid>) instead — the worker's
         own folder is always writable if the worker runs at all

    Only when even the sibling dir cannot be created (the worker's folder
    itself is read-only) does this give up and return an error."""

    def _writable(d):
        try:
            os.makedirs(d, exist_ok=True)
            probe = os.path.join(d, '.write_test')
            with open(probe, 'w') as f:
                f.write('x')
            os.remove(probe)
            return True
        except OSError:
            return False

    def _clear_leftovers(d):
        """Delete unwritable leftover files (useless for resume anyway).
        Returns True when the dir ends up clean."""
        try:
            for name in os.listdir(d):
                p = os.path.join(d, name)
                if not os.path.isfile(p) or os.access(p, os.W_OK):
                    continue
                try:
                    os.remove(p)
                    print(f"[*] Removed unwritable leftover from a previous run: {p}")
                except OSError:
                    return False
            return True
        except OSError:
            return False

    try:
        if _writable(temp_dir) and _clear_leftovers(temp_dir):
            return temp_dir, None

        # Heal 2: a dir we own whose mode got mangled.
        try:
            os.chmod(temp_dir, 0o755)
        except OSError:
            pass
        if _writable(temp_dir) and _clear_leftovers(temp_dir):
            print(f"[*] Repaired permissions on '{temp_dir}'.")
            return temp_dir, None

        # Heal 3: remove the poisoned dir entirely (works whenever the parent
        # folder is ours — e.g. an EMPTY root-owned dir) and start fresh.
        try:
            shutil.rmtree(temp_dir)
        except OSError:
            # rmtree can't even LIST an unreadable foreign dir, but deleting an
            # empty one only needs write permission on the parent.
            try:
                os.rmdir(temp_dir)
            except OSError:
                pass
        if not os.path.isdir(temp_dir) and _writable(temp_dir):
            print(f"[*] Recreated temp dir '{temp_dir}' (previous one was unusable).")
            return temp_dir, None

        # Heal 4: the dir is another user's and can't be emptied — step around
        # it with a per-user sibling. Deterministic name, so resume checkpoints
        # still work across restarts for THIS user.
        if hasattr(os, 'getuid'):
            suffix = f"u{os.getuid()}"
        else:
            suffix = re.sub(r'[^A-Za-z0-9_-]', '_', os.environ.get('USERNAME', 'alt')) or 'alt'
        alt = f"{temp_dir.rstrip('/' + os.sep)}_{suffix}"
        if _writable(alt) and _clear_leftovers(alt):
            print(f"[!] '{temp_dir}' belongs to another user and can't be cleaned — "
                  f"using '{alt}' instead.")
            print(f"    (Reclaim the old dir's disk later with: sudo rm -rf '{temp_dir}')")
            return alt, None

        return None, (f"Temp dir '{temp_dir}' is not writable and no fallback beside it "
                      f"could be created — the worker's own folder appears read-only")
    except OSError as e:
        return None, str(e)

def worker_task(worker_id, manager_url, temp_dir, quota_tracker, single_mode=False, series_id=None, watermark=False, max_size_mb=0, local_source_dir=None, no_chunks=False, wallet=None):
    global UPDATE_AVAILABLE
    log(worker_id, "Thread active.")
    # Self-heal the temp dir (sudo leftovers, mangled modes, root-owned dirs —
    # a per-user sibling dir is used when the original can't be reclaimed).
    # Only a fully read-only worker folder still refuses jobs: encoding there
    # would just burn fail_count strikes against good jobs on the manager.
    temp_dir, _tmp_err = _ensure_temp_writable(temp_dir)
    if _tmp_err:
        log(worker_id, f"{_tmp_err}. Fix the worker folder's permissions (chown/chmod it to "
                       "the user running the worker), then restart. Not taking jobs.", "ERROR")
        try:
            requests.post(f"{manager_url}/report_error",
                          json={"job_id": "none", "worker_id": worker_id,
                                "error_type": "temp_dir_permissions",
                                "message": _tmp_err[:2048], "details": ""},
                          headers=get_auth_headers(), timeout=10)
        except Exception:
            pass
        with PROGRESS_LOCK:
            WORKER_PROGRESS[worker_id] = "Perm Error"
        d = WORKER_DETAILS.get(worker_id)
        if d is not None:
            d["phase"] = "Perm Error"
        return
    
    def update_status(msg):
        with PROGRESS_LOCK:
            WORKER_PROGRESS[worker_id] = msg
        d = WORKER_DETAILS.get(worker_id)
        if d is not None:
            if not msg.startswith(("Open ", "Stall ")):
                d["note"] = ""
            if msg.startswith("DL "):
                d["phase"] = "DL"
                try: d["pct"] = int(msg[3:].rstrip('%'))
                except: pass
            elif msg.startswith("Enc "):
                d["phase"] = "Encoding"
                try: d["pct"] = int(msg[4:].rstrip('%'))
                except: pass
            elif msg.startswith("Up "):
                d["phase"] = "Uploading"
                try: d["pct"] = int(msg[3:].rstrip('%'))
                except: pass
            elif msg == "Idle":
                d.update({"phase": "Idle", "pct": 0, "file": "-", "job_start": 0.0})
            elif msg.startswith("Open "):
                d["phase"] = "Opening"
                d["note"] = msg[5:]
                d["pct"] = 0
            elif msg.startswith("Stall "):
                d["phase"] = "Stalled"
                d["note"] = msg[6:]
            elif msg == "Probing":
                d["phase"] = "Probe"
            elif msg == "Quota Limit":
                d.update({"phase": "Quota", "pct": 0, "file": "-", "job_start": 0.0})
            else:
                d["phase"] = msg
        
    def post_status(status, progress=0, duration=0, error_msg=None):
        try:
            payload = {
                "worker_id": worker_id, 
                "job_id": job_id, 
                "status": status, 
                "progress": progress,
                "version": WORKER_VERSION
            }
            if duration > 0: payload["duration"] = duration
            if error_msg: payload["error"] = error_msg
            requests.post(f"{manager_url}/report_status", json=payload, headers=get_auth_headers(), timeout=10)
        except: pass

    def report_error(rpt_job_id, error_type, message, details="", diag=None):
        """Send a structured error report to the manager for admin visibility.
        `diag` (source-read failures) is also shown as text in the details."""
        payload = {
            "job_id": rpt_job_id,
            "worker_id": worker_id,
            "error_type": error_type,
            "message": str(message)[:2048],
            "details": (str(details)[:30000] + (_diag_text(diag) if diag else ""))[:32768],
        }
        if diag:
            payload["diag"] = diag
        try:
            requests.post(
                f"{manager_url}/report_error",
                json=payload,
                headers=get_auth_headers(),
                timeout=10
            )
        except: pass

    # ==========================================================
    # CHUNKED ENCODING — encode one time-slice (or the audio
    # track) of a video that is being split across many workers.
    # ==========================================================
    def process_chunk(chunk):
        job_id     = chunk['job_id']
        kind       = chunk.get('kind', 'video')
        idx        = int(chunk.get('chunk_index', 0))
        start_sec  = float(chunk.get('start_sec', 0) or 0)
        dur_sec    = float(chunk.get('duration_sec', 0) or 0)
        total      = int(chunk.get('total_chunks', 0) or 0)
        src_dur    = float(chunk.get('source_duration_sec', 0) or 0)
        dl_url     = chunk['download_url']
        filename   = chunk.get('filename', job_id)
        chunk_tag  = "audio" if kind == 'audio' else f"chunk {idx+1}"

        def report_chunk(status, progress=0, error_msg=None):
            payload = {
                "job_id": job_id, "chunk_index": idx, "kind": kind,
                "worker_id": worker_id, "status": status,
                "progress": progress, "version": WORKER_VERSION,
            }
            if error_msg: payload["error"] = error_msg
            try:
                requests.post(f"{manager_url}/report_chunk", json=payload,
                              headers=get_auth_headers(), timeout=10)
            except: pass

        # Prefer a direct file path when the source directory is mounted locally
        if local_source_dir:
            _cand = os.path.join(local_source_dir, job_id.replace('/', os.sep))
            if os.path.isfile(_cand):
                dl_url = os.path.abspath(_cand)
        _is_local = not (dl_url.startswith('http://') or dl_url.startswith('https://'))

        d = WORKER_DETAILS.get(worker_id)
        if d is not None:
            d.update({"file": f"{filename} [{chunk_tag}]",
                      "phase": "Probe" if kind == 'audio' else "Encoding",
                      "pct": 0, "job_start": time.time()})
        log(worker_id, f"Chunk job: {filename} [{chunk_tag}/{total}] ({dur_sec/60:.1f}m slice)")
        # Without the TUI the slot kept reading "Idle" until ffmpeg's first
        # progress line, several seconds after the chunk was taken.
        update_status("Enc 0%")

        # Quota: estimate the share of the source this chunk will stream.
        # The audio pass reads the whole (interleaved) file.
        if quota_tracker:
            try:
                fsize = int(chunk.get('file_size') or 0)
                if fsize > 0:
                    est = fsize if (kind == 'audio' or src_dur <= 0) else int(fsize * dur_sec / src_dur)
                    quota_tracker.add_usage(est)
                    quota_tracker.force_save()
            except: pass

        ffmpeg_http_headers = f"X-Worker-Token: {WORKER_SECRET}\r\n"
        input_flags = [] if _is_local else _http_input_flags(ffmpeg_http_headers)
        # Per-chunk output name: a leaked/killed ffmpeg from a previous chunk
        # must never share an output path with the current one.
        _co_safe = re.sub(r'[^a-zA-Z0-9_-]', '_', f"{job_id}_{kind}_{idx}")[:80]
        out_path = os.path.join(temp_dir, f"chunk_out_{_co_safe}{ENCODING_CONFIG['OUTPUT_EXT']}")
        raw_log_path = os.path.join(temp_dir, "chunk_encode.log")
        gz_log_path = os.path.join(temp_dir, "chunk_encode.log.gz")
        slice_args = None; slice_path = None; slice_max_bytes = 0   # see "Audio slice" below

        target_crf = int(ENCODING_CONFIG["VIDEO_CRF"])
        if watermark and kind == 'video':
            log(worker_id, "Watermark is skipped on chunked jobs to keep the final video consistent.", "WARN")

        if kind == 'video':
            # NOTE: -ss before -i = accurate input seek (decode starts at the exact
            # cut point); -t bounds the slice. The manager snaps boundaries between
            # two source frames and setpts re-zeroes each chunk's timeline, so the
            # stream-copy concat is frame-exact (no dup/drop at boundaries, no A/V
            # drift). No watermark/audio/subs here — the audio chunk carries those.
            is_last = bool(chunk.get('is_last'))
            seek_flags = ['-ss', f"{start_sec:.5f}"] if start_sec > 0 else []
            limit_flags = [] if is_last else ['-t', f"{dur_sec:.5f}"]  # last chunk runs to EOF
            # Pin the encoder time base to the source frame rate (manager sends
            # the exact fraction, e.g. "24000/1001"). Without this, ffmpeg 7.x
            # doesn't propagate a frame rate through setpts under -fps_mode
            # passthrough, so libsvtav1 falls back to 1/time_base — 1000 fps on
            # an MKV source — and refuses to start ("The maximum allowed frame
            # rate is 240 fps"). Verified: output timestamps are bit-identical
            # with and without this flag on ffmpeg 6.x.
            etb_flags = []
            _fr = str(chunk.get('fps') or '')
            if not _fr:
                # Safety net: an older manager (or a job whose stored stream
                # layout predates the fps field) sends no frame rate. Read it
                # from the source header — r_frame_rate lives at the START of
                # the file, so this stays cheap even over HTTP, unlike a full
                # probe. Without it libsvtav1 sees the container timebase
                # (1000 fps on MKV) and refuses to start.
                _fr = _probe_source_fps(dl_url, _is_local, ffmpeg_http_headers) or ''
                if _fr:
                    log(worker_id, f"Manager sent no frame rate; probed {_fr} from the source.", "WARN")
            _m = re.fullmatch(r'([1-9]\d*)/([1-9]\d*)', _fr)
            if _m:
                _fn, _fd = int(_m.group(1)), int(_m.group(2))
                if 0 < _fn / _fd <= 240:
                    etb_flags = ['-enc_time_base', f"{_fd}/{_fn}"]
            cmd = ([FFMPEG_CMD] + input_flags + seek_flags +
                   ['-y', '-i', dl_url] + limit_flags +
                   ['-map', '0:v:0', '-an', '-sn',
                    '-fps_mode', 'passthrough', '-avoid_negative_ts', 'make_zero',
                    '-c:v', ENCODING_CONFIG["VIDEO_CODEC"],
                    '-preset', ENCODING_CONFIG["VIDEO_PRESET"],
                    '-crf', str(target_crf),
                    '-pix_fmt', ENCODING_CONFIG["VIDEO_PIX_FMT"]] + etb_flags +
                   ['-vf', f"setpts=PTS-STARTPTS,{ENCODING_CONFIG['VIDEO_SCALE']}",
                    '-movflags', 'frag_keyframe+empty_moov+default_base_moof',
                    '-progress', 'pipe:1', out_path])
            prog_total = dur_sec
            # Audio slice (manager asks for it with 'audio_slice'): a second
            # output of the SAME ffmpeg run that stream-copies the source's
            # audio and text-subtitle packets for this chunk's time range.
            # Those bytes are being downloaded anyway - the audio is
            # interleaved with the video - so the manager can rebuild the
            # whole audio track from the slices and nobody has to download
            # the entire source a second time just for audio.
            #   -ss 0             drop packets before the chunk start (none on
            #                     the first chunk, which must keep them all)
            #   -t dur+1          run a second past the chunk end; the overlap
            #                     is how the manager proves each join
            #   -output_ts_offset put the source's own timestamps back, so
            #                     slices line up without guesswork
            _as = chunk.get('audio_slice') if isinstance(chunk, dict) else None
            try:
                if isinstance(_as, dict) and _as.get('audio_index') is not None:
                    slice_path = os.path.join(temp_dir, f"chunk_out_{_co_safe}.aslice.mka")
                    slice_max_bytes = int(_as.get('max_bytes') or 0)
                    slice_args = ((['-ss', '0'] if start_sec > 0 else []) +
                                  ([] if is_last else ['-t', f"{dur_sec + 1.0:.5f}"]) +
                                  ['-output_ts_offset', f"{start_sec:.5f}",
                                   '-map', f"0:{int(_as['audio_index'])}"])
                    for _sidx in (_as.get('subtitle_indices') or []):
                        slice_args += ['-map', f"0:{int(_sidx)}"]
                    slice_args += ['-c', 'copy', '-f', 'matroska', slice_path]
            except (TypeError, ValueError):
                slice_args = None; slice_path = None
        else:
            # Audio + subtitles for the whole file, encoded once.
            audio_index = None; subtitle_indices = []; audio_channels = 2
            # The manager may have handed us the source's stream layout (from its
            # own probe), letting us skip probing over HTTP — the slowest and most
            # failure-prone step on constrained workers (e.g. a Pi range-streaming
            # a large MKV). Fall back to probing when it's absent or malformed.
            _cmeta = chunk.get('stream_meta') if isinstance(chunk, dict) else None
            _used_meta = False
            if _cmeta:
                try:
                    _ai = _cmeta.get('audio_index')
                    _mac = int(_cmeta.get('audio_channels') or 0)
                    _si = [int(x) for x in (_cmeta.get('subtitle_indices') or [])]
                    # Usable only when complete: an audio track needs its channel
                    # count (it selects the mono downmix formula — guessing 2 on
                    # a 5.1 source would bury the dialogue), and a subs-only
                    # source needs at least one subtitle index.
                    if (_ai is not None and _mac >= 1) or (_ai is None and _si):
                        audio_index = int(_ai) if _ai is not None else None
                        subtitle_indices = _si
                        audio_channels = _mac if _mac >= 1 else 2
                        _used_meta = True
                        log(worker_id, "Using stream info from manager; skipping probe.")
                except (TypeError, ValueError) as _cme:
                    log(worker_id, f"Bad stream_meta from manager ({_cme}); probing locally.", "WARN")
                    _used_meta = False

            if not _used_meta:
                update_status("Probing")
                probe_data = None
                for _pa in range(3):
                    try:
                        cmd_probe = ([FFPROBE_CMD] if _is_local else [FFPROBE_CMD, '-headers', ffmpeg_http_headers]) + \
                                    ['-v', 'quiet', '-print_format', 'json', '-show_streams', '-show_format', dl_url]
                        res = subprocess.run(cmd_probe, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                             encoding='utf-8', errors='replace', timeout=60)
                        probe_data = json.loads(res.stdout)
                        break
                    except Exception as _pe:
                        if _pa < 2:
                            time.sleep(5 * (_pa + 1))
                        else:
                            log(worker_id, f"Chunk probe failed: {_pe}", "ERROR")
                if probe_data is None:
                    report_chunk("failed", error_msg="FFprobe failed after 3 attempts")
                    return

                audio_streams = [s for s in probe_data.get('streams', []) if s['codec_type'] == 'audio']
                if audio_streams:
                    audio_index = audio_streams[0]['index']
                    for s in audio_streams:
                        if s.get('tags', {}).get('language', '').lower() in ['eng', 'en', 'english']:
                            audio_index = s['index']; break
                    for s in audio_streams:
                        if s['index'] == audio_index:
                            try: audio_channels = int(s.get('channels', 2))
                            except: pass
                            break
                for s in probe_data.get('streams', []):
                    if s['codec_type'] == 'subtitle':
                        if s.get('codec_name', '').lower() in ['subrip', 'ass', 'webvtt', 'mov_text', 'text', 'srt', 'ssa']:
                            subtitle_indices.append(s['index'])

            if audio_index is None and not subtitle_indices:
                report_chunk("failed", error_msg="No audio or subtitle streams found")
                return

            if audio_channels > 2:
                audio_filter = "pan=mono|c0=0.5*FC+0.25*FL+0.25*FR+0.1*BL+0.1*BR,aresample=async=1"
            elif audio_channels == 2:
                audio_filter = "pan=mono|c0=0.5*c0+0.5*c1,aresample=async=1"
            else:
                audio_filter = "aresample=async=1"

            cmd = [FFMPEG_CMD] + input_flags + ['-y', '-i', dl_url, '-vn']
            if audio_index is not None:
                cmd += ['-map', f'0:{audio_index}',
                        '-c:a', ENCODING_CONFIG["AUDIO_CODEC"],
                        '-b:a', ENCODING_CONFIG["AUDIO_BITRATE"],
                        '-ac', ENCODING_CONFIG["AUDIO_CHANNELS"],
                        '-af', audio_filter]
            for sidx in subtitle_indices:
                cmd += ['-map', f'0:{sidx}']
            if subtitle_indices:
                cmd += ['-c:s', ENCODING_CONFIG["SUBTITLE_CODEC"]]
            cmd += ['-movflags', 'frag_keyframe+empty_moov+default_base_moof',
                    '-progress', 'pipe:1', out_path]
            prog_total = src_dur if src_dur > 0 else dur_sec

        # ---- Encode (2 attempts, more when the SOURCE is what failed) ----
        # A transient source-read failure (Cloudflare 522, a Range response cut
        # short) is not a bad job, and two attempts 15s apart land inside the
        # same outage. Wait it out instead of handing the chunk back as failed.
        _MAX_ATT = 5
        proc = None; log_buffer = []; _trunc_note = None; _stall_salvaged = False
        _src_retry_delays = [30, 120, 300]
        _src_retries = 0
        report_chunk("processing", 0)
        for _att in range(_MAX_ATT):
            if SHUTDOWN_EVENT.is_set(): break
            if _att > 0:
                _source_blamed = _is_source_read_failure(log_buffer) and not _trunc_note
                if _att >= 2 and not _source_blamed:
                    break  # a real encode failure: don't grind on it
                if _source_blamed and _src_retries < len(_src_retry_delays):
                    _delay = _src_retry_delays[_src_retries]
                    _src_retries += 1
                    log(worker_id, f"Could not read the source (rc="
                                   f"{_ffmpeg_rc_text(proc.returncode) if proc else '?'}) \u2014 "
                                   f"waiting {_delay}s for it to come back ({chunk_tag}).", "WARN")
                    if _src_retries == 1 and not _is_local:
                        # Test the download now, while the problem is fresh:
                        # the full report only goes out after every retry.
                        try:
                            _fs = int(chunk.get('file_size') or 0)
                            _st = _source_selftest(dl_url, int(_fs * start_sec / src_dur)
                                                   if (_fs > 0 and src_dur > 0 and kind == 'video') else 0)
                            log(worker_id, "Source download test: " + (
                                f"FAILED: {_st['error']}" if _st.get('error') else
                                f"OK, {_st.get('mb_s')} MB/s, first byte {_st.get('ttfb_ms')} ms") +
                                f" ({chunk_tag}).", "WARN")
                        except Exception:
                            pass
                elif _source_blamed:
                    break  # source still down after every backoff step
                else:
                    _delay = 15
                    log(worker_id, f"Chunk encode failed (rc="
                                   f"{_ffmpeg_rc_text(proc.returncode) if proc else '?'}). "
                                   f"Retrying in {_delay}s...", "WARN")
                    if slice_args and not _trunc_note:
                        # The encode itself failed. The audio slice is an
                        # extra the chunk does not depend on: retry without
                        # it, so it can never be what keeps a chunk failing.
                        log(worker_id, f"Retrying without the audio slice ({chunk_tag}).", "WARN")
                        slice_args = None
                update_status("Retrying")
                for _ in range(_delay):
                    if SHUTDOWN_EVENT.is_set(): break
                    time.sleep(1)
                if SHUTDOWN_EVENT.is_set(): break

            if slice_path:
                try:
                    if os.path.exists(slice_path): os.remove(slice_path)
                except OSError: pass
            popen_kwargs = {}
            if platform.system() == 'Windows':
                popen_kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP
            else:
                popen_kwargs['start_new_session'] = True
            proc = subprocess.Popen(cmd + (slice_args or []), stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                    stdin=subprocess.DEVNULL, encoding='utf-8', errors='replace', **popen_kwargs)
            assert proc.stdout is not None
            with PROC_LOCK: ACTIVE_PROCS[worker_id] = proc

            last_rep = 0; last_pct = 0; last_hb = time.time()
            log_buffer = []
            # Ticks the display while ffmpeg opens and seeks the source, which
            # this loop cannot do: readline() below is blocked the whole time.
            watch = _StreamWatch(update_status, single_mode,
                                 heartbeat=lambda: report_chunk("processing", last_pct),
                                 measure=(kind == 'video')).start().attach(proc)
            # try/finally: an exception mid-loop (e.g. disk-full on the log
            # write) must still deregister and kill ffmpeg — a leaked encoder
            # blocks forever on a full stdout pipe once nobody reads it.
            try:
                with open(raw_log_path, 'w', encoding='utf-8') as raw_log:
                    while True:
                        if PAUSE_REQUESTED:
                            if time.time() - last_hb > 30:
                                report_chunk("processing", last_pct)
                                last_hb = time.time()
                            time.sleep(0.2)
                            continue
                        line = proc.stdout.readline()
                        if line:
                            log_buffer.append(line); log_buffer = log_buffer[-50:]
                            raw_log.write(line); raw_log.flush()
                        if not line and proc.poll() is not None: break
                        if "out_time=" in line and "N/A" not in line and prog_total > 0:
                            try:
                                curr_sec = get_seconds(line.split('=')[1].strip())
                                pct = min(100, int((curr_sec / prog_total) * 100))
                                last_pct = pct
                                watch.note_progress(pct, curr_sec)
                                if single_mode: print_progress(worker_id, curr_sec, prog_total, prefix='Enc')
                                else: update_status(f"Enc {pct}%")
                                if time.time() - last_rep > 10:
                                    report_chunk("processing", pct)
                                    last_rep = time.time(); last_hb = last_rep
                            except: pass
                        elif line.startswith("speed="):
                            _set_speed(worker_id, line)
            finally:
                watch.stop()
                with PROC_LOCK:
                    if worker_id in ACTIVE_PROCS: del ACTIVE_PROCS[worker_id]
                if proc.poll() is None:
                    try: proc.kill()
                    except Exception: pass
            if SHUTDOWN_EVENT.is_set(): break
            if watch.stall_killed:
                log_buffer.append("Stream ends prematurely (no progress; ffmpeg stopped by the stall watchdog)\n")
                # A freeze in the last moments of the LAST chunk is the common
                # case, and re-encoding just freezes at the same spot. The
                # output is a fragmented MP4, so what was written is intact:
                # keep it when it is complete to within a few seconds.
                _s_exp = max(0.0, src_dur - start_sec) if src_dur > 0 else dur_sec
                _s_dur = _clean_stopped_output(out_path) if (kind == 'video' and chunk.get('is_last')) else None
                if _s_dur is not None and _s_exp > 0 and _s_dur >= _s_exp - 20.0:
                    log(worker_id, f"Encode stalled {max(0.0, _s_exp - _s_dur):.1f}s before the end of the "
                                   f"source ({chunk_tag}); keeping the {_s_dur:.1f}s already encoded.", "WARN")
                    _stall_salvaged = True; _trunc_note = None
                    break
                log(worker_id, f"{watch.kill_reason()} ({chunk_tag}); stopped ffmpeg.", "WARN")
            if proc.returncode == 0:
                # Self-check BEFORE uploading: a dropped source stream can make
                # ffmpeg see a premature EOF and finish "successfully" with only
                # part of the chunk encoded ("Stream ends prematurely" in the
                # log, rc 0). The manager would reject it anyway (duration
                # mismatch) — catching it here turns an upload+reject+strike
                # into an immediate local retry. Mirrors the manager's tolerances.
                if kind == 'video' and bool(chunk.get('is_last')) and src_dur > 0:
                    _exp_dur = max(0.0, src_dur - start_sec)
                else:
                    _exp_dur = dur_sec
                if kind == 'video':
                    _tol = max(10.0, _exp_dur * 0.10) if chunk.get('is_last') else max(2.0, _exp_dur * 0.05)
                else:
                    _tol = max(10.0, _exp_dur * 0.05)
                _odur = _media_duration(out_path)
                if _odur is None:
                    # Undeterminable != truncated. Never discard an encode that
                    # ffmpeg reported as successful just because ffprobe could
                    # not read the duration back (fragmented MP4 on some builds,
                    # missing/!broken ffprobe). The manager verifies the upload
                    # anyway, so a genuinely bad chunk is still caught there.
                    log(worker_id, f"Could not read back chunk duration ({chunk_tag}); "
                                   "skipping the local truncation check.", "WARN")
                elif _exp_dur > 0 and _odur < _exp_dur - _tol:
                    _trunc_note = f"{_odur:.1f}s of {_exp_dur:.1f}s"
                    log(worker_id, f"Chunk output truncated ({_trunc_note}) — source stream likely "
                                   f"dropped mid-encode ({chunk_tag}). Retrying.", "WARN")
                    try: os.remove(out_path)
                    except OSError: pass
                    continue  # burn this attempt, re-encode
                _trunc_note = None
                break

        def upload_chunk_log():
            try:
                with open(raw_log_path, 'rb') as f_in, gzip.open(gz_log_path, 'wb') as f_out:
                    shutil.copyfileobj(f_in, f_out)
                chunk_log_id = f"{job_id}::chunk_{kind}_{idx}"
                with open(gz_log_path, 'rb') as lf:
                    requests.post(f"{manager_url}/upload_log",
                                  files={'log_file': (f"{chunk_log_id.replace('/', '_')}.log.gz", lf)},
                                  data={'job_id': chunk_log_id, 'worker_id': worker_id},
                                  headers=get_auth_headers(), timeout=60)
            except Exception as _le:
                log(worker_id, f"Failed to upload chunk log: {_le}", "WARN")

        def cleanup():
            for _fp in [out_path, raw_log_path, gz_log_path, slice_path]:
                try:
                    if _fp and os.path.exists(_fp): os.remove(_fp)
                except: pass

        if SHUTDOWN_EVENT.is_set() and (proc is None or proc.returncode != 0):
            # Shutting down mid-encode: hand the chunk back without penalty
            report_chunk("abandoned")
            cleanup()
            return

        if proc is None or (proc.returncode != 0 and not _stall_salvaged) or not os.path.exists(out_path):
            rc = proc.returncode if proc else -1
            if _trunc_note:
                err_msg = f"Truncated output ({_trunc_note}) — source stream interrupted ({chunk_tag})"
            elif _is_source_read_failure(log_buffer) and _is_local:
                err_msg = (f"Could not read the local source file \u2014 "
                           f"FFmpeg exited with code {_ffmpeg_rc_text(rc)} ({chunk_tag})")
                log(worker_id, f"This machine's own copy of the file may be damaged or incomplete: {dl_url}. "
                               "Compare it with the server's copy.", "WARN")
            elif _is_source_read_failure(log_buffer):
                err_msg = (f"Could not read the source \u2014 "
                           f"FFmpeg exited with code {_ffmpeg_rc_text(rc)} ({chunk_tag})")
            else:
                err_msg = f"FFmpeg exited with code {_ffmpeg_rc_text(rc)} ({chunk_tag})"
            log(worker_id, err_msg, "ERROR")
            report_chunk("failed", error_msg=err_msg)
            _diag = None
            if _trunc_note or _is_source_read_failure(log_buffer):
                try:
                    _fs = int(chunk.get('file_size') or 0)
                    _off = int(_fs * start_sec / src_dur) if (_fs > 0 and src_dur > 0 and kind == 'video') else 0
                    _diag = _source_failure_diag(watch if proc is not None else None, dl_url, _is_local, _off)
                    _st = _diag.get('selftest') or {}
                    log(worker_id, "Source download test: " + (_st.get('error') or
                        f"HTTP {_st.get('status')}, {_st.get('mb_s')} MB/s") if _st else
                        "Source is a local file; no download test.", "WARN")
                except Exception as _de:
                    log(worker_id, f"Could not collect source diagnostics: {_de}", "WARN")
            report_error(job_id, "chunk_encode_failure", err_msg, _error_tail(log_buffer), diag=_diag)
            upload_chunk_log()
            cleanup()
            d = WORKER_DETAILS.get(worker_id)
            if d is not None:
                d["phase"] = "Failed"
                d["jobs_failed"] = d.get("jobs_failed", 0) + 1
            return

        # ---- Upload ----
        chunk_bytes = os.path.getsize(out_path)
        # The audio slice goes first, so it is in place when the manager
        # records the chunk. Only a slice from a run that ended cleanly is
        # sent: a stalled-and-salvaged encode may have stopped copying early.
        # Failing to deliver it costs nothing but the saving - the manager
        # then has a worker encode the audio from the source as before.
        if slice_args and slice_path and proc is not None and proc.returncode == 0 and not _stall_salvaged:
            try:
                _sl_bytes = os.path.getsize(slice_path) if os.path.exists(slice_path) else 0
            except OSError:
                _sl_bytes = 0
            if _sl_bytes <= 0:
                log(worker_id, f"No audio slice was written ({chunk_tag}); the manager will use the separate audio pass.", "WARN")
            elif slice_max_bytes and _sl_bytes > slice_max_bytes:
                log(worker_id, f"Audio slice is {_sl_bytes/1024/1024:.0f} MB, over the manager's limit; not sending it ({chunk_tag}).", "WARN")
            else:
                log(worker_id, f"Sending audio slice ({_sl_bytes/1024/1024:.2f} MB)...")
                update_status("Up 0%")
                _sl_outcome, _sl_detail = _upload_with_retry(
                    f"{manager_url}/upload_audio_slice", lambda: open(slice_path, 'rb'),
                    f"aslice_{idx}.mka",
                    {'job_id': job_id, 'chunk_index': idx, 'worker_id': worker_id},
                    worker_id, f"Audio slice ({chunk_tag})",
                    keepalive=lambda: report_chunk("processing", 100))
                if _sl_outcome != 'ok':
                    log(worker_id, f"Audio slice not delivered ({chunk_tag}): {_sl_detail}", "WARN")
                else:
                    with STATS_LOCK:
                        SESSION_STATS["bytes_uploaded"] += _sl_bytes
        log(worker_id, f"Chunk done ({chunk_bytes/1024/1024:.2f} MB). Uploading...")
        update_status("Up 0%")
        _up_outcome, _up_detail = _upload_with_retry(
            f"{manager_url}/upload_chunk", lambda: open(out_path, 'rb'),
            f"chunk_{kind}_{idx}.mp4",
            {'job_id': job_id, 'chunk_index': idx, 'kind': kind,
             'worker_id': worker_id, 'wallet': wallet or ''},
            worker_id, f"Chunk ({chunk_tag})",
            keepalive=lambda: report_chunk("processing", 100))
        upload_ok = (_up_outcome == 'ok')
        upload_final = (_up_outcome == 'final')  # manager already resolved this chunk, don't re-report
        if upload_final:
            log(worker_id, f"Chunk not accepted by manager ({chunk_tag}): {_up_detail}", "WARN")

        if upload_ok:
            log(worker_id, f"Chunk complete ({chunk_tag}).")
            _hint = _jobs_hint()
            if _hint: log(worker_id, _hint)
            d = WORKER_DETAILS.get(worker_id)
            if d is not None:
                d.update({"phase": "Done", "pct": 100})
                d["jobs_done"] += 1
            with STATS_LOCK:
                SESSION_STATS["jobs_done"] += 1
                SESSION_STATS["bytes_uploaded"] += chunk_bytes
        elif SHUTDOWN_EVENT.is_set():
            report_chunk("abandoned")
        elif not upload_final:
            err_msg = f"Chunk upload failed: {_up_detail}"
            log(worker_id, err_msg, "ERROR")
            report_chunk("failed", error_msg=err_msg)
            d = WORKER_DETAILS.get(worker_id)
            if d is not None:
                d["phase"] = "Failed"
                d["jobs_failed"] = d.get("jobs_failed", 0) + 1

        upload_chunk_log()
        cleanup()

    while not SHUTDOWN_EVENT.is_set():
        if PAUSE_REQUESTED:
             time.sleep(1); continue

        # Reset per-iteration job id so the catch-all handler below can't
        # mis-report a failure against the PREVIOUS (already-completed) job
        # when an error happens before a new job is assigned.
        job_id = None

        try:
            if quota_tracker and quota_tracker.check_cap():
                wait_sec = quota_tracker.get_wait_time()
                update_status("Quota Limit")
                log(worker_id, f"Daily Quota Reached. Reset in {wait_sec/3600:.1f} hours.")
                while wait_sec > 0 and not SHUTDOWN_EVENT.is_set():
                    time.sleep(min(60, wait_sec))
                    wait_sec -= 60
                    if not quota_tracker.check_cap(): break
                continue

            update_status("Idle")

            # =========================================================
            # RESUME: Finish any partial encodes from a previous run
            # =========================================================
            for _r_chk_path, _r_chk in _load_resume_checkpoints(temp_dir):
                if SHUTDOWN_EVENT.is_set(): break
                _r_partial = _r_chk.get('partial_path', '')
                _r_job_id  = _r_chk.get('job_id', '')
                if not _r_job_id or not os.path.exists(_r_partial):
                    log(worker_id, f"Stale resume checkpoint ({_r_job_id}). Removing.")
                    try: os.remove(_r_chk_path)
                    except: pass
                    continue

                # ----------------------------------------------------------
                # Check with the server: is this job still ours to resume?
                # ----------------------------------------------------------
                _r_server_status = None
                _r_server_owner  = None
                _r_check_failed  = False
                try:
                    _r_chk_resp = requests.get(
                        f"{manager_url}/job_status",
                        params={"job_id": _r_job_id},
                        headers=get_auth_headers(), timeout=10)
                    if _r_chk_resp.status_code == 200:
                        _r_chk_data    = _r_chk_resp.json()
                        _r_server_status = _r_chk_data.get("job_status")
                        _r_server_owner  = _r_chk_data.get("worker_id")
                    elif _r_chk_resp.status_code == 404:
                        # Job no longer exists on the server; discard checkpoint
                        log(worker_id, f"Checkpoint job {_r_job_id} not found on server. Discarding.")
                        for _fp in [_r_chk_path, _r_partial]:
                            try:
                                if os.path.exists(_fp): os.remove(_fp)
                            except: pass
                        continue
                    else:
                        _r_check_failed = True
                except Exception as _r_ce:
                    log(worker_id, f"Could not reach server to validate checkpoint ({_r_job_id}): {_r_ce}. Skipping resume this cycle.", "WARN")
                    _r_check_failed = True

                if _r_check_failed:
                    # Can't confirm ownership — skip this iteration, try again next cycle
                    continue

                if _r_server_status == "completed":
                    log(worker_id, f"Job {_r_job_id} already completed on server. Discarding checkpoint.")
                    for _fp in [_r_chk_path, _r_partial]:
                        try:
                            if os.path.exists(_fp): os.remove(_fp)
                        except: pass
                    continue

                if _r_server_status == "permanently_failed":
                    log(worker_id, f"Job {_r_job_id} is permanently failed. Discarding checkpoint.")
                    for _fp in [_r_chk_path, _r_partial]:
                        try:
                            if os.path.exists(_fp): os.remove(_fp)
                        except: pass
                    continue

                if _r_server_status == "processing" and _r_server_owner and _r_server_owner != worker_id:
                    # A different worker has been assigned this job — leave it alone
                    log(worker_id, f"Job {_r_job_id} is now owned by {_r_server_owner}. Abandoning checkpoint.")
                    for _fp in [_r_chk_path, _r_partial]:
                        try:
                            if os.path.exists(_fp): os.remove(_fp)
                        except: pass
                    continue

                # Job is queued (timed out) or still ours — reclaim it before resuming
                if _r_server_status in ("queued", "failed"):
                    try:
                        _r_reclaim = requests.post(
                            f"{manager_url}/reclaim_job",
                            json={"job_id": _r_job_id, "worker_id": worker_id,
                                  "version": WORKER_VERSION},
                            headers=get_auth_headers(), timeout=10)
                        if _r_reclaim.status_code == 409:
                            # Race: another worker claimed it first
                            log(worker_id, f"Job {_r_job_id} reclaim failed (already taken). Abandoning checkpoint.")
                            for _fp in [_r_chk_path, _r_partial]:
                                try:
                                    if os.path.exists(_fp): os.remove(_fp)
                                except: pass
                            continue
                        if _r_reclaim.status_code != 200:
                            log(worker_id, f"Job {_r_job_id} reclaim returned {_r_reclaim.status_code}. Skipping.", "WARN")
                            continue
                        log(worker_id, f"Reclaimed job {_r_job_id} from the queue.")
                    except Exception as _r_re:
                        log(worker_id, f"Reclaim request failed for {_r_job_id}: {_r_re}. Skipping.", "WARN")
                        continue
                # ----------------------------------------------------------

                _r_partial_dur = _probe_local_duration(_r_partial)
                if _r_partial_dur < 5.0:
                    log(worker_id, f"Partial encode for {_r_job_id} unreadable/too short ({_r_partial_dur:.1f}s). Discarding.")
                    for _fp in [_r_chk_path, _r_partial]:
                        try:
                            if os.path.exists(_fp): os.remove(_fp)
                        except: pass
                    continue
                _r_total_sec = _r_chk.get('total_sec', 0)
                _r_total_min = _r_chk.get('total_min', 0)
                _r_pct = int(_r_partial_dur / _r_total_sec * 100) if _r_total_sec > 0 else 0
                log(worker_id, f"Resuming job {_r_job_id}: was {_r_pct}% done ({_r_partial_dur:.1f}s/{_r_total_sec:.1f}s).")
                job_id = _r_job_id
                d = WORKER_DETAILS.get(worker_id)
                if d is not None:
                    d.update({"file": _r_job_id, "phase": "Encoding", "pct": _r_pct, "job_start": time.time()})
                post_status("processing", _r_pct, _r_total_min)

                _r_p1     = _r_partial + '.p1.mp4'
                _r_p2     = _r_partial + '.p2.mp4'
                _r_clist  = _r_partial + '.concat.txt'
                _r_merged = _r_partial + '.merged.mp4'
                _r_tmps   = [_r_p1, _r_p2, _r_clist, _r_merged]
                _resume_ok = False
                _r_fail_reason = "unknown"
                try:
                    if _r_total_sec > 0 and _r_partial_dur >= _r_total_sec - 20.0:
                        # The checkpoint already holds the whole film bar its
                        # last seconds: an encode that froze at the very end.
                        # Re-encoding that sliver just freezes again.
                        log(worker_id, f"Checkpoint is complete to within {max(0.0, _r_total_sec - _r_partial_dur):.1f}s; "
                                       "uploading it as is.", "WARN")
                        _resume_ok = True
                        raise _ResumeDone()
                    # Trim part1 to a clean keyframe boundary using stream-copy (no re-encode)
                    _r_trim_pt = max(0.0, _r_partial_dur - 5.0)
                    _r_trim_rc = subprocess.run(
                        [FFMPEG_CMD, '-y', '-i', _r_partial,
                         '-t', str(_r_trim_pt), '-c', 'copy', _r_p1],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                        encoding='utf-8', errors='replace', timeout=300)
                    if _r_trim_rc.returncode != 0 or not os.path.exists(_r_p1):
                        raise RuntimeError(f"Part-1 trim failed (rc={_r_trim_rc.returncode})")
                    _r_p1_dur = _probe_local_duration(_r_p1)
                    if _r_p1_dur <= 0:
                        raise RuntimeError("Trimmed part-1 not readable")

                    # Encode the remainder starting from _r_p1_dur
                    _r_hdrs  = f"X-Worker-Token: {WORKER_SECRET}\r\n"
                    _r_dl    = _r_chk.get('dl_url', '')
                    _r_ai    = _r_chk.get('audio_index')  # None = source has no audio
                    _r_si    = _r_chk.get('subtitle_indices', [])
                    _r_vf    = _r_chk.get('video_filter', ENCODING_CONFIG['VIDEO_SCALE'])
                    _r_af    = _r_chk.get('audio_filter', 'aresample=async=1')
                    _r_crf   = _r_chk.get('target_crf', int(ENCODING_CONFIG['VIDEO_CRF']))
                    # Determine if the source was a local file (--local-source) or HTTP.
                    # Local paths don't start with http(s)://, so skip reconnect flags.
                    _r_is_local_src = not (_r_dl.startswith('http://') or _r_dl.startswith('https://'))
                    log(worker_id, f"Encoding remainder from {_r_p1_dur:.1f}s...")
                    _r_input_args = (
                        ['-ss', str(_r_p1_dur), '-y', '-i', _r_dl]
                        if _r_is_local_src else
                        _http_input_flags(_r_hdrs) +
                        ['-ss', str(_r_p1_dur), '-y', '-i', _r_dl]
                    )
                    _r_rem_cmd = (
                        [FFMPEG_CMD] + _r_input_args
                        + ['-map', '0:v:0']
                        + (['-map', f'0:{_r_ai}'] if _r_ai is not None else [])
                        + [x for idx in _r_si for x in ['-map', f'0:{idx}']]
                        + ['-fps_mode', 'passthrough', '-avoid_negative_ts', 'make_zero',
                           '-c:v', ENCODING_CONFIG["VIDEO_CODEC"],
                           '-preset', ENCODING_CONFIG["VIDEO_PRESET"],
                           '-crf', str(_r_crf),
                           '-pix_fmt', ENCODING_CONFIG["VIDEO_PIX_FMT"],
                           '-vf', _r_vf,
                           '-c:a', ENCODING_CONFIG["AUDIO_CODEC"],
                           '-b:a', ENCODING_CONFIG["AUDIO_BITRATE"],
                           '-ac', ENCODING_CONFIG["AUDIO_CHANNELS"],
                           '-af', _r_af,
                           '-c:s', ENCODING_CONFIG["SUBTITLE_CODEC"],
                           '-movflags', 'frag_keyframe+empty_moov+default_base_moof',
                           '-progress', 'pipe:1', _r_p2])

                    _r_popen_kw = {}
                    if platform.system() == 'Windows':
                        _r_popen_kw['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP
                    else:
                        _r_popen_kw['start_new_session'] = True
                    _r_rem = subprocess.Popen(
                        _r_rem_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                        stdin=subprocess.DEVNULL, encoding='utf-8', errors='replace', **_r_popen_kw)
                    assert _r_rem.stdout is not None
                    with PROC_LOCK: ACTIVE_PROCS[worker_id] = _r_rem
                    _r_last_rep = 0
                    _r_pos = -1.0; _r_adv = time.time(); _r_stalled = False
                    while True:
                        if SHUTDOWN_EVENT.is_set(): _r_rem.terminate(); break
                        if not PAUSE_REQUESTED and time.time() - _r_adv > _StreamWatch.STALL_KILL_SEC:
                            _r_stalled = True
                            try: _r_rem.kill()
                            except Exception: pass
                            break
                        _r_ln = _r_rem.stdout.readline()
                        if not _r_ln and _r_rem.poll() is not None: break
                        if "out_time=" in _r_ln and "N/A" not in _r_ln and _r_total_sec > 0:
                            try:
                                _r_cur = get_seconds(_r_ln.split('=')[1].strip())
                                if _r_cur > _r_pos + 0.001:
                                    _r_pos = _r_cur; _r_adv = time.time()
                                _r_ov  = min(100, int((_r_p1_dur + _r_cur) / _r_total_sec * 100))
                                update_status(f"Enc {_r_ov}%")
                                if time.time() - _r_last_rep > 10:
                                    post_status("processing", _r_ov, _r_total_min)
                                    _r_last_rep = time.time()
                            except: pass
                    with PROC_LOCK:
                        if worker_id in ACTIVE_PROCS: del ACTIVE_PROCS[worker_id]
                    if SHUTDOWN_EVENT.is_set():
                        break  # keep partial + checkpoint for the next run
                    if _r_stalled:
                        raise RuntimeError("Remainder encode stalled with no progress")
                    if _r_rem.returncode != 0 or not os.path.exists(_r_p2):
                        raise RuntimeError(f"Remainder encode failed (rc={_r_rem.returncode})")

                    # Concatenate part1 + part2 into the final merged file
                    log(worker_id, "Concatenating resume parts...")
                    with open(_r_clist, 'w', encoding='utf-8') as _cf:
                        # ABSOLUTE paths: the concat demuxer resolves a relative
                        # entry against the list file's own folder, and the temp
                        # dir is itself relative ("./temp_encode_..."), so every
                        # resume used to fail right here with "No such file".
                        for _cp in (_r_p1, _r_p2):
                            _cp_abs = os.path.abspath(_cp).replace(os.sep, '/').replace("'", "'\\''")
                            _cf.write(f"file '{_cp_abs}'\n")
                    _r_cat_rc = subprocess.run(
                        [FFMPEG_CMD, '-y', '-f', 'concat', '-safe', '0',
                         '-i', _r_clist, '-c', 'copy', '-movflags', '+faststart', _r_merged],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                        encoding='utf-8', errors='replace', timeout=600)
                    if _r_cat_rc.returncode != 0 or not os.path.exists(_r_merged):
                        raise RuntimeError(f"Concat failed (rc={_r_cat_rc.returncode})")
                    os.replace(_r_merged, _r_partial)
                    _r_tmps.remove(_r_merged)  # already moved, skip final-cleanup
                    _resume_ok = True

                except _ResumeDone:
                    pass
                except Exception as _r_err:
                    log(worker_id, f"Resume failed for {_r_job_id}: {_r_err}. Discarding.", "ERROR")
                    _r_fail_reason = str(_r_err)[:300]
                finally:
                    for _fp in _r_tmps:
                        try:
                            if os.path.exists(_fp): os.remove(_fp)
                        except: pass

                if not _resume_ok:
                    for _fp in [_r_chk_path, _r_partial]:
                        try:
                            if os.path.exists(_fp): os.remove(_fp)
                        except: pass
                    # Hand the job back now. Saying nothing left it assigned to
                    # this worker, untouched, until the manager's 6h reclaim.
                    post_status("failed", error_msg=f"Resume failed: {_r_fail_reason}")
                    job_id = None
                    continue

                # Upload the resumed, fully merged file
                _r_file_bytes = os.path.getsize(_r_partial)
                log(worker_id, f"Resume complete ({_r_file_bytes/1024/1024:.2f} MB). Uploading...")
                post_status("uploading", 0)
                update_status("Up 0%")
                _r_outcome, _r_detail = _upload_with_retry(
                    f"{manager_url}/upload_result", lambda: open(_r_partial, 'rb'),
                    _r_job_id,
                    {'job_id': _r_job_id, 'worker_id': worker_id,
                     'duration': _r_total_min, 'wallet': wallet or ''},
                    worker_id, "Resumed job",
                    keepalive=lambda: post_status("uploading", 100))
                _r_up_ok = (_r_outcome == 'ok')

                if _r_up_ok:
                    log(worker_id, f"Resumed job {_r_job_id} complete.")
                    d = WORKER_DETAILS.get(worker_id)
                    if d is not None:
                        d.update({"phase": "Done", "pct": 100})
                        d["jobs_done"] += 1
                    with STATS_LOCK:
                        SESSION_STATS["jobs_done"] += 1
                        SESSION_STATS["bytes_uploaded"] += _r_file_bytes
                elif _r_outcome == 'final':
                    # The manager answered and has settled the job itself.
                    log(worker_id, f"Resumed job {_r_job_id} not accepted by manager: {_r_detail}", "WARN")
                else:
                    log(worker_id, f"Resume upload failed for {_r_job_id}: {_r_detail}", "ERROR")
                    post_status("failed", error_msg=f"Resume upload failed: {_r_detail}")

                # Always clean up the checkpoint and partial file after an upload attempt
                for _fp in [_r_chk_path, _r_partial]:
                    try:
                        if os.path.exists(_fp): os.remove(_fp)
                    except: pass
                # The resumed job is finished (one way or the other) — clear the
                # id so a later pre-assignment exception can't be mis-reported
                # against it (same guarantee as the per-iteration reset above).
                job_id = None
            # ========================================================

            # Shutdown arrived during a resume: do not go on to claim new work
            # only to abort it a moment later.
            if SHUTDOWN_EVENT.is_set(): break

            if check_version(manager_url):
                UPDATE_AVAILABLE = True; SHUTDOWN_EVENT.set(); break

            # =========================================================
            # CHUNKED MODE: ask for a slice of a split video first, so
            # the whole swarm works on one file at a time. Falls back
            # to classic whole-file jobs when nothing is chunkable.
            # =========================================================
            if not no_chunks and _CHUNK_SUPPORT["ok"]:
                try:
                    params = {'worker_id': worker_id, 'version': WORKER_VERSION}
                    if series_id: params['series_id'] = series_id
                    if max_size_mb and max_size_mb > 0: params['max_size_mb'] = max_size_mb
                    rc = requests.get(f"{manager_url}/get_chunk", params=params, headers=get_auth_headers(), timeout=30)
                    if rc.status_code == 404:
                        _CHUNK_SUPPORT["ok"] = False
                        log(worker_id, "Manager has no chunk support — using whole-file mode.")
                    elif rc.status_code == 401:
                        log(worker_id, "AUTH FAILED: Worker Secret is invalid or missing.", "CRITICAL")
                        SHUTDOWN_EVENT.set(); break
                    elif rc.status_code == 200:
                        cdata = rc.json()
                        if cdata.get("status") == "ok" and cdata.get("chunk"):
                            _ch = cdata["chunk"]
                            try:
                                process_chunk(_ch)
                            except Exception as _ce:
                                # Release the chunk immediately instead of letting
                                # it sit 'processing' until the 30-min stale sweep
                                # (which would stall the whole split-video pipeline
                                # the other threads are converged on).
                                log(worker_id, f"Chunk processing crashed: {_ce}", "ERROR")
                                try:
                                    requests.post(f"{manager_url}/report_chunk", json={
                                        "job_id": _ch.get("job_id"), "chunk_index": _ch.get("chunk_index"),
                                        "kind": _ch.get("kind", "video"), "worker_id": worker_id,
                                        "status": "failed", "error": str(_ce)[:512],
                                        "version": WORKER_VERSION,
                                    }, headers=get_auth_headers(), timeout=10)
                                except Exception: pass
                            continue
                        elif cdata.get("status") == "retry":
                            # Manager is splitting a video right now — wait for
                            # it instead of grabbing a different whole file, so
                            # all threads converge on the same video.
                            try: _wait = min(10, max(1, int(cdata.get("wait", 3))))
                            except: _wait = 3
                            for _ in range(_wait):
                                if SHUTDOWN_EVENT.is_set(): break
                                time.sleep(1)
                            continue
                        elif cdata.get("message") == "Chunking disabled":
                            # Config toggle is static per manager process — stop
                            # doubling every idle poll with a pointless request.
                            _CHUNK_SUPPORT["ok"] = False
                            log(worker_id, "Chunked encoding disabled on manager — using whole-file mode.")
                except Exception:
                    pass  # chunk fetch failed — fall through to /get_job

            try:
                params = {'worker_id': worker_id, 'version': WORKER_VERSION}
                if series_id: params['series_id'] = series_id
                if max_size_mb and max_size_mb > 0: params['max_size_mb'] = max_size_mb
                r = requests.get(f"{manager_url}/get_job", params=params, headers=get_auth_headers(), timeout=10)
            except: time.sleep(5); continue

            data = r.json() if r.status_code == 200 else None
            
            if r.status_code == 401:
                log(worker_id, "AUTH FAILED: Worker Secret is invalid or missing.", "CRITICAL")
                SHUTDOWN_EVENT.set(); break

            if data and data.get("status") == "ok":
                job = data["job"]; job_id = job['id']; dl_url = job['download_url']
                # If this worker has direct access to the source directory, prefer the
                # local file path — avoids streaming the file through the HTTP server.
                _local_src = None
                if local_source_dir:
                    _candidate = os.path.join(local_source_dir, job['id'].replace('/', os.sep))
                    if os.path.isfile(_candidate):
                        _local_src = os.path.abspath(_candidate)
                        dl_url = _local_src
                        log(worker_id, f"Job (local): {job['filename']}")
                    else:
                        log(worker_id, f"Job (local path not found, falling back to HTTP): {job['filename']}", "WARN")
                if _local_src is None:
                    log(worker_id, f"Job: {job['filename']}")
                d = WORKER_DETAILS.get(worker_id)
                if d is not None:
                    d.update({"file": job['filename'], "phase": "Probe", "pct": 0, "job_start": time.time()})

                # Per-job output filename so a leftover resume checkpoint can
                # never point at a DIFFERENT job's partial data. Previously every
                # job in a thread wrote to the same encoded.mp4, so a stale
                # checkpoint for job A could be resumed against job B's bytes and
                # uploaded as A — silent content corruption.
                _dst_safe_id = re.sub(r'[^a-zA-Z0-9_-]', '_', str(job_id))[:80]
                local_dst = os.path.join(temp_dir, f"encoded_{_dst_safe_id}{ENCODING_CONFIG['OUTPUT_EXT']}")

                # FFmpeg auth header string (format required by libavformat HTTP demuxer)
                ffmpeg_http_headers = f"X-Worker-Token: {WORKER_SECRET}\r\n"
                # When the source is a local file the auth header and reconnect flags
                # are unnecessary; flag this so the probe/encode commands omit them.
                _is_local = (_local_src is not None)

                # Quota accounting: a single HEAD request gives us the source size instantly,
                # letting encoding start immediately rather than waiting for a full download.
                if quota_tracker:
                    try:
                        if _is_local:
                            src_size = os.path.getsize(dl_url)
                        else:
                            head_r = requests.head(dl_url, headers=get_auth_headers(), timeout=10)
                            src_size = int(head_r.headers.get('content-length', 0))
                        if quota_tracker.check_cap():
                            # Another thread used up the quota after this job
                            # was claimed: give it back before sleeping on it.
                            post_status("failed", error_msg="Aborted: daily quota reached")
                            job_id = None
                            wait_sec = quota_tracker.get_wait_time()
                            update_status("Quota Limit")
                            log(worker_id, f"Daily Quota Reached. Reset in {wait_sec/3600:.1f} hours.")
                            while wait_sec > 0 and not SHUTDOWN_EVENT.is_set():
                                time.sleep(min(60, wait_sec))
                                wait_sec -= 60
                                if not quota_tracker.check_cap(): break
                            continue
                        if src_size > 0:
                            quota_tracker.add_usage(src_size)
                            quota_tracker.force_save()
                    except Exception as e:
                        log(worker_id, f"Quota size check failed: {e}", "WARN")

                post_status("downloading", 0)

                # -------------------------------------------------------
                # SOURCE INTEGRITY CHECK
                # Only meaningful for local-source workers: the worker reads
                # the first 4 MB of the local file and submits its hash so the
                # server can detect file corruption/replacement on disk.
                # For remote HTTP sources the server hosts the file itself, so
                # there is nothing to verify from the worker side — and naively
                # streaming 4 MB (or the full file when Range isn't supported)
                # before every encode wastes bandwidth and causes the worker to
                # appear stuck.
                # -------------------------------------------------------
                if _is_local:
                    log(worker_id, "Verifying source file integrity...")
                    update_status("Verifying")
                    _our_hash = _compute_source_hash(dl_url, _is_local)
                    if _our_hash is None:
                        log(worker_id, "Could not compute source hash. Skipping integrity check.", "WARN")
                    else:
                        try:
                            _vr = requests.post(
                                f"{manager_url}/verify_source_hash",
                                json={"job_id": job_id, "worker_id": worker_id,
                                      "source_hash": _our_hash},
                                headers=get_auth_headers(), timeout=10)
                            _vstatus = _vr.json().get("status") if _vr.status_code == 200 else "error"
                        except Exception as _ve:
                            log(worker_id, f"Hash verify request failed: {_ve}. Skipping check.", "WARN")
                            _vstatus = "error"

                        if _vstatus == "mismatch":
                            log(worker_id,
                                f"SOURCE HASH MISMATCH for {job_id}! "
                                "The file on this worker does not match the server's source. "
                                "Aborting encode.", "ERROR")
                            post_status("failed", error_msg="Source hash mismatch")
                            report_error(job_id, "hash_mismatch",
                                         f"Worker hash: {_our_hash}")
                            continue
                        elif _vstatus == "ok":
                            log(worker_id, "Source integrity verified.")
                        # "pending" or "error" → server has no hash yet, proceed normally
                # -------------------------------------------------------

                # audio_index None = "no audio track". It must NOT default to 0:
                # stream 0 is the video, and mapping it as audio produced silent
                # files with two video streams (see the audio_map guard below).
                total_sec = 0; total_min = 0; audio_index = None; subtitle_indices = []
                meta_audio_channels = None
                # Reset every job: a stale probe_data surviving from the previous
                # loop iteration must never satisfy the failure check below.
                probe_data = None
                # If the manager already probed the source it hands us the stream
                # layout, letting us skip the probe entirely — the slowest and
                # most failure-prone step on constrained workers (e.g. a Pi
                # range-streaming a large MKV over HTTP). The shortcut needs the
                # FULL layout (duration, a real audio track AND its channel
                # count) because the whole-file command always maps audio and
                # picks the downmix formula from the channel count — a partial
                # blob must fall back to probing, not silently degrade.
                _smeta = job.get('stream_meta') if isinstance(job, dict) else None
                if _smeta:
                    try:
                        _s_dur = float(_smeta.get('duration') or 0)
                        _ai = _smeta.get('audio_index')
                        _mac = int(_smeta.get('audio_channels') or 0)
                        if _s_dur > 0 and _ai is not None and _mac >= 1:
                            total_sec = _s_dur; total_min = int(total_sec / 60)
                            audio_index = int(_ai)
                            subtitle_indices = [int(x) for x in (_smeta.get('subtitle_indices') or [])]
                            meta_audio_channels = _mac
                            probe_data = {"from_manager": True}
                            log(worker_id, "Using stream info from manager; skipping probe.")
                        else:
                            _smeta = None  # incomplete blob → probe normally
                    except (TypeError, ValueError) as _sme:
                        log(worker_id, f"Bad stream_meta from manager ({_sme}); probing locally.", "WARN")
                        _smeta = None
                if probe_data is None:
                    update_status("Probing")
                _probe_last_err = ''
                for _probe_attempt in ([] if probe_data else range(3)):
                    try:
                        # Start each attempt clean so a partially-parsed failure
                        # can't leave duplicate subtitle maps or a half-set state.
                        probe_data = None
                        audio_index = None; subtitle_indices = []
                        if _is_local:
                            cmd_probe = [FFPROBE_CMD,
                                '-v', 'quiet', '-print_format', 'json', '-show_streams', '-show_format', dl_url]
                        else:
                            cmd_probe = [FFPROBE_CMD,
                                '-headers', ffmpeg_http_headers,
                                '-v', 'quiet', '-print_format', 'json', '-show_streams', '-show_format', dl_url]
                        res = subprocess.run(cmd_probe, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace', timeout=60)
                        _pd = json.loads(res.stdout)
                        dur = _pd.get('format', {}).get('duration')
                        if dur: total_sec = float(dur); total_min = int(total_sec / 60)

                        audio_streams = [s for s in _pd.get('streams', []) if s['codec_type'] == 'audio']
                        if audio_streams:
                            audio_index = audio_streams[0]['index']
                            for s in audio_streams:
                                if s.get('tags', {}).get('language', '').lower() in ['eng', 'en', 'english']:
                                    audio_index = s['index']; break
                        for s in _pd.get('streams', []):
                            if s['codec_type'] == 'subtitle':
                                if s.get('codec_name', '').lower() in ['subrip', 'ass', 'webvtt', 'mov_text', 'text', 'srt', 'ssa']:
                                    subtitle_indices.append(s['index'])
                        probe_data = _pd  # only assigned once fully parsed
                        break  # probe succeeded
                    except Exception as _probe_err:
                        # Not str(_probe_err) in the report: a TimeoutExpired
                        # message includes the command, token header and all.
                        _probe_last_err = (f"ffprobe timed out after {int(_probe_err.timeout)}s"
                                           if isinstance(_probe_err, subprocess.TimeoutExpired)
                                           else f"{type(_probe_err).__name__}: {str(_probe_err)[:200]}")
                        if _probe_attempt < 2:
                            log(worker_id, f"Probe failed (attempt {_probe_attempt+1}/3): {_probe_err}. Retrying in {5*(_probe_attempt+1)}s...", "WARN")
                            time.sleep(5 * (_probe_attempt + 1))
                        else:
                            log(worker_id, f"Probe failed after 3 attempts: {_probe_err}. Skipping job.", "ERROR")

                if probe_data is None:
                    post_status("failed", error_msg="FFprobe failed after 3 attempts")
                    _diag = None
                    try:
                        _diag = _source_failure_diag(None, dl_url, _is_local, 0)
                        _diag["phase"] = "probing"
                    except Exception as _de:
                        log(worker_id, f"Could not collect source diagnostics: {_de}", "WARN")
                    report_error(job_id, "probe_failure", "FFprobe failed after 3 attempts (could not read the source)",
                                 _probe_last_err, diag=_diag)
                    continue

                log(worker_id, f"Encoding ({total_min}m)...")
                post_status("processing", 0, total_min)

                # Disk space pre-flight: need at least 500 MB free for the encoded output
                try:
                    _disk_free = shutil.disk_usage(temp_dir).free
                    if _disk_free < 500 * 1024 * 1024:
                        log(worker_id, f"Low disk space: {_disk_free/1024**2:.0f} MB free, need 500 MB. Skipping.", "ERROR")
                        post_status("failed", error_msg="Insufficient disk space")
                        report_error(job_id, "disk_space", f"Only {_disk_free/1024**2:.0f} MB free, need 500 MB")
                        continue
                except Exception as _disk_e:
                    log(worker_id, f"Disk space check error: {_disk_e}", "WARN")

                # Font is only needed for the watermark
                local_font = os.path.join(temp_dir, "arial.ttf")
                if watermark:
                    src_font = os.path.join(_script_dir, "arial.ttf")
                    if not os.path.exists(src_font):
                        log(worker_id, "arial.ttf missing locally. Downloading from manager...")
                        try:
                            font_req = requests.get(f"{manager_url}/dl/font", headers=get_auth_headers(), timeout=30)
                            if font_req.status_code == 200:
                                with open(src_font, 'wb') as f:
                                    f.write(font_req.content)
                                log(worker_id, "Font downloaded successfully.")
                        except Exception as e:
                            log(worker_id, f"Font download failed: {e}", "WARN")
                    try:
                        if os.path.exists(src_font):
                            shutil.copy(src_font, local_font)
                    except: pass

                # Construct video filter conditionally based on watermark flag and font availability
                if watermark and os.path.exists(local_font):
                    font_arg = local_font.replace("\\", "/")
                    video_filter = f"{ENCODING_CONFIG['VIDEO_SCALE']},drawtext=text='@FractumSeraph':fontfile='{font_arg}':fontcolor=white@0.2:fontsize=12:x=10:y=h-th-10"
                else:
                    video_filter = ENCODING_CONFIG['VIDEO_SCALE']
                    if watermark:
                        log(worker_id, "Warning: arial.ttf could not be sourced. Skipping watermark.", "WARN")
                
                # Robust Audio Downmixing (Prevents crashes on corrupt streams claiming 40+ channels)
                audio_channels = 2 # Default assumption
                if meta_audio_channels is not None:
                    audio_channels = meta_audio_channels
                else:
                    try:
                        for s in probe_data.get('streams', []):
                            if s['index'] == audio_index:
                                audio_channels = int(s.get('channels', 2))
                                break
                    except: pass

                # AUDIO FILTER FIX (MONO + DIALOGUE FOCUS)
                audio_filter = "aresample=async=1" 
                
                if audio_channels > 2:
                    # 5.1 -> Mono: Mix Center (FC) strongly (50%) to ensure dialogue is clear
                    # c0 = 0.5*FC + 0.25*FL + 0.25*FR + 0.1*Surround
                    audio_filter = "pan=mono|c0=0.5*FC+0.25*FL+0.25*FR+0.1*BL+0.1*BR,aresample=async=1"
                elif audio_channels == 2:
                    # Stereo -> Mono: Standard Mix
                    audio_filter = "pan=mono|c0=0.5*c0+0.5*c1,aresample=async=1"
                else:
                    # Mono -> Mono: Passthrough
                    audio_filter = "aresample=async=1"

                target_crf = int(ENCODING_CONFIG["VIDEO_CRF"])

                # Map the audio track ONLY when the source actually has one.
                # audio_index defaults to 0, so an audio-less source (or a
                # probe that found no audio streams) used to emit
                # '-map 0:v:0 -map 0:0' — the VIDEO mapped twice. Those files
                # still verified as AV1/480p and shipped, silent, with a
                # duplicated video stream. The chunk path always guarded this;
                # the whole-file path did not.
                audio_map = ['-map', f'0:{audio_index}'] if audio_index is not None else []
                if audio_index is None:
                    log(worker_id, "Source has no audio stream — encoding video only.", "WARN")
                if _is_local:
                    cmd = [FFMPEG_CMD, '-y', '-i', dl_url, '-map', '0:v:0'] + audio_map
                else:
                    cmd = ([FFMPEG_CMD] + _http_input_flags(ffmpeg_http_headers)
                           + ['-y', '-i', dl_url, '-map', '0:v:0'] + audio_map)
                _sub_map_args = [x for idx in subtitle_indices for x in ('-map', f'0:{idx}')]
                cmd.extend(_sub_map_args)
                
                cmd.extend([
                    '-fps_mode', 'passthrough',
                    '-avoid_negative_ts', 'make_zero',
                    '-c:v', ENCODING_CONFIG["VIDEO_CODEC"], 
                    '-preset', ENCODING_CONFIG["VIDEO_PRESET"], 
                    '-crf', str(target_crf),   # [CHANGED] Uses dynamically calculated CRF
                    '-pix_fmt', ENCODING_CONFIG["VIDEO_PIX_FMT"], 
                    '-vf', video_filter, 
                    '-c:a', ENCODING_CONFIG["AUDIO_CODEC"], 
                    '-b:a', ENCODING_CONFIG["AUDIO_BITRATE"], 
                    '-ac', ENCODING_CONFIG["AUDIO_CHANNELS"], # Enforce 1 channel (Mono)
                    '-af', audio_filter, 
                    '-c:s', ENCODING_CONFIG["SUBTITLE_CODEC"], 
                    # frag_keyframe writes each GOP as a self-contained fragment so the file
                    # remains readable even if the process is killed mid-encode.
                    '-movflags', 'frag_keyframe+empty_moov+default_base_moof',
                    '-progress', 'pipe:1', 
                    local_dst
                ])

                # Save a resume checkpoint so we can recover this encode if interrupted.
                _chk_safe_id = re.sub(r'[^a-zA-Z0-9_-]', '_', str(job_id))
                _chk_path = os.path.join(temp_dir, f"{_RESUME_CHK_PREFIX}{_chk_safe_id}.json")
                _save_resume_checkpoint(_chk_path, {
                    "job_id":           job_id,
                    "dl_url":           dl_url,
                    "partial_path":     local_dst,
                    "total_sec":        total_sec,
                    "total_min":        total_min,
                    "audio_index":      audio_index,
                    "subtitle_indices": subtitle_indices,
                    "target_crf":       target_crf,
                    "video_filter":     video_filter,
                    "audio_filter":     audio_filter,
                    "created_at":       time.time(),
                })

                proc = None; enc_time = 0; _wf_trunc_note = None; _wf_stall_salvaged = False
                _subs_dropped = False
                log_buffer = []  # defined before the loop: a pre-first-attempt
                                 # shutdown must not NameError the failure dump
                for _enc_attempt in range(3):
                    if SHUTDOWN_EVENT.is_set(): break
                    if _enc_attempt > 0:
                        # An mp4-muxer assertion (movenc "next_dts <= 0x7fffffff")
                        # is data-dependent and NOT fixed by re-running: it comes
                        # from a bad timestamp/duration in a mapped stream, and in
                        # practice from the tx3g subtitle track built out of the
                        # source's subrip cues. Retrying identically burned all 3
                        # attempts and left the job permanently_failed 51 minutes
                        # into an 86-minute encode. Drop the subtitles and retry:
                        # video+audio is worth far more than a failed job.
                        if (not _subs_dropped and _sub_map_args
                                and any('movenc' in l or 'next_dts' in l for l in log_buffer)):
                            for _pair in range(0, len(_sub_map_args), 2):
                                _flag, _val = _sub_map_args[_pair], _sub_map_args[_pair + 1]
                                for _i in range(len(cmd) - 1):
                                    if cmd[_i] == _flag and cmd[_i + 1] == _val:
                                        del cmd[_i:_i + 2]
                                        break
                            _subs_dropped = True
                            log(worker_id, "mp4 muxer assertion (bad subtitle timestamps) — "
                                           "retrying WITHOUT subtitles.", "WARN")
                        # Same reasoning as the chunk path: a source we could
                        # not read is worth waiting out, an encode that failed
                        # on its own is not.
                        if _is_source_read_failure(log_buffer) and not _wf_trunc_note:
                            _retry_delay = 120 * _enc_attempt
                            log(worker_id, f"Could not read the source (rc="
                                           f"{_ffmpeg_rc_text(proc.returncode) if proc else '?'}) "
                                           f"\u2014 waiting {_retry_delay}s for it to come back.", "WARN")
                        else:
                            _retry_delay = 30
                            log(worker_id, f"Encode failed (attempt {_enc_attempt}/3, rc="
                                           f"{_ffmpeg_rc_text(proc.returncode) if proc else '?'}). "
                                           f"Retrying in {_retry_delay}s...", "WARN")
                        update_status("Retrying")
                        for _ in range(_retry_delay):
                            if SHUTDOWN_EVENT.is_set(): break
                            time.sleep(1)
                        if SHUTDOWN_EVENT.is_set(): break
                        log(worker_id, f"Re-encoding ({total_min}m)...")
                        post_status("processing", 0, total_min)

                    start_enc = time.time(); last_rep = 0; last_enc_pct = 0; last_hb = 0
                    log_buffer = []
                    # See the chunk path: readline() blocks while ffmpeg opens
                    # the source, so the ticking has to come from elsewhere.
                    watch = _StreamWatch(update_status, single_mode, measure=True).start()

                    popen_kwargs = {}
                    if platform.system() == 'Windows':
                        popen_kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP
                    else:
                        popen_kwargs['start_new_session'] = True

                    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, encoding='utf-8', errors='replace', **popen_kwargs)
                    assert proc.stdout is not None
                    watch.attach(proc)

                    with PROC_LOCK: ACTIVE_PROCS[worker_id] = proc

                    # Independent heartbeat: keeps the manager updated even while
                    # this loop is blocked in readline() with a SIGSTOP'd ffmpeg
                    # (a pause), so a long pause doesn't get the job reassigned.
                    _hb = {"pct": 0}
                    _hb_stop = _start_heartbeat(
                        lambda: post_status("paused" if PAUSE_REQUESTED else "processing", _hb["pct"]))

                    raw_log_path = os.path.join(temp_dir, "encode.log")
                    # try/finally: an exception mid-loop (e.g. disk-full on the
                    # log write) must still stop the heartbeat thread — which
                    # would otherwise post "processing" forever, contradicting
                    # the "failed" status the outer handler reports — and must
                    # kill ffmpeg, which would otherwise block on a full pipe
                    # once nobody reads its stdout.
                    try:
                        with open(raw_log_path, 'w', encoding='utf-8') as raw_log:
                            while True:
                                if PAUSE_REQUESTED:
                                    _now = time.time()
                                    if _now - last_hb > 30:
                                        post_status("paused", last_enc_pct)
                                        last_hb = _now
                                    time.sleep(0.2)
                                    continue

                                line = proc.stdout.readline()
                                if line:
                                    log_buffer.append(line); log_buffer = log_buffer[-50:]
                                    raw_log.write(line)
                                    raw_log.flush()

                                if not line and proc.poll() is not None: break

                                if "out_time=" in line and "N/A" not in line and total_sec > 0:
                                    try:
                                        time_str = line.split('=')[1].strip()
                                        curr_sec = get_seconds(time_str)
                                        pct = min(100, int((curr_sec/total_sec)*100))
                                        last_enc_pct = pct
                                        _hb["pct"] = pct

                                        watch.note_progress(pct, curr_sec)
                                        if single_mode: print_progress(worker_id, curr_sec, total_sec, prefix='Enc')
                                        else: update_status(f"Enc {pct}%")

                                        if time.time() - last_rep > 10:
                                            post_status("processing", pct)
                                            last_rep = time.time()
                                            last_hb = last_rep
                                    except: pass
                                elif line.startswith("speed="):
                                    _set_speed(worker_id, line)
                    finally:
                        watch.stop()
                        _hb_stop.set()
                        with PROC_LOCK:
                            if worker_id in ACTIVE_PROCS: del ACTIVE_PROCS[worker_id]
                        if proc.poll() is None:
                            try: proc.kill()
                            except Exception: pass

                    enc_time = time.time() - start_enc
                    if SHUTDOWN_EVENT.is_set(): break
                    if watch.stall_killed:
                        log_buffer.append("Stream ends prematurely (no progress; ffmpeg stopped by the stall watchdog)\n")
                        # See the chunk path. Tighter than the manager's own
                        # tolerance on purpose: never ship a film knowingly
                        # missing more than its last few seconds.
                        _s_dur = _clean_stopped_output(local_dst) if total_sec > 0 else None
                        if _s_dur is not None and _s_dur >= total_sec - 20.0:
                            log(worker_id, f"Encode stalled {max(0.0, total_sec - _s_dur):.1f}s before the end of "
                                           f"the source; keeping the {_s_dur:.1f}s already encoded.", "WARN")
                            _wf_stall_salvaged = True; _wf_trunc_note = None
                            break
                        log(worker_id, f"{watch.kill_reason()}; stopped ffmpeg.", "WARN")
                    if proc.returncode == 0:
                        # Self-check BEFORE uploading: a dropped source stream
                        # can make ffmpeg see a premature EOF and exit 0 with a
                        # truncated file. The manager rejects those anyway —
                        # catching it locally saves the (large) upload and
                        # retries immediately. Same tolerance as the manager.
                        _wf_odur = _media_duration(local_dst) if total_sec > 0 else None
                        if total_sec > 0 and _wf_odur is None:
                            log(worker_id, "Could not read back encode duration; skipping the "
                                           "local truncation check.", "WARN")
                        elif total_sec > 0:
                            _wf_tol = max(10.0, total_sec * 0.05)
                            if _wf_odur < total_sec - _wf_tol:
                                _wf_trunc_note = f"{_wf_odur:.1f}s of {total_sec:.1f}s"
                                log(worker_id, f"Encode output truncated ({_wf_trunc_note}) — source "
                                               "stream likely dropped mid-encode. Retrying.", "WARN")
                                try: os.remove(local_dst)
                                except OSError: pass
                                continue  # burn this attempt, re-encode
                        _wf_trunc_note = None
                        break

                gz_log_path = os.path.join(temp_dir, "encode.log.gz")
                try:
                    with open(raw_log_path, 'rb') as f_in, gzip.open(gz_log_path, 'wb') as f_out:
                        shutil.copyfileobj(f_in, f_out)
                except Exception as e:
                    log(worker_id, f"Failed to compress log: {e}", "WARN")

                def upload_encode_log():
                    if os.path.exists(gz_log_path):
                        try:
                            with open(gz_log_path, 'rb') as lf:
                                requests.post(f"{manager_url}/upload_log", 
                                    files={'log_file': (f"{job_id.replace('/', '_')}.log.gz", lf)},
                                    data={'job_id': job_id, 'worker_id': worker_id},
                                    headers=get_auth_headers(), timeout=60)
                        except Exception as e:
                            log(worker_id, f"Failed to upload log: {e}", "WARN")

                if single_mode: print_progress(worker_id, total_sec, total_sec, prefix='Enc', suffix='OK')

                _keep_partial = False
                if proc and (proc.returncode == 0 or _wf_stall_salvaged) and os.path.exists(local_dst):
                    final_size_bytes = os.path.getsize(local_dst)
                    final_size = final_size_bytes / 1024 / 1024
                    log(worker_id, f"Encode done ({enc_time:.0f}s, {final_size:.2f}MB). Uploading...")
                    post_status("uploading", 0)
                    
                    class ProgressFileReader:
                        def __init__(self, filename, callback):
                            self._f = open(filename, 'rb'); self._total = os.path.getsize(filename)
                            self._read = 0; self._callback = callback; self._last_time = 0
                            self._last_pct = 0
                        def __enter__(self): return self
                        def __exit__(self, exc_type, exc_val, exc_tb): self._f.close()
                        def read(self, size=-1):
                            if PAUSE_REQUESTED:
                                _up_hb = time.time()
                                while PAUSE_REQUESTED and not SHUTDOWN_EVENT.is_set():
                                    if time.time() - _up_hb > 30:
                                        self._callback(self._last_pct)
                                        _up_hb = time.time()
                                    time.sleep(1)
                            data = self._f.read(size); self._read += len(data)
                            pct = int((self._read / self._total) * 100)
                            self._last_pct = pct
                            if single_mode: print_progress(worker_id, self._read, self._total, prefix='Up')
                            else: update_status(f"Up {pct}%")
                            if time.time() - self._last_time > 30:
                                self._callback(pct); self._last_time = time.time()
                            return data
                        def __getattr__(self, attr): return getattr(self._f, attr)

                    def upload_cb(pct): post_status("uploading", pct)

                    _up_outcome, _up_detail = _upload_with_retry(
                        f"{manager_url}/upload_result",
                        lambda: ProgressFileReader(local_dst, upload_cb), job_id,
                        {'job_id': job_id, 'worker_id': worker_id, 'duration': total_min, 'wallet': wallet or ''},
                        worker_id, "Job",
                        keepalive=lambda: post_status("uploading", 100))
                    upload_success = (_up_outcome == 'ok')
                    upload_final = (_up_outcome == 'final')  # manager already resolved the job — don't re-report
                    if upload_final:
                        log(worker_id, f"Upload not accepted by manager: {_up_detail}", "WARN")

                    if upload_success:
                        if single_mode: print_progress(worker_id, 100, 100, prefix='Up', suffix='OK')
                        log(worker_id, "Job complete.")
                        _hint = _jobs_hint()
                        if _hint: log(worker_id, _hint)
                        d = WORKER_DETAILS.get(worker_id)
                        if d is not None:
                            d.update({"phase": "Done", "pct": 100})
                            d["jobs_done"] += 1
                        with STATS_LOCK:
                            SESSION_STATS["jobs_done"] += 1
                            SESSION_STATS["bytes_uploaded"] += final_size_bytes
                        # Remove the resume checkpoint now that the job is finished
                        try:
                            _done_chk = os.path.join(temp_dir, f"{_RESUME_CHK_PREFIX}{re.sub(r'[^a-zA-Z0-9_-]', '_', str(job_id))}.json")
                            if os.path.exists(_done_chk): os.remove(_done_chk)
                        except: pass
                        upload_encode_log()
                    elif upload_final:
                        # Manager already resolved the job (409/400) — its state
                        # is authoritative; a "failed" report here would clobber it.
                        d = WORKER_DETAILS.get(worker_id)
                        if d is not None: d["phase"] = "Done"
                        upload_encode_log()
                    else:
                        d = WORKER_DETAILS.get(worker_id)
                        if d is not None:
                            d["phase"] = "Failed"
                            d["jobs_failed"] = d.get("jobs_failed", 0) + 1
                        err_msg = f"Upload failed: {_up_detail}"
                        log(worker_id, err_msg, "ERROR")
                        post_status("failed", error_msg=err_msg)
                        upload_encode_log()

                else:
                    rc = proc.returncode if proc else -1
                    err_msg = f"FFmpeg exited with code {_ffmpeg_rc_text(rc)}"
                    if _is_source_read_failure(log_buffer) and _is_local:
                        err_msg = (f"Could not read the local source file — "
                                   f"FFmpeg exited with code {_ffmpeg_rc_text(rc)}")
                        _where = ""
                        try:
                            _p = float((watch.diag() if proc is not None else {}).get('pos_s') or 0)
                            if _p > 0:
                                _where = f" around {int(_p // 3600)}:{int(_p % 3600 // 60):02d}:{int(_p % 60):02d}"
                        except Exception:
                            pass
                        log(worker_id, f"This machine's own copy of the file may be damaged or incomplete{_where}: "
                                       f"{dl_url}. Compare it with the server's copy.", "WARN")
                    elif _is_source_read_failure(log_buffer):
                        err_msg = (f"Could not read the source — "
                                   f"FFmpeg exited with code {_ffmpeg_rc_text(rc)}")
                    if _wf_trunc_note:
                        err_msg = f"Truncated output ({_wf_trunc_note}) — source stream interrupted"
                    if SHUTDOWN_EVENT.is_set(): err_msg = "Aborted by user/update"

                    d = WORKER_DETAILS.get(worker_id)
                    if d is not None and not SHUTDOWN_EVENT.is_set():
                        d["phase"] = "Failed"
                        d["jobs_failed"] = d.get("jobs_failed", 0) + 1

                    log(worker_id, err_msg, "ERROR")
                    log(worker_id, "--- FFmpeg Output Dump ---", "ERROR")
                    for l in log_buffer: safe_print(f"    {l.strip()}")
                    log(worker_id, "--------------------------", "ERROR")
                    post_status("failed", error_msg=err_msg)
                    if not SHUTDOWN_EVENT.is_set():
                        _diag = None
                        if _wf_trunc_note or _is_source_read_failure(log_buffer):
                            try:
                                _fs = int(job.get('file_size') or 0)
                                _wd = watch.diag() if proc is not None else {}
                                _off = (int(_fs * float(_wd.get('pos_s') or 0) / total_sec)
                                        if (_fs > 0 and total_sec > 0) else 0)
                                _diag = _source_failure_diag(watch if proc is not None else None,
                                                             dl_url, _is_local, _off)
                            except Exception as _de:
                                log(worker_id, f"Could not collect source diagnostics: {_de}", "WARN")
                        report_error(job_id, "encode_failure", err_msg, _error_tail(log_buffer), diag=_diag)
                    upload_encode_log()
                    # Stopped mid-encode: leave the partial file and its
                    # checkpoint so the next start resumes instead of starting
                    # over. (Deleting it here defeated resume on every clean
                    # stop; only a crash or power cut ever resumed.)
                    try:
                        _keep_partial = (SHUTDOWN_EVENT.is_set() and os.path.exists(local_dst)
                                         and os.path.getsize(local_dst) > 0)
                    except OSError:
                        _keep_partial = False

                if not _keep_partial:
                    try:
                        if os.path.exists(_chk_path): os.remove(_chk_path)
                    except OSError: pass
                if os.path.exists(local_dst) and not _keep_partial: os.remove(local_dst)
                if os.path.exists(raw_log_path): os.remove(raw_log_path)
                if os.path.exists(gz_log_path): os.remove(gz_log_path)
            else:
                if single_mode and not _plain_log():
                    with CONSOLE_LOCK:
                        sys.stdout.write(f"\033[2K\r[{datetime.now().strftime('%H:%M:%S')}] [{worker_id}] Idle. Waiting...")
                        sys.stdout.flush()
                time.sleep(10)
        except Exception as e:
            err_str = str(e)
            err_tb = traceback.format_exc()
            log(worker_id, f"Error: {err_str}", "CRITICAL")
            try:
                # Only report against a job actually assigned this iteration.
                if job_id:
                    post_status("failed", error_msg=err_str)
                    report_error(job_id, "exception", err_str, err_tb)
            except: pass
            time.sleep(10)

def _grace_join(threads, seconds):
    """Give worker threads a few seconds to tell the manager they stopped."""
    deadline = time.time() + seconds
    for t in threads:
        left = deadline - time.time()
        if left <= 0: break
        try: t.join(timeout=left)
        except Exception: pass

def run_worker(args):
    print("==================================================")
    print(" FRACTUM DISTRIBUTED WORKER")
    print("==================================================")

    config_file = "worker_config.json"
    saved_config = {}
    
    if os.path.exists(config_file):
        try:
            with open(config_file, 'r') as f:
                content = f.read().strip()
                if content:
                    saved_config = json.loads(content)
                else:
                    print("[!] Config file is empty. Resetting.")
                    f.close()
                    os.remove(config_file)
                    
                if args.username == DEFAULT_USERNAME and 'username' in saved_config:
                    args.username = saved_config['username']
                if args.workername == DEFAULT_WORKERNAME and 'workername' in saved_config:
                    args.workername = saved_config['workername']
                if not getattr(args, 'wallet', None) and saved_config.get('wallet'):
                    args.wallet = saved_config['wallet']
                    print(f"[*] Using saved FractumCoin wallet: {args.wallet}")
        except json.JSONDecodeError:
            print("[!] Config file corrupted. Resetting.")
            os.remove(config_file)
        except Exception as e:
            print(f"[!] Warning: Could not read config file: {e}")

    if sys.stdin.isatty():
        config_changed = False
        
        if args.username == DEFAULT_USERNAME:
            print("\n[*] First Time Setup detected.")
            print("    Please enter the USERNAME of the person running the program.")
            print("    (e.g., 'FractumSeraph', 'John Smith')")
            u_input = input(f"    Enter Username (Default: {DEFAULT_USERNAME}): ").strip()
            if u_input:
                args.username = u_input
                config_changed = True
        
        if args.workername == DEFAULT_WORKERNAME:
            w_default = f"Node-{int(time.time())}"
            print("\n    Please enter a name for THIS COMPUTER.")
            print("    (e.g., 'Fractums Laptop', 'Johns Gaming PC')")
            w_input = input(f"    Enter Worker Name (Default: {w_default}): ").strip()
            if w_input:
                args.workername = w_input
            else:
                args.workername = w_default
            config_changed = True

        if config_changed:
            try:
                cfg = dict(saved_config)
                cfg.update({"username": args.username, "workername": args.workername})
                if getattr(args, 'wallet', None):
                    cfg["wallet"] = args.wallet
                with open(config_file, 'w') as f:
                    json.dump(cfg, f, indent=4)
                print(f"[*] Configuration saved to {config_file}")
            except:
                print("[!] Failed to save configuration file.")

    # Persist a newly provided wallet address (like username/workername) so
    # future runs don't need the flag.
    if getattr(args, 'wallet', None) and saved_config.get('wallet') != args.wallet:
        try:
            cfg = dict(saved_config)
            cfg.setdefault("username", args.username)
            cfg.setdefault("workername", args.workername)
            cfg["wallet"] = args.wallet
            with open(config_file, 'w') as f:
                json.dump(cfg, f, indent=4)
            print(f"[*] FractumCoin wallet saved to {config_file}")
        except:
            print("[!] Failed to save wallet to configuration file.")

    if check_ffmpeg(getattr(args, 'ffmpeg', None)):
        threading.Thread(target=_ffmpeg_update_loop, daemon=True).start()

    manager_url = (args.manager or DEFAULT_MANAGER_URL).rstrip('/')
    username = args.username or DEFAULT_USERNAME
    base_workername = args.workername or DEFAULT_WORKERNAME
    
    global WORKER_SECRET
    if args.secret: WORKER_SECRET = args.secret

    if WORKER_SECRET == "DefaultInsecureSecret":
        print("[*] INFO: Using default WORKER_SECRET. Compatible with public manager defaults.")
    
    if not verify_connection(manager_url): sys.exit(1)
    if check_version(manager_url): apply_update(manager_url)
    
    quota_tracker = None
    if args.daily_quota > 0:
        print(f"[*] Daily Quota Active: {args.daily_quota} GB")
        quota_tracker = QuotaTracker(args.daily_quota, base_workername)
        if quota_tracker.check_cap():
            print(f"[!] Quota already exceeded for today. Waiting until tomorrow.")

    num_jobs = args.jobs if args.jobs > 0 else 1
    if num_jobs > 32: num_jobs = 32
    ENC_USAGE["slots"] = num_jobs
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    threads = []
    worker_ids = []
    _force_tui = getattr(args, 'force_tui', False)

    use_tui = HAS_TEXTUAL and (not getattr(args, 'no_tui', False) or _force_tui)
    # A full-screen UI needs a terminal to draw on. With output going to a
    # file, a pipe or the systemd journal it only filled the log with cursor
    # control codes, so fall back to plain lines there (--force-tui overrides).
    _no_terminal = False
    try:
        _no_terminal = not sys.stdout.isatty()
    except Exception:
        _no_terminal = True
    if use_tui and _no_terminal and not _force_tui:
        use_tui = False
    single_mode = (num_jobs == 1) and not use_tui

    # Initialize per-worker detail state and session stats
    global WORKER_DETAILS, SESSION_STATS
    WORKER_DETAILS = {}
    with STATS_LOCK:
        SESSION_STATS["jobs_done"] = 0
        SESSION_STATS["bytes_uploaded"] = 0
        SESSION_STATS["start"] = time.time()

    if args.series_id:
        print(f"[*] SERIES ID ACTIVE: Processing Series #{args.series_id}")

    for i in range(num_jobs):
        worker_id = f"{username}-{base_workername}-{i+1}"
        worker_ids.append(worker_id)
        WORKER_DETAILS[worker_id] = {"file": "-", "phase": "Starting", "pct": 0, "job_start": 0.0, "jobs_done": 0, "jobs_failed": 0}
        temp_dir = f"./temp_encode_{base_workername}_{i+1}"

        t = threading.Thread(target=worker_task, args=(worker_id, manager_url, temp_dir, quota_tracker, single_mode, args.series_id, args.watermark, args.max_size_mb, getattr(args, 'local_source', None), getattr(args, 'no_chunks', False), getattr(args, 'wallet', None)))
        t.daemon = True
        t.start()
        threads.append(t)

    if not single_mode and not use_tui:
        monitor_t = threading.Thread(target=monitor_status_loop, args=(worker_ids,))
        monitor_t.daemon = True
        monitor_t.start()

    global PAUSE_REQUESTED, TUI_APP
    if use_tui:
        app = WorkerApp(
            worker_ids=worker_ids,
            threads=threads,
            quota_tracker=quota_tracker,
            manager_url=manager_url,
        )
        TUI_APP = app
        # Save Windows console modes now (before Textual modifies them) so
        # we can unconditionally restore them on any exit path — including
        # crashes and abnormal shutdowns that skip Textual's own cleanup.
        # Without this, echo is left disabled, causing the "can't see typing"
        # symptom and ANSI mouse-tracking sequences leaking into the shell.
        if platform.system() == 'Windows':
            try:
                import ctypes, ctypes.wintypes, atexit as _atexit
                _k32   = ctypes.windll.kernel32
                _hIn   = _k32.GetStdHandle(-10)   # STD_INPUT_HANDLE
                _hOut  = _k32.GetStdHandle(-11)   # STD_OUTPUT_HANDLE
                _m_in  = ctypes.wintypes.DWORD()
                _m_out = ctypes.wintypes.DWORD()
                _k32.GetConsoleMode(_hIn,  ctypes.byref(_m_in))
                _k32.GetConsoleMode(_hOut, ctypes.byref(_m_out))
                def _restore_win_console():
                    try:
                        # Full terminal reset sequence — covers every mode Textual
                        # may have enabled that survives an abnormal exit.
                        sys.stdout.write(
                            '\033[?1049l'   # exit alternate screen buffer (main symptom:
                                            #   cursor stuck at top-left after exit)
                            '\033[?2004l'   # disable bracketed-paste mode
                            '\033[?1000l'   # disable basic mouse tracking
                            '\033[?1002l'   # disable button-event tracking
                            '\033[?1003l'   # disable any-event tracking
                            '\033[?1006l'   # disable SGR extended mouse mode
                            '\033[?1015l'   # disable URXVT extended mouse mode
                            '\033[?25h'     # ensure cursor is visible
                            '\033[0m'       # reset all SGR attributes (color, bold…)
                            '\r\n'          # move to a clean line
                        )
                        sys.stdout.flush()
                    except Exception:
                        pass
                    try:
                        _k32.SetConsoleMode(_hIn,  _m_in)
                        _k32.SetConsoleMode(_hOut, _m_out)
                    except Exception:
                        pass
                _atexit.register(_restore_win_console)
            except Exception:
                pass
        # Run the TUI.  Mouse support is left enabled so RichLog and DataTable
        # remain scrollable with the mouse wheel.  The atexit handler and the
        # reset block below send the disable sequences after Textual exits,
        # which is the only safe time to write raw escapes to the terminal.
        global _TUI_WAS_RUNNING
        _TUI_WAS_RUNNING = True
        app.run()
        TUI_APP = None
        # Explicit terminal reset after a clean exit — Textual should have
        # done this itself, but belt-and-suspenders for any missed sequences.
        try:
            sys.stdout.write(
                '\033[?1049l'   # exit alternate screen buffer
                '\033[?2004l'   # disable bracketed-paste mode
                '\033[?1000l\033[?1002l\033[?1003l\033[?1006l\033[?1015l'
                '\033[?25h'     # show cursor
                '\033[0m'       # reset SGR attributes
                '\r\n'
            )
            sys.stdout.flush()
        except Exception:
            pass
    else:
        if HAS_TEXTUAL and getattr(args, 'no_tui', False):
            _tui_reason = "--no-tui flag passed"
        elif HAS_TEXTUAL and _no_terminal:
            _tui_reason = "output is not a terminal"
        else:
            _tui_reason = _TEXTUAL_UNAVAIL_REASON or "textual not installed (pip install textual)"
        # safe_print clears the status line first; a bare print() landed on
        # the end of it ("[1: Idle] [2: Idle]Fractum Worker v...").
        safe_print(f"Fractum Worker v{WORKER_VERSION} — TUI disabled ({_tui_reason})")
        while True:
            if not PAUSE_REQUESTED:
                all_dead = True
                for t in threads:
                    if t.is_alive(): all_dead = False; break
                if all_dead: break
                # Draining ("Finish", or an update) waits for the active work,
                # as the TUI does. Only an abort leaves early, after a moment
                # for the threads to hand their work back to the manager.
                if SHUTDOWN_EVENT.is_set() and ABORT_EVENT.is_set():
                    _grace_join(threads, 8)
                    break
                time.sleep(0.5)
                continue

            MONITOR_PAUSED.set()            # stop monitor from clobbering stdout
            time.sleep(0.6)                 # give it a moment to stop writing
            sys.stdout.write('\n')          # move to a clean line
            sys.stdout.flush()
            toggle_processes(suspend=True)
            print("\n" + "="*40)
            print(" [!] WORKER PAUSED")
            print("="*40)
            print(" [C]ontinue  - Resume encoding")
            print(" [F]inish    - Finish active, then stop")
            print(" [S]top      - Abort immediately")
            print(" Ctrl+C again - Force abort")

            # Open /dev/tty directly so input works even when stdin is a pipe
            # (e.g. launched via curl | bash or inside tmux with redirected stdin).
            _input_src = None
            if not sys.stdin.isatty():
                try:
                    _input_src = open('/dev/tty', 'r')
                except Exception:
                    pass

            def _read_choice():
                src = _input_src if _input_src else sys.stdin
                sys.stdout.write("Select [c/f/s]: ")
                sys.stdout.flush()
                line = src.readline()
                if not line:
                    raise EOFError
                return line.strip().lower()

            while PAUSE_REQUESTED:
                try:
                    choice = _read_choice()
                    if choice == 'c':
                        print("[*] Resuming...")
                        MONITOR_PAUSED.clear()
                        PAUSE_REQUESTED = False
                        toggle_processes(suspend=False)
                    elif choice == 'f':
                        print("[*] Draining jobs...")
                        PAUSE_REQUESTED = False
                        MONITOR_PAUSED.clear()
                        toggle_processes(suspend=False)
                        SHUTDOWN_EVENT.set()
                    elif choice == 's':
                        print("[*] Aborting...")
                        toggle_processes(suspend=False)
                        SHUTDOWN_EVENT.set()
                        kill_processes()
                        PAUSE_REQUESTED = False
                        _grace_join(threads, 8)
                        if _input_src:
                            try: _input_src.close()
                            except: pass
                        sys.exit(0)
                except KeyboardInterrupt:
                    # Second Ctrl+C while paused = force stop
                    print("\n[*] Force abort.")
                    toggle_processes(suspend=False)
                    SHUTDOWN_EVENT.set()
                    kill_processes()
                    PAUSE_REQUESTED = False
                    _grace_join(threads, 8)
                    if _input_src:
                        try: _input_src.close()
                        except: pass
                    sys.exit(0)
                except EOFError:
                    # stdin fully exhausted and /dev/tty unavailable — can't prompt
                    print("\n[!] No input available — aborting.")
                    toggle_processes(suspend=False)
                    SHUTDOWN_EVENT.set()
                    kill_processes()
                    PAUSE_REQUESTED = False
                    _grace_join(threads, 8)
                    sys.exit(0)
                except Exception:
                    time.sleep(0.5)

            if _input_src:
                try: _input_src.close()
                except: pass

    if UPDATE_AVAILABLE:
        # Before re-exec'ing into the new version, make sure every worker
        # thread has actually stopped and its ffmpeg child is dead. Otherwise
        # a sibling thread's ffmpeg (started with start_new_session=True)
        # survives the execv and keeps writing its output file while the
        # restarted worker reuses the same temp dir — a corrupt upload.
        SHUTDOWN_EVENT.set()
        for t in threads:
            t.join(timeout=60)
        kill_processes()
        time.sleep(1)  # let the OS reap terminated ffmpeg children
        apply_update(manager_url)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--manager", default=DEFAULT_MANAGER_URL)
    parser.add_argument("--username", default=DEFAULT_USERNAME)
    parser.add_argument("--workername", default=DEFAULT_WORKERNAME)
    parser.add_argument("--jobs", type=int, default=1)
    parser.add_argument("--series-id", default=None, help="Process only specific Series ID")
    parser.add_argument("--secret", default=None, help="Manually set worker secret token")
    parser.add_argument("--daily-quota", type=float, default=0, help="Daily download limit in GB (0 = unlimited)")
    parser.add_argument("--watermark", action="store_true", default=False, help="Burn the @FractumSeraph watermark into encoded video")
    parser.add_argument("--no-tui", action="store_true", default=False, help="Disable Textual TUI and use plain terminal output")
    parser.add_argument("--force-tui", action="store_true", default=False, help="Force Textual TUI even in SSH/tmux environments (may have input issues)")
    parser.add_argument("--max-size-mb", type=int, default=0, help="Skip source files larger than this size in MB (0 = no limit)")
    parser.add_argument("--ffmpeg", default=None, metavar="PATH",
                        help="Use this FFmpeg binary instead of the worker's own build (the newest "
                             "FFmpeg release, downloaded automatically on Windows and Linux). ffprobe "
                             "is taken from the same folder. It must have libsvtav1 and libopus and "
                             "be FFmpeg 7.1 or newer.")
    parser.add_argument("--local-source", default=None, metavar="DIR",
                        help="Path to the source media directory on this machine. When set and the "
                             "source file exists locally, it is read directly instead of streaming "
                             "over HTTP (useful when this worker runs on the server itself).")
    parser.add_argument("--no-chunks", action="store_true", default=False,
                        help="Opt out of chunked encoding: always take whole files instead of "
                             "time-slices of videos split across multiple workers.")
    parser.add_argument("--wallet", default=None, metavar="ADDRESS",
                        help="FractumCoin wallet address. Every verified upload is credited to "
                             "this address on the manager so encoding rewards can be paid out. "
                             "Saved to worker_config.json after first use.")
    args = parser.parse_args()
    run_worker(args)
