#!/usr/bin/env python3
"""LB Publisher server — папка готовых роликов → телефон (приложение LB Publisher для Android и iOS).

Один файл, только стандартная библиотека Python 3.9+. Любой агент (Claude Code, Kimi, Codex, скрипт)
кладёт ролик в папку очереди, приложение на телефоне забирает его, кладёт видео в галерею, подпись — в буфер
и открывает экран загрузки TikTok / Instagram Reels / YouTube. «Опубликовать» нажимает человек.

Папка очереди (по умолчанию ~/LBPublisher):

    ~/LBPublisher/
      2026-11-27_my-first-clip/      ← один ролик = одна папка (латиница, цифры, «-», «_», «.»)
        video.mp4                    ← ровно один .mp4
        post.json                    ← тексты; пишется ПОСЛЕДНИМ — по нему сервер понимает, что ролик готов
        cover.jpg                    ← необязательно: картинка в списке
        thumbnail.jpg                ← необязательно, только long: обложка для YouTube
        .published.json              ← пишет сервер: где ролик уже вышел

Запуск:   python3 lb_publisher_server.py [--dir ~/LBPublisher] [--port 8787] [--name "Мой канал"]
          Сервер сам открывает в браузере страницу с QR-кодом (http://127.0.0.1:8787/) — пакет qrcode не нужен.
          Windows: файл можно переименовать в .pyw и запускать двойным щелчком — без окна консоли.
Протокол: docs/PROTOCOL.md (API v1, тот же, что у фермы Lapsus Borz `python -m farm serve`).
"""
from __future__ import annotations

import argparse
import hashlib
import hmac
import ipaddress
import json
import os
import re
import secrets
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
import time
import webbrowser
from datetime import date, datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import unquote, urlsplit

__version__ = "1.0.0"
API_VERSION = 1
APP_ID = "lb-publisher-server"
SCHEME = "lbp"                         # строка подключения: lbp://<адрес>:<порт>#<токен>
DEFAULT_DIR = Path.home() / "LBPublisher"
DEFAULT_PORT = 8787
PLATFORMS = ("tiktok", "instagram", "youtube")
FORMAT_PLATFORMS = {"short": PLATFORMS, "long": ("youtube",)}
ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
TOKEN_RE = re.compile(r"^[A-Za-z0-9._~+/=-]{16,256}$")
URL_RE = re.compile(r"^https?://\S+$")
URL_MAX = 2000
SETTLE_S = 5.0                         # mp4 моложе — его, скорее всего, ещё пишут
CHUNK = 256 * 1024
PUBLISHED_FILE = ".published.json"
STATE_DIR = ".lbpublisher"
LIMITS = {"youtube_title": 100, "tiktok": 4000, "instagram": 2200, "youtube_description": 5000}


LANG = "en"                            # язык сообщений: en или ru (--lang, иначе по LANG системы)


def T(ru: str, en: str) -> str:
    return ru if LANG == "ru" else en


def _lang_code(val: str) -> str:
    val = val.lower()
    return "ru" if val.startswith(("ru", "russian")) else "zh" if val.startswith(("zh", "chinese")) else "en"


def detect_lang() -> str:
    """en / ru / zh: переменные окружения, на Windows — язык интерфейса системы."""
    for v in ("LBP_LANG", "LC_ALL", "LC_MESSAGES", "LANG"):
        val = os.environ.get(v, "")
        if val:
            return _lang_code(val)
    if os.name == "nt":
        try:
            import ctypes
            prim = ctypes.windll.kernel32.GetUserDefaultUILanguage() & 0x3FF   # type: ignore[attr-defined]
            return {0x19: "ru", 0x04: "zh"}.get(prim, "en")
        except Exception:  # noqa: BLE001
            pass
    return "en"


class ApiError(Exception):
    def __init__(self, status: int, message: str):
        super().__init__(message)
        self.status = status
        self.message = message


# ---------- токен ----------

def ensure_token(state: Path, renew: bool = False) -> tuple[str, bool]:
    """Токен из <папка>/.lbpublisher/token (права 600); нет или renew — новый."""
    path = state / "token"
    if path.is_file() and not renew:
        token = path.read_text(encoding="utf-8").strip()
        if TOKEN_RE.match(token):
            return token, False
    state.mkdir(parents=True, exist_ok=True)
    token = secrets.token_urlsafe(32)
    tmp = path.with_suffix(".tmp")
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        f.write(token + "\n")
    os.replace(tmp, path)
    return token, True


def token_ok(header: str | None, token: str) -> bool:
    if not header:
        return False
    scheme, _, given = header.strip().partition(" ")
    return scheme.lower() == "bearer" and hmac.compare_digest(given.strip().encode(), token.encode())


# ---------- адреса ----------

_VPN = re.compile(r"^(utun|tun|tap|ppp|ipsec|wg|gif|stf|awdl|llw|anpi|bridge|vmnet|vboxnet|docker|veth)")


def _ifaces() -> list[tuple[str, str]]:
    out: list[tuple[str, str]] = []
    for cmd in (["ifconfig"], ["ip", "-4", "-o", "addr", "show"]):
        if not shutil.which(cmd[0]):
            continue
        try:
            text = subprocess.run(cmd, capture_output=True, text=True, timeout=3).stdout
        except (OSError, subprocess.SubprocessError):
            continue
        iface = ""
        for line in text.splitlines():
            m = re.match(r"^(\d+:\s*)?([A-Za-z0-9_.@-]+):?\s", line)
            if m and not line.startswith((" ", "\t")):
                iface = m.group(2).split("@")[0]
            for ip in re.findall(r"inet (?:addr:)?(\d+\.\d+\.\d+\.\d+)", line):
                out.append((iface, ip))
        if out:
            break
    return out


def addresses() -> list[tuple[str, str]]:
    """[(IPv4, подпись)] для телефона: Wi-Fi первыми, Tailscale (100.64/10) — с пометкой."""
    found: dict[str, str] = {}
    for iface, ip in _ifaces():
        found.setdefault(ip, iface)
    try:
        for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
            found.setdefault(ip, "")
    except OSError:
        pass
    ranked = []
    for ip, iface in found.items():
        try:
            a = ipaddress.IPv4Address(ip)
        except ValueError:
            continue
        if a.is_loopback or a.is_link_local or a.is_unspecified or a.is_multicast:
            continue
        if a in ipaddress.IPv4Network("100.64.0.0/10"):
            ranked.append((5, ip, T("Tailscale / VPN — работает и вне дома", "Tailscale / VPN — works away from home")))
            continue
        vpn = bool(iface and _VPN.match(iface))
        r = 0 if a.is_private else 4
        ranked.append((r + (10 if vpn else 0), ip, T("та же Wi-Fi", "same Wi-Fi") if a.is_private and not vpn else iface))
    return [(ip, label) for _, ip, label in sorted(ranked)]


def connect_string(host: str, port: int, token: str) -> str:
    return f"{SCHEME}://{host}:{port}#{token}"


# ---------- QR-код без сторонних пакетов ----------
# Байтовый режим, уровень коррекции M, версии 1–10 (до 213 байт — строке подключения хватает с запасом).

# версия: (кодовых слов коррекции на блок, [(блоков, данных в блоке), ...]) — ISO/IEC 18004, уровень M
_QR_M = {1: (10, [(1, 16)]), 2: (16, [(1, 28)]), 3: (26, [(1, 44)]), 4: (18, [(2, 32)]), 5: (24, [(2, 43)]),
         6: (16, [(4, 27)]), 7: (18, [(4, 31)]), 8: (22, [(2, 38), (2, 39)]), 9: (22, [(3, 36), (2, 37)]),
         10: (26, [(4, 43), (1, 44)])}
_QR_ALIGN = {1: [], 2: [6, 18], 3: [6, 22], 4: [6, 26], 5: [6, 30], 6: [6, 34], 7: [6, 22, 38], 8: [6, 24, 42],
             9: [6, 26, 46], 10: [6, 28, 50]}


def _gf_tables():
    exp, log = [0] * 512, [0] * 256
    x = 1
    for i in range(255):
        exp[i], log[x] = x, i
        x <<= 1
        if x & 0x100:
            x ^= 0x11D
    for i in range(255, 512):
        exp[i] = exp[i - 255]
    return exp, log


_GF_EXP, _GF_LOG = _gf_tables()


def _rs_ecc(data: list[int], n: int) -> list[int]:
    gen = [1]
    for i in range(n):                              # ∏ (x − α^i)
        nxt = [0] * (len(gen) + 1)
        for j, g in enumerate(gen):
            nxt[j] ^= g
            if g:
                nxt[j + 1] ^= _GF_EXP[_GF_LOG[g] + i]
        gen = nxt
    rem = [0] * n
    for d in data:
        f = d ^ rem[0]
        rem = rem[1:] + [0]
        if f:
            for j in range(n):
                if gen[j + 1]:
                    rem[j] ^= _GF_EXP[_GF_LOG[gen[j + 1]] + _GF_LOG[f]]
    return rem


def _bch(value: int, poly: int, bits: int) -> int:
    v = value << bits
    top = poly.bit_length() - 1
    for i in range(v.bit_length() - 1, top - 1, -1):
        if v >> i & 1:
            v ^= poly << (i - top)
    return (value << bits) | v


def qr_matrix(text: str) -> list[list[bool]]:
    """Матрица QR-кода (True — тёмный модуль) для строки text."""
    data = text.encode("utf-8")
    for ver in range(1, 11):
        ec_n, groups = _QR_M[ver]
        cap = sum(b * d for b, d in groups)
        cnt_bits = 8 if ver < 10 else 16
        if 4 + cnt_bits + 8 * len(data) <= cap * 8:
            break
    else:
        raise ValueError("text is too long for a QR code")
    bits: list[int] = []
    put = lambda v, n: bits.extend((v >> i) & 1 for i in range(n - 1, -1, -1))  # noqa: E731
    put(0b0100, 4)
    put(len(data), cnt_bits)
    for b in data:
        put(b, 8)
    put(0, min(4, cap * 8 - len(bits)))
    put(0, -len(bits) % 8)
    words = [int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)]
    pad = 0xEC
    while len(words) < cap:
        words.append(pad)
        pad ^= 0xEC ^ 0x11
    blocks, pos = [], 0
    for count, size in groups:
        for _ in range(count):
            blocks.append(words[pos:pos + size])
            pos += size
    eccs = [_rs_ecc(b, ec_n) for b in blocks]
    stream = [b[i] for i in range(max(map(len, blocks))) for b in blocks if i < len(b)]
    stream += [e[i] for i in range(ec_n) for e in eccs]

    n = 17 + 4 * ver
    m = [[False] * n for _ in range(n)]
    fixed = [[False] * n for _ in range(n)]

    def setf(x, y, dark):
        m[y][x], fixed[y][x] = dark, True

    for cx, cy in ((3, 3), (n - 4, 3), (3, n - 4)):           # искатели + белая рамка
        for dy in range(-4, 5):
            for dx in range(-4, 5):
                x, y = cx + dx, cy + dy
                if 0 <= x < n and 0 <= y < n:
                    d = max(abs(dx), abs(dy))
                    setf(x, y, d not in (2, 4))
    for i in range(8, n - 8):                                 # синхрополосы
        setf(6, i, i % 2 == 0)
        setf(i, 6, i % 2 == 0)
    al = _QR_ALIGN[ver]
    for ay in al:
        for ax in al:
            if (ax, ay) in ((6, 6), (6, al[-1]), (al[-1], 6)):
                continue
            for dy in range(-2, 3):
                for dx in range(-2, 3):
                    setf(ax + dx, ay + dy, max(abs(dx), abs(dy)) != 1)

    def draw_format(mask):
        f = _bch((0b00 << 3) | mask, 0x537, 10) ^ 0x5412       # 00 — уровень M
        bit = lambda i: (f >> i) & 1 == 1                     # noqa: E731
        for i in range(6):
            setf(8, i, bit(i))
        setf(8, 7, bit(6))
        setf(8, 8, bit(7))
        setf(7, 8, bit(8))
        for i in range(9, 15):
            setf(14 - i, 8, bit(i))
        for i in range(8):
            setf(n - 1 - i, 8, bit(i))
        for i in range(8, 15):
            setf(8, n - 15 + i, bit(i))
        setf(8, n - 8, True)                                  # тёмный модуль

    draw_format(0)                                            # резервирует места формата
    if ver >= 7:
        v = _bch(ver, 0x1F25, 12)
        for i in range(18):
            b = (v >> i) & 1 == 1
            a, c = n - 11 + i % 3, i // 3
            setf(a, c, b)
            setf(c, a, b)

    i = 0                                                     # данные: змейкой снизу вверх по парам столбцов
    total = len(stream) * 8
    right = n - 1
    while right >= 1:
        if right == 6:
            right = 5
        for vert in range(n):
            for j in range(2):
                x = right - j
                upward = ((right + 1) & 2) == 0
                y = n - 1 - vert if upward else vert
                if not fixed[y][x] and i < total:
                    m[y][x] = (stream[i >> 3] >> (7 - (i & 7))) & 1 == 1
                    i += 1
        right -= 2

    masks = [lambda x, y: (x + y) % 2 == 0, lambda x, y: y % 2 == 0, lambda x, y: x % 3 == 0,
             lambda x, y: (x + y) % 3 == 0, lambda x, y: (x // 3 + y // 2) % 2 == 0,
             lambda x, y: x * y % 2 + x * y % 3 == 0, lambda x, y: (x * y % 2 + x * y % 3) % 2 == 0,
             lambda x, y: ((x + y) % 2 + x * y % 3) % 2 == 0]

    def masked(k):
        out = [row[:] for row in m]
        for y in range(n):
            for x in range(n):
                if not fixed[y][x] and masks[k](x, y):
                    out[y][x] = not out[y][x]
        return out

    def penalty(g):
        p = 0
        lines = g + [list(col) for col in zip(*g)]
        for line in lines:                                    # N1: 5+ подряд одного цвета
            run, prev = 0, None
            for c in line:
                if c == prev:
                    run += 1
                else:
                    if run >= 5:
                        p += run - 2
                    run, prev = 1, c
            if run >= 5:
                p += run - 2
            s = "".join("1" if c else "0" for c in line)      # N3: шаблон, похожий на искатель
            p += 40 * (len(re.findall(r"(?=10111010000)", s)) + len(re.findall(r"(?=00001011101)", s)))
        for y in range(n - 1):                                # N2: блоки 2×2
            for x in range(n - 1):
                if g[y][x] == g[y][x + 1] == g[y + 1][x] == g[y + 1][x + 1]:
                    p += 3
        dark = sum(map(sum, g))                               # N4: баланс тёмных
        p += 10 * (abs(dark * 20 - n * n * 10) // (n * n))
        return p

    best = None
    for k in range(8):
        draw_format(k)
        g = masked(k)
        sc = penalty(g)
        if best is None or sc < best[0]:
            best = (sc, k)
    draw_format(best[1])
    return masked(best[1])


def qr_svg(text: str, border: int = 3) -> str:
    g = qr_matrix(text)
    n = len(g) + 2 * border
    path = "".join(f"M{x + border} {y + border}h1v1h-1z" for y, row in enumerate(g) for x, c in enumerate(row) if c)
    return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {n} {n}" shape-rendering="crispEdges">'
            f'<rect width="{n}" height="{n}" fill="#fff"/><path d="{path}" fill="#000"/></svg>')


def qr_text(text: str) -> str:
    """QR для терминала полублоками: светлая рамка, тёмные модули — пробелы на светлом фоне не нужны."""
    g = qr_matrix(text)
    b = 2
    n = len(g)
    dark = lambda x, y: 0 <= x < n and 0 <= y < n and g[y][x]   # noqa: E731
    rows = []
    for y in range(-b, n + b, 2):
        rows.append("".join(" " if dark(x, y) and dark(x, y + 1) else "▄" if dark(x, y) else "▀" if dark(x, y + 1) else "█"
                            for x in range(-b, n + b)))
    return "\n".join(rows)


def print_qr(text: str) -> bool:
    """QR в терминале: светлые модули — символы «█▀▄», тёмные — пробел (тёмный фон терминала)."""
    try:
        print(qr_text(text))
        return True
    except (UnicodeEncodeError, ValueError, AttributeError):
        return False


# ---------- очередь ----------

def _read_json(path: Path):
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return None


def _write_atomic(path: Path, data) -> None:
    fd, tmp = tempfile.mkstemp(prefix=".tmp-", dir=path.parent)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
            f.write("\n")
        os.replace(tmp, path)
    except BaseException:
        Path(tmp).unlink(missing_ok=True)
        raise


def _str(v) -> str:
    return v.strip() if isinstance(v, str) else ""


def _tags(v) -> str:
    if isinstance(v, list):
        return ", ".join(t.strip().lstrip("#") for t in v if isinstance(t, str) and t.strip())
    return _str(v)


class Queue:
    """Ролики папки root: готовность, тексты площадок, отметки публикации."""

    def __init__(self, root: Path, name: str = "LB Publisher", today=date.today, clock=time.time):
        self.root = Path(root).expanduser()
        self.name = name
        self.today = today
        self.clock = clock
        self.lock = threading.Lock()
        self._sha: dict[str, tuple[int, float, str]] = {}

    # --- файлы ---

    def _dirs(self) -> list[Path]:
        if not self.root.is_dir():
            return []
        return [d for d in sorted(self.root.iterdir())
                if d.is_dir() and not d.is_symlink() and not d.name.startswith((".", "_"))]

    def ep_dir(self, ep_id: str) -> Path:
        if not isinstance(ep_id, str) or not ID_RE.match(ep_id) or ".." in ep_id:
            raise ApiError(400, T("неверный id ролика", "bad clip id"))
        d = self.root / ep_id
        try:
            real = d.resolve(strict=True)
        except (OSError, RuntimeError):
            raise ApiError(404, T("нет такого ролика", "no such clip")) from None
        if real.parent != self.root.resolve() or not real.is_dir():
            raise ApiError(404, T("нет такого ролика", "no such clip"))
        return real

    @staticmethod
    def _file(d: Path, name: str) -> Path | None:
        p = d / name
        if p.is_symlink() or not p.is_file():
            return None
        return p

    def sha1(self, path: Path) -> str:
        st = path.stat()
        key = str(path)
        hit = self._sha.get(key)
        if hit and hit[0] == st.st_size and hit[1] == st.st_mtime:
            return hit[2]
        h = hashlib.sha1()
        with path.open("rb") as f:
            for chunk in iter(lambda: f.read(1 << 20), b""):
                h.update(chunk)
        self._sha[key] = (st.st_size, st.st_mtime, h.hexdigest())
        return h.hexdigest()

    # --- разбор папки ролика ---

    def inspect(self, d: Path) -> tuple[list[str], dict]:
        """(почему не готов — пусто, если готов; разобранный ролик)."""
        problems: list[str] = []
        info: dict = {"id": d.name}
        if not ID_RE.match(d.name):
            return [T("имя папки — только латиница, цифры, «-», «_», «.» (до 128 символов)", "folder name: only Latin letters, digits, “-”, “_”, “.” (up to 128 characters)")], info
        mp4s = [p for p in d.iterdir() if p.suffix.lower() == ".mp4" and p.is_file() and not p.is_symlink()]
        post_path = d / "post.json"
        post = _read_json(post_path) if post_path.is_file() else None
        if not post_path.is_file():
            problems.append(T("нет post.json (агент пишет его последним, когда видео уже записано)", "no post.json (the agent writes it last, after the video)"))
        elif not isinstance(post, dict):
            problems.append(T("post.json не читается: нужен JSON-объект в UTF-8", "post.json can't be read: it must be a JSON object in UTF-8"))
        if not mp4s:
            problems.append(T("нет видео .mp4", "no .mp4 video"))
        elif len(mp4s) > 1:
            problems.append(T(f"в папке {len(mp4s)} файла .mp4 — оставь один", f"{len(mp4s)} .mp4 files in the folder — keep one"))
        elif self.clock() - mp4s[0].stat().st_mtime < SETTLE_S:
            problems.append(T("видео ещё записывается — подожди пару секунд", "the video is still being written — wait a few seconds"))
        if not isinstance(post, dict):
            return problems, info
        fmt = _str(post.get("format")).lower() or "short"
        if fmt not in FORMAT_PLATFORMS:
            problems.append(T("format — short (вертикальные Shorts/Reels/TikTok) или long (видео YouTube)", "format: short (vertical Shorts/Reels/TikTok) or long (YouTube video)"))
            fmt = "short"
        title = _str(post.get("title"))
        if not title:
            problems.append(T("в post.json нет title — название ролика", "post.json has no title"))
        pd = _str(post.get("publish_date"))
        if pd:
            try:
                date.fromisoformat(pd)
            except ValueError:
                problems.append(T("publish_date — дата ГГГГ-ММ-ДД", "publish_date must be YYYY-MM-DD"))
                pd = ""
        allowed = FORMAT_PLATFORMS[fmt]
        plats = post.get("platforms")
        if plats is None:
            plats = list(allowed)
        if not isinstance(plats, list) or not plats or any(p not in allowed for p in plats):
            problems.append(T(f"platforms — список из: {', '.join(allowed)}", f"platforms: a list of {', '.join(allowed)}"))
            plats = list(allowed)
        plats = [p for p in PLATFORMS if p in plats]

        tx = post.get("texts") if isinstance(post.get("texts"), dict) else {}
        def sub(p):
            return tx.get(p) if isinstance(tx.get(p), dict) else {}
        caption = _str(post.get("caption"))
        yt = sub("youtube")
        texts = {
            "youtube": {
                "title": _str(yt.get("title")) or title,
                "description": _str(yt.get("description")) or _str(post.get("description")) or caption,
                "tags": _tags(yt.get("tags") if yt.get("tags") is not None else post.get("tags")),
                "shorts_title": _str(yt.get("shorts_title")),
            },
            "tiktok": {"caption": _str(sub("tiktok").get("caption")) or caption or title},
            "instagram": {"caption": _str(sub("instagram").get("caption")) or caption or title},
        }
        warnings = []
        if len(texts["youtube"]["title"]) > LIMITS["youtube_title"]:
            warnings.append(T(f"название YouTube длиннее {LIMITS['youtube_title']} символов — YouTube его обрежет", f"YouTube title is longer than {LIMITS['youtube_title']} characters — YouTube will cut it"))
        for p in ("tiktok", "instagram"):
            if p in plats and len(texts[p]["caption"]) > LIMITS[p]:
                warnings.append(T(f"подпись {p} длиннее {LIMITS[p]} символов", f"{p} caption is longer than {LIMITS[p]} characters"))
        info.update(post=post, format=fmt, title=title, publish_date=pd, platforms=plats, texts=texts,
                    warnings=warnings, pinned_comment=_str(post.get("pinned_comment")),
                    ai_label=post.get("ai_label") if isinstance(post.get("ai_label"), bool) else True,
                    rubric=_str(post.get("label")) or None,
                    duration=post.get("duration") if isinstance(post.get("duration"), (int, float)) else None)
        if mp4s and not problems:
            info["video"] = mp4s[0]
            info["size"] = mp4s[0].stat().st_size
        return problems, info

    def published(self, d: Path, plats) -> dict:
        data = _read_json(d / PUBLISHED_FILE)
        data = data if isinstance(data, dict) else {}
        out = {}
        for p in plats:
            rec = data.get(p) if isinstance(data.get(p), dict) else {}
            done = bool(rec.get("published"))
            out[p] = {"done": done, "url": rec.get("url") if done else None, "at": rec.get("at") if done else None}
        return out

    def _date_warnings(self, pd: str) -> list[str]:
        if not pd:
            return []
        d, today = date.fromisoformat(pd), self.today()
        if d < today:
            return [T(f"дата публикации {pd} уже прошла", f"publish date {pd} has passed")]
        if d > today:
            return [T(f"дата публикации — {pd}, ещё не сегодня", f"publish date is {pd}, not today")]
        return []

    def item(self, d: Path, info: dict) -> dict:
        ep_id = d.name
        pub = self.published(d, info["platforms"])
        all_done = all(v["done"] for v in pub.values())
        return {
            "id": ep_id,
            "episode_id": ep_id,
            "format": info["format"],
            "platforms": info["platforms"],
            "rubric": info["rubric"],
            "hook_title": info["title"],
            "topic": "",
            "publish_date": info["publish_date"],
            "duration": info["duration"],
            "size": info["size"],
            "video_sha1": self.sha1(info["video"]),
            "video_url": f"/api/episodes/{ep_id}/video",
            "cover_url": f"/api/episodes/{ep_id}/cover" if self._file(d, "cover.jpg") else None,
            "thumbnail_url": (f"/api/episodes/{ep_id}/thumbnail"
                              if info["format"] == "long" and self._file(d, "thumbnail.jpg") else None),
            "published": pub,
            "all_published": all_done,
            "ai_label": info["ai_label"],
            "cta_ok": True,
            "warnings": [] if all_done else info["warnings"] + self._date_warnings(info["publish_date"]),
        }

    def queue(self) -> dict:
        ready, not_ready = [], []
        for d in self._dirs():
            problems, info = self.inspect(d)
            if problems:
                not_ready.append({"id": d.name, "hook_title": info.get("title", ""),
                                  "publish_date": info.get("publish_date", ""), "format": info.get("format", "short"),
                                  "problems": problems})
            else:
                ready.append(self.item(d, info))
        key = lambda x: (x["publish_date"] or "9999", x["id"])  # noqa: E731 — без даты — в конце
        ready.sort(key=key)
        not_ready.sort(key=lambda x: x["id"])
        return {"today": self.today().isoformat(), "platforms": list(PLATFORMS), "episodes": ready,
                "not_ready": not_ready}

    def ready(self, ep_id: str) -> tuple[Path, dict]:
        d = self.ep_dir(ep_id)
        problems, info = self.inspect(d)
        if problems:
            raise ApiError(409, T("ролик не готов: ", "clip not ready: ") + "; ".join(problems))
        return d, info

    def episode(self, ep_id: str) -> dict:
        d, info = self.ready(ep_id)
        out = self.item(d, info)
        t = info["texts"]
        yt = t["youtube"]
        youtube = {"title": yt["title"], "description": yt["description"], "tags": yt["tags"],
                   "clipboard": yt["title"] if info["format"] == "long"
                   else (yt["shorts_title"] or yt["title"])[:LIMITS["youtube_title"]]}
        out["texts"] = {"youtube": youtube, "pinned_comment": info["pinned_comment"]}
        if info["format"] == "short":
            for p in ("tiktok", "instagram"):
                out["texts"][p] = {"caption": t[p]["caption"], "clipboard": t[p]["caption"]}
        out["visible"] = {}
        out["seo_warnings"] = []
        return out

    def media(self, ep_id: str, kind: str) -> tuple[Path, str, str | None]:
        d, info = self.ready(ep_id)
        if kind == "video":
            return info["video"], "video/mp4", f'"{self.sha1(info["video"])}"'
        name = "thumbnail.jpg" if kind == "thumbnail" else "cover.jpg"
        p = self._file(d, name)
        if p is None:
            raise ApiError(404, T(f"нет {name}", f"no {name}"))
        return p, "image/jpeg", f'"{self.sha1(p)}"'

    def mark(self, ep_id: str, body) -> dict:
        if not isinstance(body, dict):
            raise ApiError(400, T("ожидается JSON-объект {\"platform\": …}", "expected a JSON object {\"platform\": …}"))
        platform = body.get("platform")
        if platform not in PLATFORMS:
            raise ApiError(400, T(f"platform — одно из: {', '.join(PLATFORMS)}", f"platform must be one of: {', '.join(PLATFORMS)}"))
        flag = body.get("published", True)
        if not isinstance(flag, bool):
            raise ApiError(400, T("published — true или false", "published must be true or false"))
        url = body.get("url")
        if url is not None:
            if not isinstance(url, str):
                raise ApiError(400, T("url — строка", "url must be a string"))
            url = url.strip() or None
            if url and (not URL_RE.match(url) or len(url) > URL_MAX):
                raise ApiError(400, T(f"url — ссылка http(s) до {URL_MAX} символов", f"url must be an http(s) link up to {URL_MAX} characters"))
        d = self.ep_dir(ep_id)
        problems, info = self.inspect(d)
        plats = info.get("platforms") or list(PLATFORMS)
        if platform not in plats:
            raise ApiError(400, T(f"этот ролик публикуется только на: {', '.join(plats)}", f"this clip is only for: {', '.join(plats)}"))
        with self.lock:
            path = d / PUBLISHED_FILE
            data = _read_json(path)
            data = data if isinstance(data, dict) else {}
            if flag:
                prev = data.get(platform) if isinstance(data.get(platform), dict) else {}
                data[platform] = {"published": True,
                                  "at": prev.get("at") or datetime.now().astimezone().isoformat(timespec="seconds"),
                                  "url": url or prev.get("url")}
            else:
                data.pop(platform, None)
            _write_atomic(path, data)
            state = self.published(d, plats)
        return {"ok": True, "id": ep_id, "published": state, "all_published": all(v["done"] for v in state.values())}


# ---------- HTTP ----------

def parse_range(header: str, size: int):
    m = re.fullmatch(r"\s*bytes\s*=\s*(\d{0,18})\s*-\s*(\d{0,18})\s*", header or "")
    if not m or (not m.group(1) and not m.group(2)):
        return "full"
    a, b = m.group(1), m.group(2)
    if not a:
        n = int(b)
        if n == 0 or size == 0:
            return None
        return max(0, size - n), size - 1
    start = int(a)
    end = int(b) if b else size - 1
    if b and end < start:
        return "full"
    if start >= size:
        return None
    return start, min(end, size - 1)


# ---------- страница с QR-кодом на этом компьютере ----------

PAGE_TEXT = {
    "en": dict(title="LB Publisher server", running="Running", scan="In the LB Publisher app on your phone: <b>Connection → Scan QR code</b>.",
               paste="Or copy the connection string and paste it in the app:", copy="Copy", copied="Copied",
               other="Other addresses", folder="Queue folder", open="Open", clips="Clips ready in the queue: {n}",
               phone_on="Phone connected", phone_off="Phone has not connected yet",
               net="Phone and computer: same Wi-Fi — or both in Tailscale to post from anywhere.",
               bg="The server keeps running after you close this tab. To stop it, press “Stop server”.",
               stop="Stop server", stopped="Server stopped. You can close this tab.", guide="Video guide"),
    "ru": dict(title="Сервер LB Publisher", running="Работает", scan="В приложении LB Publisher на телефоне: <b>«Подключение» → «Сканировать QR-код»</b>.",
               paste="Или скопируй строку подключения и вставь её в приложении:", copy="Скопировать", copied="Скопировано",
               other="Другие адреса", folder="Папка очереди", open="Открыть", clips="Готовых роликов в очереди: {n}",
               phone_on="Телефон подключён", phone_off="Телефон ещё не подключался",
               net="Телефон и компьютер — в одной Wi-Fi, или оба в Tailscale, чтобы публиковать откуда угодно.",
               bg="Сервер работает и после закрытия вкладки. Чтобы остановить — «Остановить сервер».",
               stop="Остановить сервер", stopped="Сервер остановлен. Вкладку можно закрыть.", guide="Видеоинструкция"),
    "zh": dict(title="LB Publisher 服务器", running="运行中", scan="在手机上的 LB Publisher 中：<b>连接 → 扫描二维码</b>。",
               paste="或复制连接字符串，粘贴到 App 中：", copy="复制", copied="已复制",
               other="其他地址", folder="队列文件夹", open="打开", clips="队列中可发布的视频：{n}",
               phone_on="手机已连接", phone_off="手机尚未连接",
               net="手机和电脑连接同一 Wi-Fi，或都使用 Tailscale，随时随地发布。",
               bg="关闭此页面后服务器仍在运行。要停止，请点击“停止服务器”。",
               stop="停止服务器", stopped="服务器已停止，可以关闭此页面。", guide="视频教程"),
}

PAGE_HTML = """<!doctype html><html lang="{lang}"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><title>{title}</title>
<style>
:root {{ color-scheme: light dark; --bg:#f5f5f7; --card:#fff; --ink:#1d1d1f; --dim:#6e6e73; --line:#d2d2d7; --pink:#ff2e88; }}
@media (prefers-color-scheme: dark) {{ :root {{ --bg:#000; --card:#1c1c1e; --ink:#f5f5f7; --dim:#a1a1a6; --line:#38383a; }} }}
* {{ box-sizing: border-box; }}
body {{ margin:0; background:var(--bg); color:var(--ink); font:17px/1.47 -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif; }}
main {{ max-width:760px; margin:0 auto; padding:40px 20px 60px; }}
h1 {{ font-size:34px; margin:0 0 6px; letter-spacing:-.02em; }}
.st {{ color:#30d158; font-weight:600; }} .st::before {{ content:"●"; margin-right:6px; }}
.card {{ background:var(--card); border-radius:20px; padding:26px; margin-top:20px; }}
.qr {{ display:flex; gap:28px; align-items:center; flex-wrap:wrap; }}
.qr .code {{ width:min(260px, 100%); aspect-ratio:1; flex:none; border-radius:14px; overflow:hidden; }}
.qr .code svg {{ width:100%; height:100%; display:block; }}
.qr p {{ margin:0 0 12px; }}
.line {{ display:flex; gap:8px; margin-top:6px; }}
code {{ font:14px/1.4 ui-monospace, Menlo, Consolas, monospace; background:rgba(127,127,127,.14); border-radius:8px; padding:9px 11px; flex:1; overflow-wrap:anywhere; }}
button {{ font:inherit; font-size:15px; border:0; border-radius:10px; padding:9px 16px; cursor:pointer; background:rgba(127,127,127,.18); color:inherit; }}
button.p {{ background:var(--pink); color:#fff; font-weight:600; }}
.dim {{ color:var(--dim); font-size:15px; }}
.row {{ display:flex; justify-content:space-between; gap:12px; align-items:center; padding:10px 0; border-top:1px solid var(--line); }}
.row:first-child {{ border-top:0; padding-top:0; }}
a {{ color:var(--pink); text-decoration:none; }}
</style></head><body><main>
<h1>{title}</h1><p><span class="st">{running}</span> · <span id="phone" class="dim">{phone}</span></p>
<section class="card qr"><div class="code">{svg}</div><div style="flex:1;min-width:min(240px, 100%)">
<p>{scan}</p><p class="dim">{paste}</p><div class="line"><code id="cs">{line}</code><button onclick="cp()" id="cpb">{copy}</button></div>
<p class="dim" style="margin-top:14px">{net}</p></div></section>
{others}
<section class="card"><div class="row"><div><div>{folder}</div><div class="dim">{root}</div></div><button onclick="post('/local/open-folder')">{open}</button></div>
<div class="row"><div id="clips">{clips}</div><a href="https://lapsusborz.net{site}/video" target="_blank" rel="noopener">{guide} ›</a></div></section>
<p class="dim" style="margin-top:22px">{bg}</p><p><button onclick="stop()">{stop}</button></p>
</main><script>
function cp(){{ navigator.clipboard.writeText(document.getElementById('cs').textContent).then(function(){{ document.getElementById('cpb').textContent={copied!r}; }}); }}
function post(u){{ return fetch(u, {{method:'POST'}}); }}
function stop(){{ post('/local/stop').then(function(){{ document.querySelector('main').innerHTML='<h1>'+{stopped!r}+'</h1>'; }}); }}
setInterval(function(){{ fetch('/local/status').then(function(r){{return r.json()}}).then(function(d){{
  document.getElementById('clips').textContent=d.clips; document.getElementById('phone').textContent=d.phone; }}).catch(function(){{}}); }}, 4000);
</script></body></html>"""


class Handler(BaseHTTPRequestHandler):
    server_version = f"LBPublisher/{__version__}"
    protocol_version = "HTTP/1.1"
    queue: Queue
    token: str
    quiet = False
    local: dict | None = None          # данные для страницы на 127.0.0.1: строки подключения, папка, порт
    last_phone = 0.0                   # когда телефон последний раз заходил с верным токеном

    def log_message(self, fmt, *args):
        if not self.quiet:
            sys.stderr.write("%s %s\n" % (self.address_string(), fmt % args))

    def _send(self, status: int, body: bytes, ctype: str, extra: dict | None = None) -> None:
        self.send_response(status)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        for k, v in (extra or {}).items():
            self.send_header(k, v)
        self.end_headers()
        if self.command != "HEAD":
            self.wfile.write(body)

    def _json(self, status: int, data) -> None:
        self._send(status, json.dumps(data, ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8")

    def _error(self, status: int, message: str, extra: dict | None = None) -> None:
        if not self._body_read and self.command == "POST":
            self.close_connection = True       # тело не прочитано — соединение дальше не годится
        self._send(status, json.dumps({"ok": False, "error": message}, ensure_ascii=False).encode("utf-8"),
                   "application/json; charset=utf-8", extra)

    def _body(self):
        self._body_read = True
        try:
            n = int(self.headers.get("Content-Length") or 0)
        except ValueError:
            raise ApiError(400, T("неверный Content-Length", "bad Content-Length")) from None
        if n <= 0 or n > 64 * 1024:
            raise ApiError(400, T("нужно JSON-тело до 64 КБ", "a JSON body up to 64 KB is required"))
        try:
            return json.loads(self.rfile.read(n).decode("utf-8"))
        except (UnicodeDecodeError, ValueError):
            raise ApiError(400, T("тело — не JSON", "the body is not JSON")) from None

    def _file(self, path: Path, ctype: str, etag: str | None) -> None:
        size = path.stat().st_size
        start, end, status = 0, size - 1, 200
        rng, if_range = self.headers.get("Range"), self.headers.get("If-Range")
        if rng and (not if_range or (etag and if_range.strip() == etag)):
            r = parse_range(rng, size)
            if r is None:
                self._error(416, T("диапазон за пределами файла", "range outside the file"), {"Content-Range": f"bytes */{size}"})
                return
            if r != "full":
                start, end = r
                status = 206
        length = max(0, end - start + 1)
        self.send_response(status)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(length))
        self.send_header("Accept-Ranges", "bytes")
        self.send_header("Cache-Control", "private, no-cache")
        if etag:
            self.send_header("ETag", etag)
        if status == 206:
            self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
        self.end_headers()
        if self.command == "HEAD" or length == 0:
            return
        with path.open("rb") as f:
            f.seek(start)
            left = length
            while left > 0:
                chunk = f.read(min(CHUNK, left))
                if not chunk:
                    break
                self.wfile.write(chunk)
                left -= len(chunk)

    # ── страница с QR-кодом: только с этого компьютера и только по адресу localhost (защита от DNS rebinding) ──
    def _is_local(self) -> bool:
        if self.local is None:
            return False
        ip = self.client_address[0]
        if ip not in ("127.0.0.1", "::1", "::ffff:127.0.0.1"):
            return False
        host = (self.headers.get("Host") or "").lower()
        port = self.local["port"]
        if host not in (f"127.0.0.1:{port}", f"localhost:{port}", f"[::1]:{port}"):
            return False
        origin = self.headers.get("Origin")
        return self.command in ("GET", "HEAD") or origin is None or origin.lower() in (f"http://127.0.0.1:{port}", f"http://localhost:{port}")

    def _local_status(self) -> dict:
        tx = PAGE_TEXT.get(LANG, PAGE_TEXT["en"])
        try:
            n = len(self.queue.queue().get("episodes", []))
        except Exception:  # noqa: BLE001
            n = 0
        on = time.time() - Handler.last_phone < 600
        return {"clips": tx["clips"].format(n=n), "phone": tx["phone_on"] if on else tx["phone_off"]}

    def _local_page(self) -> None:
        tx = PAGE_TEXT.get(LANG, PAGE_TEXT["en"])
        esc = lambda v: str(v).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")   # noqa: E731
        lines = self.local["lines"]
        others = ""
        if len(lines) > 1:
            rows = "".join(f'<div class="row"><code>{esc(l)}</code><span class="dim">{esc(lab)}</span></div>' for l, lab in lines[1:])
            others = f'<section class="card"><div class="dim" style="margin-bottom:10px">{tx["other"]}</div>{rows}</section>'
        st = self._local_status()
        page = PAGE_HTML.format(lang=LANG, svg=qr_svg(lines[0][0]), line=esc(lines[0][0]), root=esc(self.local["root"]),
                                others=others, phone=st["phone"], clips=st["clips"],
                                site={"ru": "/ru", "zh": "/zh"}.get(LANG, ""), **{k: v for k, v in tx.items() if k not in ("clips",)})
        self._send(200, page.encode("utf-8"), "text/html; charset=utf-8")

    def _handle_local(self, method: str, path: str) -> bool:
        if path not in ("/", "/qr", "/local/status", "/local/stop", "/local/open-folder"):
            return False
        if not self._is_local():
            self._error(403, T("страница доступна только на этом компьютере", "this page is only available on this computer"))
            return True
        if method in ("GET", "HEAD") and path in ("/", "/qr"):
            self._local_page()
        elif method == "GET" and path == "/local/status":
            self._json(200, self._local_status())
        elif method == "POST" and path == "/local/open-folder":
            open_folder(self.local["root"])
            self._json(200, {"ok": True})
        elif method == "POST" and path == "/local/stop":
            self._json(200, {"ok": True})
            threading.Thread(target=self.server.shutdown, daemon=True).start()
        else:
            self._error(405, T("метод не поддерживается", "method not allowed"))
        return True

    def _handle(self, method: str) -> None:
        self._body_read = False
        try:
            if self._handle_local(method, urlsplit(self.path).path):
                return
            if not token_ok(self.headers.get("Authorization"), self.token):
                self._error(401, T("нужен токен: заголовок Authorization: Bearer <токен> из строки подключения", "token required: Authorization: Bearer <token> from the connection string"),
                            {"WWW-Authenticate": 'Bearer realm="lb-publisher"'})
                return
            Handler.last_phone = time.time()
            segs = [unquote(s) for s in urlsplit(self.path).path.split("/") if s]
            if any(s in (".", "..") or "/" in s or "\\" in s or "\x00" in s for s in segs):
                raise ApiError(400, T("неверный путь", "bad path"))
            if segs[:1] != ["api"]:
                raise ApiError(404, T("нет такого адреса", "no such endpoint"))
            rest = segs[1:]
            q = self.queue
            get = method in ("GET", "HEAD")
            if rest == ["ping"] and get:
                self._json(200, {"ok": True, "app": APP_ID, "version": __version__, "api": API_VERSION,
                                 "name": q.name, "today": q.today().isoformat(),
                                 "time": datetime.now().astimezone().isoformat(timespec="seconds")})
                return
            if rest == ["queue"] and get:
                self._json(200, q.queue())
                return
            if len(rest) >= 2 and rest[0] == "episodes":
                ep_id, tail = rest[1], rest[2:]
                if not tail and get:
                    self._json(200, q.episode(ep_id))
                    return
                if tail in (["video"], ["cover"], ["thumbnail"]) and get:
                    self._file(*q.media(ep_id, tail[0]))
                    return
                if tail == ["published"] and method == "POST":
                    self._json(200, q.mark(ep_id, self._body()))
                    return
                if not tail or tail in (["video"], ["cover"], ["thumbnail"], ["published"]):
                    raise ApiError(405, T("метод не поддерживается", "method not allowed"))
            raise ApiError(404, T("нет такого адреса", "no such endpoint"))
        except ApiError as e:
            self._error(e.status, e.message)
        except (BrokenPipeError, ConnectionResetError):
            pass
        except Exception:  # noqa: BLE001 — один запрос не роняет сервер
            if os.environ.get("LBP_DEBUG"):
                import traceback
                traceback.print_exc()
            self._error(500, T("внутренняя ошибка сервера", "internal server error"))

    def do_GET(self):
        self._handle("GET")

    def do_HEAD(self):
        self._handle("HEAD")

    def do_POST(self):
        self._handle("POST")

    def do_PUT(self):
        self._handle("PUT")

    def do_DELETE(self):
        self._handle("DELETE")


def make_server(queue: Queue, token: str, host: str = "0.0.0.0", port: int = DEFAULT_PORT,
                quiet: bool = False, local: dict | None = None) -> ThreadingHTTPServer:
    handler = type("BoundHandler", (Handler,), {"queue": queue, "token": token, "quiet": quiet, "local": local})
    srv = ThreadingHTTPServer((host, port), handler)
    srv.daemon_threads = True
    return srv


# ---------- пример ролика ----------

EXAMPLE_POST = {
    "title": "My first clip",
    "format": "short",
    "publish_date": "",
    "caption": "Short caption for TikTok and Reels #example",
    "description": "Description for YouTube",
    "tags": ["example", "lb publisher"],
    "pinned_comment": "What do you think? Tell me in the comments 👇",
    "ai_label": True,
}


def open_folder(path) -> None:
    try:
        if os.name == "nt":
            os.startfile(str(path))  # type: ignore[attr-defined]
        elif sys.platform == "darwin":
            subprocess.Popen(["open", str(path)])
        else:
            subprocess.Popen(["xdg-open", str(path)])
    except OSError:
        pass


def local_url(port: int) -> str:
    return f"http://127.0.0.1:{port}/"


def already_running(port: int) -> bool:
    """На порту уже наш сервер? (проверка без токена: /api/ping отвечает 401 с нашим realm)."""
    import http.client
    try:
        c = http.client.HTTPConnection("127.0.0.1", port, timeout=1.5)
        c.request("GET", "/api/ping")
        r = c.getresponse()
        return r.status == 401 and "lb-publisher" in (r.getheader("WWW-Authenticate") or "")
    except OSError:
        return False


def init_dir(root: Path) -> None:
    root.mkdir(parents=True, exist_ok=True)
    readme = root / "README.txt"
    if not readme.exists():
        readme.write_text(
            "LB Publisher queue folder. One clip = one folder: video.mp4 + post.json (+ cover.jpg).\n"
            "Write post.json last. Field example: post.example.json. Protocol: docs/PROTOCOL.md.\n"
            "Папка очереди LB Publisher. Один ролик = одна папка: video.mp4 + post.json (+ cover.jpg).\n"
            "post.json кладётся последним. Пример полей — post.example.json.\n",
            encoding="utf-8")
    ex = root / "post.example.json"
    if not ex.exists():
        ex.write_text(json.dumps(EXAMPLE_POST, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


# ---------- CLI ----------

def main(argv=None) -> int:
    ap = argparse.ArgumentParser(prog="lb_publisher_server.py", description="LB Publisher: clips folder → phone")
    ap.add_argument("--dir", default=os.environ.get("LBP_DIR", str(DEFAULT_DIR)), help="папка очереди")
    ap.add_argument("--host", default="0.0.0.0", help="адрес прослушивания (по умолчанию все)")
    ap.add_argument("--port", type=int, default=int(os.environ.get("LBP_PORT", DEFAULT_PORT)))
    ap.add_argument("--name", default=os.environ.get("LBP_NAME", "LB Publisher"), help="имя в приложении")
    ap.add_argument("--new-token", action="store_true", help="выдать новый токен (старые телефоны отключатся)")
    ap.add_argument("--print-connect", action="store_true", help="только напечатать строку подключения и выйти")
    ap.add_argument("--quiet", action="store_true", help="не печатать каждый запрос")
    ap.add_argument("--lang", choices=["en", "ru", "zh"], help="язык сообщений (по умолчанию — язык системы)")
    ap.add_argument("--no-browser", action="store_true", help="не открывать страницу с QR-кодом в браузере")
    ap.add_argument("--version", action="version", version=__version__)
    a = ap.parse_args(argv)
    global LANG
    LANG = a.lang or detect_lang()

    root = Path(a.dir).expanduser()
    init_dir(root)
    token, _ = ensure_token(root / STATE_DIR, renew=a.new_token)
    if sys.stdout is None or sys.stderr is None:        # pythonw / .pyw: консоли нет — пишем в журнал
        log = open(root / STATE_DIR / "server.log", "a", encoding="utf-8", buffering=1)
        sys.stdout = sys.stdout or log
        sys.stderr = sys.stderr or log
    addrs = addresses()
    best = addrs[0][0] if addrs else "127.0.0.1"
    line = connect_string(best, a.port, token)
    if a.print_connect:
        print(line)
        return 0
    lines = [(connect_string(ip, a.port, token), label) for ip, label in addrs] or [(line, "")]
    local = {"port": a.port, "root": str(root), "lines": lines}
    try:
        srv = make_server(Queue(root, a.name), token, a.host, a.port, quiet=a.quiet, local=local)
    except OSError as e:
        if already_running(a.port):                     # второй запуск (двойной щелчок ещё раз) — показать первый
            print(T("Сервер уже запущен — открываю его страницу.", "The server is already running — opening its page."))
            if not a.no_browser:
                webbrowser.open(local_url(a.port))
            return 0
        print(T(f"Порт {a.port} занят или недоступен ({e}). Попробуй --port {a.port + 1}",
                f"Port {a.port} is busy or unavailable ({e}). Try --port {a.port + 1}"), file=sys.stderr)
        return 2
    print(f"LB Publisher {__version__} · " + T("папка очереди", "queue folder") + f": {root}")
    print(T("Строка подключения для приложения (Подключение → QR или Вставить):\n",
            "Connection string for the app (Connection → scan QR or Paste):\n"))
    print("   " + line + "\n")
    print_qr(line)
    print("\n   " + T("QR-код и строка подключения — на странице", "QR code and connection string — on the page") + f": {local_url(a.port)}")
    for ip, label in addrs[1:]:
        print("   " + T("другой адрес", "other address") + f" ({label}): {connect_string(ip, a.port, token)}")
    print(T("\nТелефон и компьютер — в одной Wi-Fi или оба в Tailscale. Ctrl+C — остановить.",
            "\nPhone and computer: same Wi-Fi, or both in Tailscale. Ctrl+C to stop."))
    if not a.no_browser:
        threading.Timer(0.6, webbrowser.open, [local_url(a.port)]).start()
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        srv.server_close()
    return 0


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