"""Flovix eye: an independent observer on a laptop (Windows, macOS), a Raspberry Pi 5 or any Linux.

An eye is your own node of a coin plus this small agent next to it. No third-party explorers:
the node gets blocks from the network and checks every one of them by the network's rules.
Every 15 seconds the agent tells the Flovix server what the node sees. For Bitcoin it attaches
the raw block headers, so the server checks the hashes and the proof-of-work itself and a fake
report is useless. The Flovix watcher compares all eyes and decides whether there is a threat.

The node is never opened to the internet and no router ports are needed.

Several eyes (on one computer, one address or of one owner) should look at different parts of
the network. The server tells each eye which of its node's neighbours another such eye already
uses; the agent then drops one of them now and then (at most once in 10 minutes) and the node
picks a different one by itself. Turn it off with "spread off".

    python flovix_eye.py setup KEY     set up: your eye key and your node
                                       (Bitcoin Core is downloaded and checked for you)
    python flovix_eye.py               run (or start the setup if there are no settings yet)
    python flovix_eye.py status        what the eye sees now
    python flovix_eye.py once          one report and exit
    python flovix_eye.py autostart     start with the computer (autostart off: stop doing that)
    python flovix_eye.py stop          stop the eye that runs in the background
    python flovix_eye.py spread off    keep the node's neighbours as they are (spread on: default)

    python flovix_eye.py connect --key KEY --rpc URL [--cookie FILE] [--network NAME]
                                       connect a running node without questions (used by testnet.py)

Options: --server URL (default https://flovixclude.com), --lang en|ru,
         --dir FOLDER (keep settings in this folder: a second eye on the same computer).
Needs only Python 3.8 or newer, no extra packages.
"""
import base64
import hashlib
import json
import os
import platform
import re
import shutil
import socket
import struct
import subprocess
import sys
import tarfile
import time
import urllib.error
import urllib.request
import zipfile
from datetime import datetime, timezone
from pathlib import Path

VERSION = "flovix-eye/1.12"
DEFAULT_SERVER = "https://flovixclude.com"
# Первый блок Bitcoin: пункты 1 и 2 мастера ставят Bitcoin Core только для настоящего Bitcoin
BTC_GENESIS = {"main": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
               "testnet4": "00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043"}
PY = "python" if os.name == "nt" else "python3"   # как запускать Python в подсказках
WINDOWS = platform.system() == "Windows"
MACOS = platform.system() == "Darwin"
SCRIPT = Path(__file__).resolve()
HERE = SCRIPT.parent
MAX_HEADERS = 150          # сколько заголовков отправлять, если сервер ещё ничего не знает
PLAN_EVERY = 600           # как часто переспрашивать сервер, какие сети смотреть
REPORT_GAP = 5             # новый блок — отчёт сразу, но не чаще раза в 5 секунд
REPORT_LIMIT = 400_000     # байт: сервер принимает отчёт до 512 КБ (много сетей сразу после запуска)
SPREAD_GAP = 600           # меняем соседа ноды не чаще раза в 10 минут
SPREAD_PER_DAY = 24        # и не больше 24 раз в сутки: в маленькой сети соседей на всех может не хватить
SPREAD_MIN_OUT = 6         # у ноды должно остаться достаточно исходящих соседей
MEMPOOL_EVERY = 120        # очередь транзакций смотрим раз в 2 минуты (для проверки на цензуру)
MEMPOOL_MAX = 20000        # очередь больше — подробно не разбираем, только размер
STUCK_AGE = 60             # транзакция в очереди дольше минуты — кандидат «держат специально»
BLOCKSTATS_LAST = 6        # по скольким новым блокам присылать, сколько платили дешёвые транзакции

# Bitcoin Core, который мастер скачивает сам с bitcoincore.org. Отпечатки взяты из
# воспроизводимых сборок (github.com/bitcoin-core/guix.sigs, 31.1): у всех 16 сборщиков совпали.
CORE_VERSION = "31.1"
CORE_URL = "https://bitcoincore.org/bin/bitcoin-core-{v}/{file}"
CORE_FILES = {
    "windows-x86_64": ("bitcoin-31.1-win64.zip", "c99ef173471c58e6766d9eebd12e6c35349082eeed3939bc99eed58ef57db587"),
    "linux-x86_64": ("bitcoin-31.1-x86_64-linux-gnu.tar.gz", "b80d9c3e04da78fb6f0569685673418cf686fadba9042d926d13fb87ff503f9e"),
    "linux-aarch64": ("bitcoin-31.1-aarch64-linux-gnu.tar.gz", "dcf1873f2208ba4f962f3398d47e154c39c0084be8f4553e05c940d0ace3d004"),
    "linux-armhf": ("bitcoin-31.1-arm-linux-gnueabihf.tar.gz", "66b2b45359efa161031a49898f96aa7cf1455db46ca6102acd16a7197dc3b96f"),
    "darwin-arm64": ("bitcoin-31.1-arm64-apple-darwin.tar.gz", "16a097c09fbd7eb78b240ce1dae123663ea2e5e377cfd6a951e71e227e23cf2f"),
    "darwin-x86_64": ("bitcoin-31.1-x86_64-apple-darwin.tar.gz", "bc506958d0f387c1ea770bdc7c7192a505fa645ff62cabcc7761fa7eb89e867e"),
}
CORE_MIN = 28               # testnet4 появилась в Bitcoin Core 28

BITCOIN_NETS = {
    # сеть: (строка bitcoin.conf, порт RPC, подпапка с .cookie, prune в МБ, нужно места в ГБ)
    "testnet4": ("testnet4=1", 48332, "testnet4", 2000, 4),
    "main": ("", 8332, "", 10000, 25),
}


def _home():
    """Домашняя папка того, кто запускает (под sudo — того, кто вызвал sudo)."""
    user = os.environ.get("SUDO_USER")
    if user and not WINDOWS:
        return Path(os.path.expanduser("~" + user))
    return Path.home()


# Где живёт глаз. Если настройки лежат рядом с файлом (так было до 1.4) — там и остаёмся.
APP_DIR = _home() / ("FlovixEye" if WINDOWS or MACOS else "flovix-eye")
DIR = HERE if (HERE / "flovix-eye.json").exists() else APP_DIR
CONFIG = DIR / "flovix-eye.json"
STATUS = DIR / "flovix-eye.status.json"
LOG = DIR / "flovix-eye.log"
LOCK = DIR / "flovix-eye.lock"
STOP = DIR / "flovix-eye.stop"


def set_dir(folder):
    """--dir: настройки, журнал и замок в этой папке (второй глаз на том же компьютере)."""
    global DIR, CONFIG, STATUS, LOG, LOCK, STOP
    DIR = Path(folder).expanduser().resolve()
    CONFIG, STATUS, LOG = DIR / "flovix-eye.json", DIR / "flovix-eye.status.json", DIR / "flovix-eye.log"
    LOCK, STOP = DIR / "flovix-eye.lock", DIR / "flovix-eye.stop"


# ---------- язык ----------

def _detect_lang():
    for value in (os.environ.get("FLOVIX_LANG"),):
        if value:
            return "ru" if value.lower().startswith("ru") else "en"
    if WINDOWS:
        try:
            import ctypes
            return "ru" if ctypes.windll.kernel32.GetUserDefaultUILanguage() & 0x3FF == 0x19 else "en"
        except Exception:
            return "en"
    for k in ("LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"):
        if os.environ.get(k):
            return "ru" if os.environ[k].lower().startswith("ru") else "en"
    return "en"


LANG = _detect_lang()


def L(en, ru):
    return ru if LANG == "ru" else en


def log(msg):
    line = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {msg}"
    print(line, flush=True)
    try:
        DIR.mkdir(parents=True, exist_ok=True)
        if LOG.exists() and LOG.stat().st_size > 1_000_000:
            LOG.replace(LOG.with_suffix(".log.1"))
        with open(LOG, "a", encoding="utf-8") as f:
            f.write(line + "\n")
    except OSError:
        pass


class ReadError(Exception):
    """Ошибка своей ноды. На сервер уходит английский текст, на экран — на языке системы."""

    def __init__(self, en, ru=None):
        super().__init__(en)
        self.en = en
        self.ru = ru or en

    def local(self):
        return L(self.en, self.ru)


class ServerError(Exception):
    def __init__(self, en, ru=None, code=0):
        super().__init__(en)
        self.en, self.ru, self.code = en, ru or en, code

    def local(self):
        return L(self.en, self.ru)


def http_json(url, body=None, headers=None, timeout=25, local=False):
    data = json.dumps(body).encode() if body is not None else None
    h = {"User-Agent": VERSION, "Accept": "application/json"}
    if data is not None:
        h["Content-Type"] = "application/json"
    h.update(headers or {})
    req = urllib.request.Request(url, data=data, headers=h)
    # своя нода всегда на этом компьютере: системный прокси её не касается
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) if local else urllib.request.build_opener()
    with opener.open(req, timeout=timeout) as r:
        raw = r.read(5_000_000)
    return json.loads(raw.decode("utf-8")) if raw.strip()[:1] in (b"{", b"[") else raw.decode("utf-8").strip()


# ---------- своя нода ----------

class NodeReader:
    """Нода Bitcoin Core (и её форков), EVM-нода или нода Cosmos (CometBFT) на этом компьютере."""

    def __init__(self, ncfg):
        self.kind = ncfg["node"]
        self.url = ncfg["rpc_url"]
        self.cookie = ncfg.get("cookie_file")
        self.user, self.password = ncfg.get("rpc_user"), ncfg.get("rpc_password")
        self.cache = {}
        self.sent_branches = set()  # конкурирующие ветки, о которых сервер уже знает
        self.last_peers = []        # getpeerinfo последнего отчёта: кого можно отключить
        self.spread_log = []        # когда меняли соседей (для лимита в сутки)
        self.mempool_at = 0.0
        self.sent_stats = set()     # хеши блоков, по которым статистику уже отправили
        self.genesis = None         # первый блок: по нему сервер отличает ноду Firo от ноды Bitcoin

    def call(self, method, *params, timeout=30):
        headers = {}
        auth = None
        if self.cookie:
            try:
                auth = Path(self.cookie).read_text(encoding="utf-8").strip()
            except OSError:
                raise ReadError("the node is not running or is still starting",
                                "нода не запущена или ещё стартует") from None
        elif self.user:
            auth = f"{self.user}:{self.password or ''}"
        if auth:
            headers["Authorization"] = "Basic " + base64.b64encode(auth.encode()).decode()
        body = {"jsonrpc": "2.0" if self.kind == "evm" else "1.0", "id": 1, "method": method, "params": list(params)}
        try:
            reply = http_json(self.url, body, headers, timeout=timeout, local=True)
        except urllib.error.HTTPError as e:
            try:
                reply = json.loads(e.read().decode("utf-8"))
            except ValueError:
                if e.code == 401:
                    raise ReadError("the node did not accept the login", "нода не приняла логин") from None
                raise ReadError(f"the node answered HTTP {e.code}", f"нода ответила HTTP {e.code}") from None
        except (urllib.error.URLError, OSError) as e:
            why = getattr(e, "reason", e)
            raise ReadError(f"the node does not answer ({why})", f"нода не отвечает ({why})") from None
        except ValueError:
            raise ReadError("the node answered something that is not JSON", "нода ответила не JSON") from None
        if not isinstance(reply, dict):
            raise ReadError("strange answer from the node", "странный ответ ноды")
        if reply.get("error"):
            err = reply["error"]
            text = err.get("message", err) if isinstance(err, dict) else err
            if isinstance(err, dict) and err.get("code") == -28:  # нода ещё загружает свои данные
                raise ReadError(f"the node is starting: {text}", f"нода запускается: {text}")
            raise ReadError(f"node: {text}", f"нода: {text}")
        return reply.get("result")

    def tm(self, path, timeout=30):
        """Нода CometBFT (сети Cosmos): GET <адрес RPC><путь>, ответ — поле result."""
        try:
            reply = http_json(self.url.rstrip("/") + path, None, {}, timeout=timeout, local=True)
        except urllib.error.HTTPError as e:
            try:
                reply = json.loads(e.read().decode("utf-8"))
            except ValueError:
                raise ReadError(f"the node answered HTTP {e.code}", f"нода ответила HTTP {e.code}") from None
        except (urllib.error.URLError, OSError) as e:
            why = getattr(e, "reason", e)
            raise ReadError(f"the node does not answer ({why})", f"нода не отвечает ({why})") from None
        except ValueError:
            raise ReadError("the node answered something that is not JSON", "нода ответила не JSON") from None
        if not isinstance(reply, dict):
            raise ReadError("strange answer from the node", "странный ответ ноды")
        if reply.get("error"):
            err = reply["error"]
            text = (err.get("data") or err.get("message")) if isinstance(err, dict) else err
            raise ReadError(f"node: {text}", f"нода: {text}")
        return reply.get("result", reply)

    def quick_tip(self):
        """Дешёвая проверка раз в пару секунд: какая сейчас вершина у ноды (без отчёта).
        Новый блок или отмена блоков уходят на сервер сразу, а не при следующем отчёте."""
        try:
            if self.kind == "bitcoind":
                tip = self.call("getbestblockhash", timeout=5)
            elif self.kind == "tendermint":
                tip = ((self.tm("/status", timeout=5) or {}).get("sync_info") or {}).get("latest_block_hash")
            else:
                tip = (self.call("eth_getBlockByNumber", "latest", False, timeout=5) or {}).get("hash")
        except ReadError:
            return None
        return str(tip).lower() if tip else None

    def header(self, block_hash):
        if block_hash in self.cache:
            return self.cache[block_hash]
        if self.kind == "bitcoind":
            h = self.call("getblockheader", block_hash)
            raw = self.call("getblockheader", block_hash, False)  # исходные 80 байт: доказательство для сервера
            hdr = [h["height"], h["hash"], h.get("previousblockhash"), int(h["time"]), float(h.get("difficulty") or 0), raw]
        elif self.kind == "tendermint":
            try:
                r = self.tm(f"/block_by_hash?hash=0x{block_hash.upper()}")
                hdr = tm_hdr(r["block"]["header"], r["block_id"]["hash"])
            except (KeyError, TypeError, ValueError):
                raise ReadError(f"the node does not know block {block_hash[:12]}",
                                f"нода не знает блок {block_hash[:12]}") from None
        else:
            b = self.call("eth_getBlockByHash", block_hash, False)
            if not b:
                raise ReadError(f"the node does not know block {block_hash[:12]}",
                                f"нода не знает блок {block_hash[:12]}")
            hdr = evm_hdr(b)
        remember(self.cache, hdr)
        return hdr

    def report(self, have):
        out = {"mode": "node", "kind": self.kind}
        if self.kind == "bitcoind":
            info = self.call("getblockchaininfo")
            ibd = info.get("initialblockdownload")
            if ibd is None:  # форки на старом Bitcoin (Firo — на 0.14) этого поля не знают
                ibd = (int(info.get("headers") or 0) - int(info.get("blocks") or 0) > 6
                       or float(info.get("verificationprogress") or 0) < 0.999)
            out.update({"chain": info.get("chain", ""), "syncing": bool(ibd),
                        "progress": float(info.get("verificationprogress") or 0)})
            if ibd:  # сколько блоков из скольких: по доле транзакций прогресс долго выглядит как 0%
                out["sync"] = {"blocks": int(info.get("blocks") or 0), "headers": int(info.get("headers") or 0)}
            if self.genesis is None:
                try:
                    self.genesis = str(self.call("getblockhash", 0, timeout=10) or "").lower()
                except ReadError:
                    self.genesis = ""
            if self.genesis:
                out["genesis"] = self.genesis
            tip_hash, tip_height = info["bestblockhash"], info["blocks"]
            try:
                out["peers"] = self.call("getconnectioncount")
                out["version"] = (self.call("getnetworkinfo") or {}).get("subversion", "")
                # С кем соединена нода (только исходящие: это публичные ноды сети, не люди).
                # По ним сервер понимает, в какую часть сети смотрит глаз и не одна ли это
                # нода под разными глазами. Сервер хранит не адреса, а только их отпечатки.
                self.last_peers = [p for p in (self.call("getpeerinfo") or []) if isinstance(p, dict)]
                out["peers_out"] = [peer_host(p.get("addr", "")) for p in self.last_peers
                                    if not p.get("inbound")][:16]
                tips = [t for t in (self.call("getchaintips") or [])
                        if t.get("status") != "active" and t["height"] > tip_height - 200][:10]
                out["tips"] = [{"height": t["height"], "hash": t["hash"], "branchlen": t.get("branchlen", 0),
                                "status": t.get("status", "")} for t in tips]
                # Конкурирующие ветки, которые видела нода: с исходными заголовками, это доказательство
                out["branches"] = []
                for t in tips:
                    if t["hash"] in self.sent_branches or t.get("status") not in ("valid-fork", "valid-headers", "headers-only"):
                        continue
                    hdrs, cur = [], t["hash"]
                    for _ in range(max(1, min(int(t.get("branchlen") or 1), 20))):
                        hdr = self.header(cur)
                        hdrs.append(hdr)
                        cur = hdr[2]
                    out["branches"].append({"tip": t["hash"], "status": t.get("status"), "headers": hdrs[::-1]})
            except ReadError:
                pass
        elif self.kind == "tendermint":
            st = self.tm("/status") or {}
            node, sync = st.get("node_info") or {}, st.get("sync_info") or {}
            out["chain"] = str(node.get("network", ""))
            out["syncing"] = bool(sync.get("catching_up"))  # нода догоняет сеть: сколько осталось, она не говорит
            out["version"] = str(node.get("version", ""))[:60]
            try:
                tip_height, tip_hash = int(sync["latest_block_height"]), str(sync["latest_block_hash"]).lower()
            except (KeyError, TypeError, ValueError):
                raise ReadError("the node did not report its latest block", "нода не сообщила последний блок") from None
            try:  # заголовки последних 20 блоков одним запросом, дальше — из памяти
                metas = self.tm(f"/blockchain?minHeight={max(1, tip_height - 19)}&maxHeight={tip_height}")
                for m in (metas or {}).get("block_metas") or []:
                    remember(self.cache, tm_hdr(m["header"], m["block_id"]["hash"]))
            except (ReadError, KeyError, TypeError, ValueError):
                pass
            try:
                net = self.tm("/net_info") or {}
                out["peers"] = int(net.get("n_peers") or 0)
                # исходящие соседи — публичные ноды сети; сервер хранит только их отпечатки
                out["peers_out"] = [str(x.get("remote_ip", "")) for x in net.get("peers") or []
                                    if isinstance(x, dict) and x.get("is_outbound")][:16]
            except (ReadError, TypeError, ValueError):
                pass
        else:
            out["chain"] = str(int(self.call("eth_chainId"), 16))
            blk = self.call("eth_getBlockByNumber", "latest", False)
            if not blk:
                raise ReadError("the node did not return the latest block", "нода не вернула последний блок")
            hdr = evm_hdr(blk)
            remember(self.cache, hdr)
            tip_height, tip_hash = hdr[0], hdr[1]
            sync = self.call("eth_syncing")
            out["syncing"] = bool(sync)
            if isinstance(sync, dict) and sync.get("highestBlock"):
                cur, top = int(sync.get("currentBlock", "0x0"), 16), int(sync["highestBlock"], 16)
                out["progress"] = cur / top if top else 0
            try:
                out["peers"] = int(self.call("net_peerCount"), 16)
                out["version"] = self.call("web3_clientVersion") or ""
            except (ReadError, TypeError, ValueError):
                pass
        if self.kind == "bitcoind" and not out.get("syncing"):
            self.add_mempool(out, tip_height)
        out["tip"] = {"height": tip_height, "hash": tip_hash}
        out["headers"] = walk(self.header, tip_hash, have, MAX_HEADERS)
        return out


    def add_mempool(self, out, tip_height):
        """Для проверки на цензуру: транзакции, которые давно ждут в очереди (и сколько они платят
        с учётом родителей), и по новым блокам — сколько платили самые дешёвые транзакции в них.
        Если блоки раз за разом берут более дешёвые, а эти пропускают, их держат специально."""
        try:
            stats = []
            for h in range(tip_height, max(0, tip_height - BLOCKSTATS_LAST), -1):
                bh = self.call("getblockhash", h, timeout=5)
                if bh in self.sent_stats:
                    break  # дальше вниз всё уже отправлено
                st = self.call("getblockstats", bh, ["txs", "minfeerate", "feerate_percentiles", "total_weight"])
                pcts = st.get("feerate_percentiles") or [None]
                stats.append({"height": h, "hash": bh, "txs": st.get("txs"),
                              "min": st.get("minfeerate"), "p10": pcts[0], "weight": st.get("total_weight")})
                self.sent_stats.add(bh)
            if len(self.sent_stats) > 500:
                self.sent_stats = set(list(self.sent_stats)[-100:])
            if stats:
                out["blockstats"] = stats
        except (ReadError, AttributeError, TypeError):
            pass  # старая нода без getblockstats: проверки на цензуру не будет
        now = time.time()
        if now - self.mempool_at < MEMPOOL_EVERY:
            return
        self.mempool_at = now
        try:
            info = self.call("getmempoolinfo") or {}
            pool = {"count": int(info.get("size") or 0), "bytes": int(info.get("bytes") or 0)}
            if 0 < pool["count"] <= MEMPOOL_MAX:
                stuck = []
                for txid, e in (self.call("getrawmempool", True, timeout=60) or {}).items():
                    if now - int(e.get("time") or now) < STUCK_AGE:
                        continue
                    vsize = e.get("vsize") or e.get("size") or 0
                    fees = e.get("fees") or {}
                    base = fees.get("base", e.get("fee"))
                    if not vsize or base is None:
                        continue
                    rate = float(base) * 1e8 / vsize
                    anc, anc_size = fees.get("ancestor"), e.get("ancestorsize")
                    if anc is not None and anc_size:
                        rate = min(rate, float(anc) * 1e8 / anc_size)  # платит за родителей тоже
                    stuck.append({"txid": txid, "rate": round(rate, 3), "height": e.get("height"),
                                  "time": e.get("time")})
                stuck.sort(key=lambda x: -x["rate"])
                pool["stuck"] = stuck[:20]
            out["mempool"] = pool
        except (ReadError, AttributeError, TypeError, ValueError):
            pass

    def spread(self, busy, now=None):
        """Сервер сказал: эти соседи уже есть у другого твоего глаза. Отключаем одного такого
        (только автоматического исходящего, не добавленного вручную) — нода сама найдёт другого.
        Возвращает адрес отключённого соседа или None."""
        now = now or time.time()
        if self.kind != "bitcoind" or not busy:
            return None
        self.spread_log = [t for t in self.spread_log if now - t < 86400]
        if (self.spread_log and now - self.spread_log[-1] < SPREAD_GAP) or len(self.spread_log) >= SPREAD_PER_DAY:
            return None
        outs = [p for p in self.last_peers if not p.get("inbound")]
        if len(outs) < SPREAD_MIN_OUT:
            return None
        auto = [p for p in outs if not p.get("addnode") and
                p.get("connection_type", "outbound-full-relay") in ("outbound-full-relay", "block-relay-only")]
        target = next((p for p in auto if peer_host(p.get("addr", "")) in busy and "id" in p), None)
        if not target:
            return None
        try:
            self.call("disconnectnode", "", target["id"], timeout=10)
        except ReadError:
            return None
        self.spread_log.append(now)
        self.last_peers = [p for p in self.last_peers if p is not target]
        return peer_host(target.get("addr", ""))


# ---------- общее ----------

def peer_host(addr):
    """Адрес соседа без порта: 1.2.3.4:8333 -> 1.2.3.4, [2001:db8::1]:8333 -> 2001:db8::1."""
    addr = str(addr or "")
    if addr.startswith("["):
        return addr[1:].split("]")[0]
    if addr.count(":") == 1:
        return addr.split(":")[0]
    return addr


def tm_time(text):
    """Время блока CometBFT («2026-10-23T10:00:00.123456789Z») -> секунды Unix."""
    return int(datetime.strptime(str(text)[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc).timestamp())


def tm_hdr(h, block_hash):
    prev = ((h.get("last_block_id") or {}).get("hash") or "").lower() or None
    return [int(h["height"]), str(block_hash).lower(), prev, tm_time(h["time"]), 0.0]


def evm_hdr(b):
    return [int(b["number"], 16), b["hash"].lower(), (b.get("parentHash") or "").lower() or None,
            int(b["timestamp"], 16), float(int(b.get("difficulty") or "0x0", 16))]


def remember(cache, hdr):
    if len(cache) > 3000:
        cache.clear()
    cache[hdr[1]] = hdr


def fit_reports(reports, limit=REPORT_LIMIT):
    """Много сетей сразу (например, после запуска глаза, когда сервер ещё ничего не знает) — отчёт
    может выйти больше, чем сервер принимает. Тогда у самых длинных сетей оставляем только
    новые заголовки: остальное уйдёт следующими отчётами (сервер скажет, до куда он уже знает)."""
    while len(json.dumps(reports, separators=(",", ":"))) > limit:
        longest = max(reports.values(), key=lambda r: len(r.get("headers") or []), default=None)
        if not longest or len(longest.get("headers") or []) <= 10:
            break
        longest["headers"] = longest["headers"][:len(longest["headers"]) // 2]
    return reports


def walk(get_header, tip_hash, have, limit):
    """Заголовки от вершины назад, пока не дойдём до того, что сервер уже знает."""
    out, cur = [], tip_hash
    while cur and cur != have and len(out) < limit:
        hdr = get_header(cur)
        out.append(hdr)
        cur = hdr[2]
    return out


def version_tuple(text):
    m = re.search(r"(\d+)\.(\d+)", str(text or ""))
    return (int(m.group(1)), int(m.group(2))) if m else (0, 0)


# ---------- работа ----------

def server_call(cfg, path, body=None):
    server = cfg["server"].rstrip("/")
    try:
        return http_json(server + path, body, {"X-Eye-Key": cfg["key"]}, timeout=30)
    except urllib.error.HTTPError as e:
        try:
            msg = json.loads(e.read().decode("utf-8")).get("error", "")
        except ValueError:
            msg = ""
        if e.code == 401:
            raise ServerError("the server does not know this eye key. In your cabinet press “New key” on the eye "
                              "and run the setup with the new key",
                              "сервер не знает этот ключ глаза. В кабинете нажми у глаза «New key» "
                              "и запусти настройку с новым ключом", 401) from None
        hints = {413: ("the report is too big (the server needs web_setup.sh)", "отчёт слишком большой (на сервере нужно запустить web_setup.sh)"),
                 404: (f"{server} has no Flovix eyes (an old version or a wrong address)",
                       f"на {server} нет глаз Flovix (старая версия или не тот адрес)"),
                 429: ("too many requests, slowing down", "слишком часто, сбавляю темп")}
        en, ru = hints.get(e.code, (msg, msg))
        raise ServerError(f"the server answered {e.code}: {msg or en}", f"сервер ответил {e.code}: {msg or ru}", e.code) from None
    except (urllib.error.URLError, OSError) as e:
        why = getattr(e, "reason", e)
        raise ServerError(f"cannot reach {server} ({why}). Check the internet connection",
                          f"нет связи с {server} ({why}). Проверь интернет") from None
    except ValueError:
        raise ServerError(f"{server} is not a Flovix server", f"{server} — это не сервер Flovix") from None


def start_node(ncfg, quiet=False):
    cmd = ncfg.get("start_node")
    if not cmd:
        return False
    try:
        if WINDOWS:
            subprocess.Popen(cmd, creationflags=0x08000000 | 0x00000200,  # без окна, отдельной группой
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
        else:
            subprocess.Popen(cmd, start_new_session=True, stdout=subprocess.DEVNULL,
                             stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
        if not quiet:
            log(L("starting the node: ", "запускаю ноду: ") + " ".join(cmd))
        return True
    except OSError as e:
        log(L(f"could not start the node: {e}", f"не удалось запустить ноду: {e}"))
        return False


def load_config(required=True):
    if not CONFIG.exists():
        if required:
            print(L(f"No settings yet. First run:  {PY} {SCRIPT.name} setup YOUR-KEY",
                    f"Настроек ещё нет. Сначала:  {PY} {SCRIPT.name} setup ТВОЙ-КЛЮЧ"))
            sys.exit(1)
        return {}
    with open(CONFIG, encoding="utf-8") as f:
        return json.load(f)


def save_config(cfg):
    DIR.mkdir(parents=True, exist_ok=True)
    tmp = CONFIG.with_suffix(".tmp")
    tmp.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
    if not WINDOWS:
        os.chmod(tmp, 0o600)
    os.replace(tmp, CONFIG)


def write_status(state):
    try:
        tmp = STATUS.with_suffix(".tmp")
        tmp.write_text(json.dumps(state, ensure_ascii=False, indent=1), encoding="utf-8")
        os.replace(tmp, STATUS)
    except OSError:
        pass


def describe(rep, local_error=None):
    if rep.get("error"):
        return L("node: ", "нода: ") + (local_error or rep["error"])
    if rep.get("syncing"):
        if rep.get("progress") is None:
            return L("the node is catching up with the network, the eye waits until it finishes",
                     "нода догоняет сеть, глаз ждёт, пока она закончит")
        pct = 100 * rep.get("progress", 0)
        sync = rep.get("sync") or {}
        if sync.get("headers"):
            return L(f"the node is syncing: block {sync.get('blocks', 0):,} of {sync['headers']:,} ({pct:.2f}%), "
                     "the eye waits until it finishes",
                     f"нода синхронизируется: блок {sync.get('blocks', 0):,} из {sync['headers']:,} ({pct:.2f}%), "
                     "глаз ждёт, пока она закончит")
        return L(f"the node is syncing: {pct:.2f}%, the eye waits until it finishes",
                 f"нода синхронизируется: {pct:.2f}%, глаз ждёт, пока она закончит")
    peers = L(f", {rep.get('peers')} peers", f", соседей {rep.get('peers')}") if rep.get("peers") is not None else ""
    return L(f"watching, height {rep['tip']['height']}", f"наблюдает, высота {rep['tip']['height']}") + peers


# ---------- один глаз на компьютере ----------

class Lock:
    """Не даёт запустить второй глаз с теми же настройками."""

    def __init__(self):
        self.f = None

    def acquire(self, wait=0):
        DIR.mkdir(parents=True, exist_ok=True)
        deadline = time.time() + wait
        while True:
            f = open(LOCK, "a+")
            try:
                if WINDOWS:
                    import msvcrt
                    f.seek(0)
                    msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
                else:
                    import fcntl
                    fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
                self.f = f
                return True
            except OSError:
                f.close()
                if time.time() >= deadline:
                    return False
                time.sleep(1)

    def release(self):
        if self.f:
            try:
                if WINDOWS:
                    import msvcrt
                    self.f.seek(0)
                    msvcrt.locking(self.f.fileno(), msvcrt.LK_UNLCK, 1)
                self.f.close()
            except OSError:
                pass
            self.f = None


def is_running():
    lock = Lock()
    if lock.acquire():
        lock.release()
        return False
    return True


def spawn_background(script=None):
    """Запустить глаз в фоне, без окна."""
    script = str(script or SCRIPT)
    if WINDOWS:
        pyw = Path(sys.executable).with_name("pythonw.exe")
        exe = str(pyw if pyw.exists() else sys.executable)
        subprocess.Popen([exe, script, "run"], creationflags=0x08000000 | 0x00000200,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
    else:
        subprocess.Popen([sys.executable, script, "run"], start_new_session=True,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)


def restart_self(lock):
    """Файл агента заменили новой версией: перезапускаемся с ней."""
    log(L("the agent or its settings changed, restarting",
          "агент или его настройки изменились, перезапускаюсь"))
    lock.release()
    argv = sys.argv[1:] or ["run"]  # те же параметры (например, --dir), что и при запуске
    if WINDOWS:
        pyw = Path(sys.executable).with_name("pythonw.exe")
        subprocess.Popen([str(pyw if pyw.exists() else sys.executable), str(SCRIPT)] + argv,
                         creationflags=0x08000000 | 0x00000200,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
        sys.exit(0)
    os.execv(sys.executable, [sys.executable, str(SCRIPT)] + argv)


def run(once=False):
    cfg = load_config()
    nodes_cfg = cfg.get("nodes") or {}
    if not nodes_cfg:
        print(L(f"No node of your own yet, so the eye has nothing to watch. Run:  {PY} {SCRIPT.name} setup",
                f"Своих нод ещё нет: глазу нечего наблюдать. Запусти:  {PY} {SCRIPT.name} setup"))
        return 1
    lock = Lock()
    if not once:
        if not lock.acquire(wait=30):
            print(L(f"The eye is already running on this computer. See:  {PY} {SCRIPT.name} status",
                    f"Глаз уже работает на этом компьютере. Посмотреть:  {PY} {SCRIPT.name} status"))
            return 0
        try:
            STOP.unlink()
        except OSError:
            pass
    script_mtime = SCRIPT.stat().st_mtime
    config_mtime = CONFIG.stat().st_mtime
    nodes = {nid: NodeReader(n) for nid, n in nodes_cfg.items()}
    have = {}
    plan, plan_at, plan_version = None, 0.0, None
    every = int(cfg.get("every", 15))
    reported = {}  # сеть -> вершина из последнего принятого отчёта
    down_since, last_start = {}, {}
    last_lines = {}
    update_note = ""
    if not once:
        log(L(f"Flovix eye started ({VERSION}), server {cfg['server']}",
              f"Глаз Flovix запущен ({VERSION}), сервер {cfg['server']}"))
    while True:
        state = {"time": time.strftime("%Y-%m-%d %H:%M:%S"), "agent": VERSION, "networks": {}}
        pause = every
        try:
            if plan is None or time.time() - plan_at > PLAN_EVERY:
                plan = server_call(cfg, "/api/eye/plan")
                plan_at, plan_version = time.time(), plan.get("plan_version")
                every = max(5, int(plan.get("every", every)))
                latest = (plan.get("agent") or {}).get("version", "")
                if latest and version_tuple(latest) > version_tuple(VERSION):
                    update_note = L(f"a newer agent is out ({latest}): download it from {cfg['server']}/observers "
                                    "and run the setup again, your settings stay",
                                    f"вышел новый агент ({latest}): скачай его на {cfg['server']}/observers "
                                    "и снова запусти setup, настройки сохранятся")
                    if not once:
                        log(update_note)
                watched = [n["name"] for n in plan["networks"] if n["id"] in nodes]
                if not once:
                    log(L("watching with my own nodes: ", "наблюдаю своими нодами: ") +
                        (", ".join(watched) or L("none of the watcher's networks", "ни одной сети сторожа")))
            reports, local_errors = {}, {}
            for net in plan["networks"]:
                nid = net["id"]
                if nid not in nodes:
                    continue  # своей ноды этой сети здесь нет: эту сеть глаз не наблюдает
                try:
                    rep = nodes[nid].report(have.get(nid))
                    want = net.get("chain")
                    if want and rep.get("chain") and rep["chain"] != want:
                        raise ReadError(f"the node is on chain “{rep['chain']}”, but “{want}” is needed: check its settings",
                                        f"нода в сети «{rep['chain']}», а нужна «{want}»: проверь её настройки")
                    down_since.pop(nid, None)
                except ReadError as e:
                    rep = {"mode": "node", "kind": net["kind"], "error": e.en[:200]}
                    local_errors[nid] = e.local()
                    down_since.setdefault(nid, time.time())
                    if time.time() - down_since[nid] > 60 and time.time() - last_start.get(nid, 0) > 600:
                        if start_node(nodes_cfg[nid]):
                            last_start[nid] = time.time()
                reports[nid] = rep
                state["networks"][net["name"]] = describe(rep, local_errors.get(nid))
            reply = server_call(cfg, "/api/eye/report", {"v": 3, "agent": VERSION, "networks": fit_reports(reports)})
            for nid, h in (reply.get("have") or {}).items():
                if h:
                    have[nid] = h
            for nid, rep in reports.items():  # сервер принял: эти ветки больше не отправляем
                if nid in nodes and nid not in (reply.get("errors") or {}):
                    nodes[nid].sent_branches.update(b["tip"] for b in rep.get("branches") or [])
                tip = (rep.get("tip") or {}).get("hash")
                # нода ещё синхронизируется: вершина меняется постоянно, срочные отчёты не нужны
                if tip and not rep.get("error") and not rep.get("syncing") and nid not in (reply.get("errors") or {}):
                    reported[nid] = str(tip).lower()
                else:
                    reported.pop(nid, None)
            names = {n["id"]: n["name"] for n in plan["networks"]}
            for nid, err in (reply.get("errors") or {}).items():
                state["networks"][names.get(nid, nid)] = L(f"the server did not accept it: {err}",
                                                           f"сервер не принял: {err}")
                have.pop(nid, None)
            if cfg.get("spread", True) and not once:
                for nid, hint in (reply.get("spread") or {}).items():
                    if nid in nodes and isinstance(hint, dict):
                        dropped = nodes[nid].spread(set(hint.get("busy") or []))
                        if dropped:
                            log(L(f"{names.get(nid, nid)}: dropped neighbour {dropped} — another of your eyes already "
                                  "sees the network through it; the node will pick a different one",
                                  f"{names.get(nid, nid)}: отключил соседа {dropped} — через него сеть уже видит другой "
                                  "твой глаз; нода сама выберет другого"))
            every = max(5, int(reply.get("every", every)))
            pause = every
            if reply.get("plan_version") and reply["plan_version"] != plan_version:
                plan = None  # на сервере поменяли список сетей
            state["server"] = "ok"
        except ServerError as e:
            state["server"] = e.local()
            if e.code == 401:
                pause = 300  # ключ заменили: не стучимся зря каждые 15 секунд
                plan = None
        if update_note:
            state["update"] = update_note
        write_status(state)
        if once:
            print(L("Server: ", "Сервер: ") + state["server"])
            for name, line in state["networks"].items():
                print(f"  {name}: {line}")
            if update_note:
                print(cap(update_note) + ".")
            return 0 if state["server"] == "ok" else 1
        # В журнал — только перемены, а не каждый отчёт
        for name, line in list(state["networks"].items()) + [(L("server", "сервер"), state["server"])]:
            kind_of = line.split(":")[0].split(",")[0]
            if last_lines.get(name) != kind_of:
                log(f"{name}: {line}")
                last_lines[name] = kind_of
        sent_at, moved = time.time(), False
        for second in range(int(pause)):
            time.sleep(1)
            # раз в 2 с спрашиваем ноды, не сменилась ли вершина: тогда отчёт уходит сразу
            # (но не чаще раза в REPORT_GAP секунд — не засыпаем сервер при быстрых блоках)
            if state["server"] == "ok" and second % 2 == 1 and not moved:
                moved = any(nodes[nid].quick_tip() not in (None, tip) for nid, tip in list(reported.items()))
            if moved and time.time() - sent_at >= REPORT_GAP:
                break
            if STOP.exists():
                try:
                    STOP.unlink()
                except OSError:
                    pass
                log(L("stopped by request", "остановлен по команде stop"))
                lock.release()
                return 0
            try:
                # новая версия агента или мастер поменял настройки (добавил или убрал сеть)
                if SCRIPT.stat().st_mtime != script_mtime or CONFIG.stat().st_mtime != config_mtime:
                    restart_self(lock)
            except OSError:
                pass


# ---------- мастер настройки ----------

def cap(text):
    return text[:1].upper() + text[1:]


def ask(question, default=None):
    tip = f" [{default}]" if default else ""
    answer = input(f"{question}{tip}: ").strip().strip('"').strip("'")  # EOF: ответов больше нет, выходим
    return answer or (default or "")


def ask_yes(question, default=True):
    hint = L("Y/n", "Д/н") if default else L("y/N", "д/Н")
    answer = ask(f"{question} ({hint})").lower()
    if not answer:
        return default
    return answer[:1] in ("y", "д", "l")  # «l» — «д» в английской раскладке


def normalize_key(text):
    """FEYE-XXXX-… из того, что вставил человек; None, если это не ключ глаза."""
    t = re.sub(r"[\s\-_]", "", str(text or "")).upper()
    if not t.startswith("FEYE"):
        return None
    t = t[4:]
    if not re.fullmatch(r"[A-Z2-7]{24}", t):
        return None
    return "FEYE-" + "-".join(t[i:i + 4] for i in range(0, 24, 4))


def key_problem(text):
    t = str(text or "").strip()
    if re.fullmatch(r"[0-9a-fA-F]{64}", t):
        return L("This is the fingerprint (SHA-256) of the file, not the key.",
                 "Это отпечаток файла (SHA-256), а не ключ.")
    if t.lower().startswith(("http://", "https://")):
        return L("This is a web address, not the key.", "Это адрес сайта, а не ключ.")
    if t.upper().startswith("FLVX"):
        return L("This is your cabinet key. The eye has its own key, it starts with FEYE-.",
                 "Это ключ кабинета. У глаза свой ключ, он начинается с FEYE-.")
    return L("This does not look like an eye key.", "Это не похоже на ключ глаза.")


def platform_id():
    system = platform.system().lower()
    machine = platform.machine().lower()
    bits64 = struct.calcsize("P") == 8
    if system == "windows":
        return "windows-x86_64" if machine in ("amd64", "x86_64") else None
    if system == "darwin":
        return "darwin-arm64" if machine == "arm64" else "darwin-x86_64"
    if system == "linux":
        if machine in ("x86_64", "amd64"):
            return "linux-x86_64"
        if machine in ("aarch64", "arm64"):
            return "linux-aarch64" if bits64 else "linux-armhf"
        if machine.startswith("armv7") or machine.startswith("armv8"):
            return "linux-armhf"
    return None


def bitcoind_name():
    return "bitcoind.exe" if WINDOWS else "bitcoind"


def bitcoind_version(path):
    try:
        out = subprocess.run([path, "-version"], capture_output=True, text=True, timeout=30).stdout
    except (OSError, subprocess.SubprocessError):
        return None
    m = re.search(r"v(\d+)\.(\d+)", out)
    return (int(m.group(1)), int(m.group(2))) if m else None


def find_bitcoind():
    """Уже установленный Bitcoin Core: (путь, версия) самого нового из найденных."""
    candidates = []
    found = shutil.which("bitcoind")
    if found:
        candidates.append(found)
    candidates += sorted(str(p) for p in APP_DIR.glob(f"bitcoin-core-*/{bitcoind_name()}"))
    if WINDOWS:
        for drive in "CDEFGH":
            candidates += [f"{drive}:\\Bitcoin\\daemon\\bitcoind.exe", f"{drive}:\\Program Files\\Bitcoin\\daemon\\bitcoind.exe"]
    else:
        candidates += ["/usr/local/bin/bitcoind", "/opt/bitcoin/bin/bitcoind", str(_home() / "bitcoin/bin/bitcoind")]
    best = (None, None)
    for c in dict.fromkeys(candidates):
        if Path(c).exists():
            v = bitcoind_version(c)
            if v and (best[1] is None or v > best[1]):
                best = (c, v)
    return best


def core_release():
    test = os.environ.get("FLOVIX_EYE_TEST_CORE")  # только для проверки мастера без интернета
    if test:
        t = json.loads(test)
        return t["url"], t["file"], t["sha256"]
    pid = platform_id()
    if pid not in CORE_FILES:
        return None
    file, sha = CORE_FILES[pid]
    return CORE_URL.format(v=CORE_VERSION, file=file), file, sha


def download_core():
    """Скачать Bitcoin Core с bitcoincore.org, сверить отпечаток, достать bitcoind."""
    rel = core_release()
    if not rel:
        print(L(f"I cannot download Bitcoin Core for this computer ({platform.system()} {platform.machine()}). "
                "Install it from bitcoincore.org and run the setup again.",
                f"Для этого компьютера ({platform.system()} {platform.machine()}) скачать Bitcoin Core сам не могу. "
                "Установи его с bitcoincore.org и запусти настройку ещё раз."))
        return None
    url, file, sha = rel
    target_dir = APP_DIR / f"bitcoin-core-{CORE_VERSION}"
    target = target_dir / bitcoind_name()
    tmp = APP_DIR / (file + ".part")
    APP_DIR.mkdir(parents=True, exist_ok=True)
    print(L(f"Downloading {url}", f"Скачиваю {url}"))
    digest = hashlib.sha256()
    try:
        req = urllib.request.Request(url, headers={"User-Agent": VERSION})
        with urllib.request.urlopen(req, timeout=60) as r, open(tmp, "wb") as out:
            total = int(r.headers.get("Content-Length") or 0)
            done, shown = 0, -1
            while True:
                chunk = r.read(256 * 1024)
                if not chunk:
                    break
                out.write(chunk)
                digest.update(chunk)
                done += len(chunk)
                mb = done // (1024 * 1024)
                if mb != shown:
                    shown = mb
                    of = f" / {total / 1048576:.0f}" if total else ""
                    print(f"\r  {mb}{of} MB", end="", flush=True)
        print()
    except (urllib.error.URLError, OSError) as e:
        print()
        print(L(f"Download failed: {getattr(e, 'reason', e)}. Check the internet connection and run the setup again.",
                f"Скачать не получилось: {getattr(e, 'reason', e)}. Проверь интернет и запусти настройку ещё раз."))
        tmp.unlink(missing_ok=True)
        return None
    if digest.hexdigest() != sha:
        tmp.unlink()
        print(L("STOP: the downloaded file does not match the official fingerprint. Nothing was installed.",
                "СТОП: скачанный файл не совпал с официальным отпечатком. Ничего не установлено."))
        return None
    print(L("Fingerprint checked: this is the official Bitcoin Core.",
            "Отпечаток сверен: это официальный Bitcoin Core."))
    name = bitcoind_name()
    try:
        target_dir.mkdir(parents=True, exist_ok=True)
        if file.endswith(".zip"):
            with zipfile.ZipFile(tmp) as z:
                members = [m for m in z.namelist() if m.rsplit("/", 1)[-1] == name]
                member = next((m for m in members if "/bin/" in "/" + m), members[0] if members else None)
                if not member:
                    raise ValueError("no bitcoind in the archive")
                with z.open(member) as src, open(target, "wb") as dst:
                    shutil.copyfileobj(src, dst)
        else:
            with tarfile.open(tmp, "r:gz") as tf:
                members = [m for m in tf.getmembers() if m.isfile() and m.name.rsplit("/", 1)[-1] == name]
                member = next((m for m in members if "/bin/" in "/" + m.name), members[0] if members else None)
                if not member:
                    raise ValueError("no bitcoind in the archive")
                with tf.extractfile(member) as src, open(target, "wb") as dst:
                    shutil.copyfileobj(src, dst)
        if not WINDOWS:
            os.chmod(target, 0o755)
    except (OSError, ValueError, zipfile.BadZipFile, tarfile.TarError) as e:
        print(L(f"Could not unpack Bitcoin Core: {e}", f"Не получилось распаковать Bitcoin Core: {e}"))
        return None
    finally:
        try:
            tmp.unlink()
        except OSError:
            pass
    print(L(f"Bitcoin Core {CORE_VERSION} is in {target_dir}", f"Bitcoin Core {CORE_VERSION} лежит в {target_dir}"))
    return str(target)


def free_gb(path):
    p = Path(path)
    while not p.exists() and p != p.parent:
        p = p.parent
    try:
        return shutil.disk_usage(str(p)).free / 1e9
    except OSError:
        return 0.0


def fixed_drives():
    if not WINDOWS:
        return []
    try:
        import ctypes
        mask = ctypes.windll.kernel32.GetLogicalDrives()
        return [f"{chr(65 + i)}:\\" for i in range(26)
                if mask & (1 << i) and ctypes.windll.kernel32.GetDriveTypeW(f"{chr(65 + i)}:\\") == 3]
    except Exception:
        return []


def default_datadir(chain, need):
    sub = "FlovixNode" if WINDOWS or MACOS else "flovix-node"
    home_dir = _home() / sub / chain
    if free_gb(_home()) >= need + 5:
        return home_dir
    drives = sorted(fixed_drives(), key=free_gb, reverse=True)
    if drives and free_gb(drives[0]) >= need + 5:
        return Path(drives[0]) / sub / chain
    return home_dir


def setup_bitcoin_core(chain):
    conf_line, port, sub, prune, need = BITCOIN_NETS[chain]
    bitcoind, ver = find_bitcoind()
    if bitcoind and ver and ver[0] >= CORE_MIN:
        print(L(f"Found Bitcoin Core {ver[0]}.{ver[1]}: {bitcoind}", f"Нашёл Bitcoin Core {ver[0]}.{ver[1]}: {bitcoind}"))
    else:
        if bitcoind and ver:
            print(L(f"Found Bitcoin Core {ver[0]}.{ver[1]}, but version {CORE_MIN} or newer is needed.",
                    f"Нашёл Bitcoin Core {ver[0]}.{ver[1]}, а нужна версия {CORE_MIN} или новее."))
        else:
            print(L("Bitcoin Core is not installed on this computer yet.", "Bitcoin Core на этом компьютере ещё нет."))
        if not ask_yes(L(f"Download Bitcoin Core {CORE_VERSION} from bitcoincore.org now? "
                         "I check its fingerprint before using it",
                         f"Скачать Bitcoin Core {CORE_VERSION} с bitcoincore.org? "
                         "Перед запуском сверю его отпечаток"), True):
            return None
        bitcoind = download_core()
        if not bitcoind:
            return None
    datadir = default_datadir(chain, need)
    while True:
        print(L(f"\nThe node needs about {need} GB of disk. Free on the suggested disk: {free_gb(datadir):.0f} GB.",
                f"\nНоде нужно около {need} ГБ на диске. Свободно на предложенном диске: {free_gb(datadir):.0f} ГБ."))
        datadir = Path(ask(L("Folder for the node data (Enter to accept)", "Папка для данных ноды (Enter — согласиться)"),
                           str(datadir))).expanduser()
        if free_gb(datadir) >= need or (datadir / "bitcoin.conf").exists():
            break
        print(L("Not enough free space there. Type another folder, for example on another disk.",
                "Там мало места. Укажи другую папку, например на другом диске."))
    datadir.mkdir(parents=True, exist_ok=True)
    conf = datadir / "bitcoin.conf"
    if not conf.exists():
        lines = ["# Node for the Flovix eye", conf_line, f"prune={prune}", "server=1", "dbcache=300", "maxmempool=100",
                 "listen=0"]  # только исходящие соединения: роутер и брандмауэр трогать не нужно
        if chain != "main":
            lines.append(f"[{chain}]")
        lines += ["rpcbind=127.0.0.1", "rpcallowip=127.0.0.1"]
        conf.write_text("\n".join(x for x in lines if x) + "\n", encoding="utf-8")
    return {"node": "bitcoind", "rpc_url": f"http://127.0.0.1:{port}",
            "cookie_file": str(datadir / sub / ".cookie") if sub else str(datadir / ".cookie"),
            "datadir": str(datadir), "start_node": [bitcoind, f"-datadir={datadir}"]}


def pick_any_network(plan):
    nets = plan["networks"]
    print(L("\nWhich network is your node for?", "\nДля какой сети твоя нода?"))
    kinds = {"bitcoind": L("Bitcoin-family node", "нода семейства Bitcoin"), "evm": L("EVM node", "EVM-нода"),
             "tendermint": L("Cosmos node, CometBFT", "нода Cosmos, CometBFT")}
    for i, n in enumerate(nets, 1):
        if n.get("own"):
            mine = L(", your cabinet", ", твой кабинет")
        elif n.get("community"):  # сеть чужого кабинета: её владелец попросил наблюдателей о помощи
            mine = L(", another cabinet asks observers for help", ", чужой кабинет просит наблюдателей о помощи")
        else:
            mine = ""
        print(f"  {i}. {n['name']} ({kinds.get(n['kind'], n['kind'])}{mine})")
    choice = ask(L("Number", "Номер"))
    return nets[int(choice) - 1] if choice.isdigit() and 1 <= int(choice) <= len(nets) else None


# Ноды форков Bitcoin: порт RPC, папка данных (Windows, macOS, Linux) и подпапка сети
KNOWN_NODES = {
    "firo": (8888, "firo", "Firo", ".firo", ""),
    "dash": (9998, "DashCore", "DashCore", ".dashcore", ""),
    "ravencoin": (8766, "Raven", "Raven", ".raven", ""),
    "litecoin": (9332, "Litecoin", "Litecoin", ".litecoin", ""),
    "dogecoin": (22555, "Dogecoin", "Dogecoin", ".dogecoin", ""),
    "bitcoin": (8332, "Bitcoin", "Bitcoin", ".bitcoin", ""),
    "bitcointestnet": (48332, "Bitcoin", "Bitcoin", ".bitcoin", "testnet4"),
}
# Адрес RPC у EVM-нод и нод Cosmos (у Avalanche C-Chain — отдельный путь на ноде AvalancheGo)
RPC_DEFAULTS = {"avalanchecchain": "http://127.0.0.1:9650/ext/bc/C/rpc"}
KIND_RPC = {"evm": "http://127.0.0.1:8545", "tendermint": "http://127.0.0.1:26657", "bitcoind": "http://127.0.0.1:8332"}


def node_defaults(name, kind="bitcoind"):
    """(адрес RPC, файл .cookie, если он есть) для ноды этой монеты на этом компьютере."""
    key = re.sub(r"[^a-z]", "", str(name).lower())
    if kind != "bitcoind":
        return RPC_DEFAULTS.get(key, KIND_RPC.get(kind, KIND_RPC["evm"])), ""
    port, win, mac, nix, sub = KNOWN_NODES.get(key.replace("testnet4", "testnet"), KNOWN_NODES["bitcoin"])
    if WINDOWS:
        base = Path(os.environ.get("APPDATA", str(_home()))) / win
    elif MACOS:
        base = _home() / "Library" / "Application Support" / mac
    else:
        base = _home() / nix
    cookie = (base / sub if sub else base) / ".cookie"
    return f"http://127.0.0.1:{port}", (str(cookie) if cookie.exists() else "")


def find_running_node(net):
    """Работающая нода форка Bitcoin на этом компьютере для сети net: (адрес RPC, файл .cookie) или None.
    Смотрим все известные ноды (Raven Core, Firo, Dash, Litecoin…): открыт ли порт RPC и есть ли .cookie.
    Если сервер знает первый блок сети, берём ноду именно с ним; иначе — единственную найденную.
    Так ноду находим и у сети кабинета, названной по-своему («RVN test»)."""
    found = []
    for coin in KNOWN_NODES:
        url, cookie = node_defaults(coin)
        try:
            with socket.create_connection(("127.0.0.1", int(url.rsplit(":", 1)[1])), timeout=0.3):
                pass
        except OSError:
            continue
        found.append((url, cookie))
    want = str(net.get("genesis") or "").lower()
    if not want:
        return found[0] if len(found) == 1 else None
    for url, cookie in found:
        if not cookie:
            continue
        try:
            reader = NodeReader({"node": "bitcoind", "rpc_url": url, "cookie_file": cookie})
            if str(reader.call("getblockhash", 0, timeout=5) or "").lower() == want:
                return url, cookie
        except (ReadError, OSError, ValueError, TypeError):
            continue
    return None


def node_chain(reader, kind):
    """Какая сеть у ноды: имя у форков Bitcoin, номер (chain id) у EVM, chain-id у Cosmos."""
    if kind == "evm":
        return str(int(reader.call("eth_chainId"), 16))
    if kind == "tendermint":
        return str(((reader.tm("/status") or {}).get("node_info") or {}).get("network", ""))
    return (reader.call("getblockchaininfo") or {}).get("chain", "")


def node_problem(net, reader, chain):
    """Та ли это нода: у форков Bitcoin сеть у всех называется "main", поэтому сверяем ещё и первый
    блок; у EVM — номер сети, у Cosmos — chain-id. Возвращает текст ошибки или None."""
    genesis = str(net.get("genesis") or "").lower()
    if genesis and net["kind"] == "bitcoind":
        try:
            first = str(reader.call("getblockhash", 0) or "").lower()
        except ReadError:
            first = ""
        if first and first != genesis:
            return L(f"This node is not {net['name']}: its first block is different. Check that the RPC address "
                     f"is the one of the {net['name']} node.",
                     f"Эта нода — не {net['name']}: у неё другой первый блок. Проверь, что адрес RPC — "
                     f"от ноды {net['name']}.")
    want = net.get("chain")
    if want and chain and chain != want:
        return L(f"This node is on chain “{chain}”, but {net['name']} is “{want}”. Check the node's settings.",
                 f"Эта нода в сети «{chain}», а {net['name']} — это «{want}». Проверь настройки ноды.")
    return None


def remove_network(cfg, nodes, names):
    """Пункт 4 мастера: глаз больше не смотрит эту сеть. Ноду, которую ставил сам глаз (Bitcoin Core),
    можно сразу остановить; её папку с данными человек удаляет сам, если хочет освободить диск."""
    ids = list(nodes)
    print(L("\nWhich network should the eye stop watching?", "\nКакую сеть глазу больше не наблюдать?"))
    for i, nid in enumerate(ids, 1):
        print(f"  {i}. {names.get(nid, nid)}")
    pick = ask(L("Number", "Номер"))
    if not (pick.isdigit() and 1 <= int(pick) <= len(ids)):
        print(L("Nothing changed.", "Ничего не изменил."))
        return False
    nid = ids[int(pick) - 1]
    gone = nodes.pop(nid)
    name = names.get(nid, nid)
    print(L(f"{name}: the eye no longer watches it.", f"{name}: глаз её больше не наблюдает."))
    if gone.get("start_node"):  # эту ноду когда-то поставил и запускал сам глаз
        if ask_yes(L("Stop that node too?", "Остановить и саму ноду?"), True):
            try:
                NodeReader(gone).call("stop", timeout=20)
                print(L("The node is stopping.", "Нода останавливается."))
            except ReadError:
                print(L("The node is not running.", "Нода и так не работает."))
        if gone.get("datadir"):
            print(L(f"Its data stays in {gone['datadir']}: delete that folder if you need the disk space.",
                    f"Её данные остались в {gone['datadir']}: удали эту папку, если нужно место на диске."))
    return True


def setup_existing_node(plan):
    net = pick_any_network(plan)
    if not net:
        return None, None
    if net["kind"] in ("evm", "tendermint"):
        ncfg = {"node": net["kind"], "rpc_url": ask(L("RPC address of the node", "Адрес RPC ноды"),
                                                     node_defaults(net["name"], net["kind"])[0])}
    else:
        url, found = node_defaults(net["name"])
        running = find_running_node(net)
        if running:
            if running[0] != url:
                print(L(f"Found a running node of this network: {running[0]}",
                        f"Нашёл работающую ноду этой сети: {running[0]}"))
            url, found = running[0], running[1] or found
        ncfg = {"node": "bitcoind", "rpc_url": ask(L("RPC address of the node", "Адрес RPC ноды"), url)}
        cookie = ask(L("The node's .cookie file (empty: RPC login and password)", "Файл .cookie ноды (пусто — логин и пароль RPC)"), found)
        if cookie:
            ncfg["cookie_file"] = cookie
        else:
            import getpass
            ncfg["rpc_user"] = ask(L("RPC login", "Логин RPC"), "")
            ncfg["rpc_password"] = getpass.getpass(L("RPC password: ", "Пароль RPC: "))
    # Сразу проверяем: пункт 3 только для ноды, которая уже работает
    reader = NodeReader(ncfg)
    try:
        chain = node_chain(reader, net["kind"])
    except (ReadError, TypeError, ValueError) as e:
        if not isinstance(e, ReadError):
            e = ReadError("the node answered something unexpected", "нода ответила что-то не то")
        print(cap(e.local()) + ".")
        print(L(f"Choice 3 is only for a node of {net['name']} that already runs on this computer: "
                "the setup does not install it.",
                f"Пункт 3 — только для ноды {net['name']}, которая уже работает на этом компьютере: "
                "мастер её не ставит."))
        if net.get("chain") == "61":
            print(L("For Ethereum Classic that is Core-Geth: hundreds of GB on a fast SSD, 8 GB of memory, "
                    "several days of sync. Start the node, then run the setup again.",
                    "Для Ethereum Classic это Core-Geth: сотни ГБ на быстром SSD, 8 ГБ памяти, "
                    "несколько дней синхронизации. Запусти ноду и снова запусти настройку."))
        return net, None
    problem = node_problem(net, reader, chain)
    if problem:
        print(problem)
        return net, None
    print(L(f"The node answers: {net['name']}.", f"Нода отвечает: {net['name']}."))
    if net.get("own"):
        print(L("This is a network of your cabinet: your node becomes its source, Flovix watches it through your node.",
                "Это сеть из твоего кабинета: твоя нода станет её источником, Flovix будет смотреть сеть через неё."))
    elif net.get("pow") != "sha256d":
        print(L("Flovix cannot check the proof-of-work of this network yet, so here your eye is a witness "
                "without points for now.",
                "Proof-of-work этой сети Flovix пока проверять не умеет, поэтому здесь глаз — свидетель, "
                "без баллов (пока)."))
    return net, ncfg


def get_plan(cfg, key_arg):
    """Ключ глаза и проверка его на сервере. До трёх попыток, если ключ не тот."""
    key = key_arg
    for _ in range(3):
        if not key:
            if cfg.get("key"):
                key = ask(L("Eye key (Enter to keep the current one)", "Ключ глаза (Enter — оставить прежний)")) or cfg["key"]
            else:
                print(L("Paste the key of your eye. You get it in your cabinet: " + cfg["server"] + "/cabinet#observers\n"
                        "To paste: right-click or Ctrl+V.",
                        "Вставь ключ глаза. Его выдаёт кабинет: " + cfg["server"] + "/cabinet#observers\n"
                        "Вставить: правая кнопка мыши или Ctrl+V."))
                key = ask(L("Eye key (FEYE-…)", "Ключ глаза (FEYE-…)"))
        norm = normalize_key(key)
        if not norm:
            print(key_problem(key) + " " + L("The eye key looks like FEYE-ABCD-EFGH-… (six groups of four).",
                                             "Ключ глаза выглядит так: FEYE-ABCD-EFGH-… (шесть групп по четыре)."))
            key = None
            continue
        cfg["key"] = norm
        try:
            plan = server_call(cfg, "/api/eye/plan")
            return plan
        except ServerError as e:
            print(cap(e.local()) + ".")
            if e.code != 401:
                return None
            key = None
    return None


def connect(opts):
    """Подключить уже работающую ноду без вопросов: ключ, адрес RPC, файл .cookie, сеть по имени."""
    cfg = load_config(required=False)
    cfg["server"] = (opts.get("--server") or cfg.get("server") or DEFAULT_SERVER).rstrip("/")
    key = normalize_key(opts.get("--key") or cfg.get("key"))
    if not key:
        print(L("Give the eye key: --key FEYE-…", "Укажи ключ глаза: --key FEYE-…"))
        return 1
    cfg["key"] = key
    try:
        plan = server_call(cfg, "/api/eye/plan")
    except ServerError as e:
        print(cap(e.local()) + ".")
        return 1
    want = (opts.get("--network") or "").strip().lower()
    nets = [n for n in plan["networks"] if (n["name"].lower() == want if want else n.get("own"))]
    if len(nets) != 1:
        names = ", ".join(n["name"] for n in plan["networks"]) or "-"
        print(L(f"Choose the network with --network NAME. Networks for this eye: {names}",
                f"Укажи сеть: --network ИМЯ. Сети для этого глаза: {names}"))
        return 1
    net = nets[0]
    ncfg = {"node": net["kind"], "rpc_url": opts.get("--rpc") or node_defaults(net["name"], net["kind"])[0]}
    if net["kind"] == "bitcoind" and not opts.get("--rpc"):
        running = find_running_node(net)  # сеть под своим именем: нода находится сама
        if running:
            ncfg["rpc_url"] = running[0]
            if running[1] and not opts.get("--cookie"):
                ncfg["cookie_file"] = running[1]
    if opts.get("--cookie"):
        ncfg["cookie_file"] = str(Path(opts["--cookie"]).expanduser().resolve())
    reader = NodeReader(ncfg)
    try:
        problem = node_problem(net, reader, node_chain(reader, net["kind"]))
    except ReadError as e:
        print(cap(e.local()) + ".")
        return 1
    if problem:
        print(problem)
        return 1
    cfg.setdefault("nodes", {})[net["id"]] = ncfg
    cfg["every"], cfg["lang"] = 15, LANG
    save_config(cfg)
    print(L(f"Connected: {net['name']} through {ncfg['rpc_url']}. Settings: {CONFIG}",
            f"Подключено: {net['name']} через {ncfg['rpc_url']}. Настройки: {CONFIG}"))
    return run(once=True)


def install_copy():
    """Положить агент в постоянную папку (из «Загрузок» его легко случайно удалить)."""
    target = DIR / "flovix_eye.py"
    if target.resolve() == SCRIPT:
        return target
    DIR.mkdir(parents=True, exist_ok=True)
    shutil.copyfile(SCRIPT, target)  # новая дата файла: работающий глаз сам перезапустится с новой версией
    return target


def setup(key_arg=None, server_arg=None):
    print(L("Flovix eye setup", "Настройка глаза Flovix"))
    cfg = load_config(required=False)
    if cfg:
        print(L(f"Found the settings from before ({CONFIG}). Press Enter wherever you want to keep them.\n",
                f"Нашёл прежние настройки ({CONFIG}). Где хочешь оставить как было — просто Enter.\n"))
    server = (server_arg or cfg.get("server") or DEFAULT_SERVER).rstrip("/")
    if not server.startswith(("https://", "http://")):
        print(L(f"The server address must start with https://, not “{server}”.",
                f"Адрес сервера должен начинаться с https://, а не «{server}»."))
        return 1
    cfg["server"] = server
    plan = get_plan(cfg, key_arg)
    if not plan:
        return 1
    print(L(f"\nKey accepted: this is your eye “{plan.get('name')}”.", f"\nКлюч подошёл: это твой глаз «{plan.get('name')}»."))
    nodes = cfg.setdefault("nodes", {})
    names = {n["id"]: n["name"] for n in plan["networks"]}
    by_chain = {}
    for n in plan["networks"]:  # сначала сети сторожа, потом кабинетов: берём первую подходящую
        if n["kind"] != "bitcoind":
            continue
        gen = str(n.get("genesis") or "")
        if n["id"] == "bitcoin" or gen == BTC_GENESIS["main"]:
            by_chain.setdefault("main", n)
        elif n.get("chain") == "testnet4" and (not gen or gen == BTC_GENESIS["testnet4"]):
            by_chain.setdefault("testnet4", n)
    if nodes:
        print(L("Already watching with your own node: ", "Уже наблюдает своей нодой: ") + ", ".join(names.get(k, k) for k in nodes))
    print(L("\nWhich network will this computer watch?", "\nЗа какой сетью будет следить этот компьютер?"))
    if nodes:
        print(L("  0. Keep everything as it is", "  0. Оставить всё как есть"))
    if "testnet4" in by_chain:
        print(L(f"  1. {by_chain['testnet4']['name']}: the easiest start. About 4 GB of disk, the first sync takes a few hours.\n"
                "     A test network for practice: findings there earn no points",
                f"  1. {by_chain['testnet4']['name']}: проще всего. Около 4 ГБ на диске, первая синхронизация — несколько часов.\n"
                "     Тестовая сеть для пробы: баллов за находки там нет"))
    if "main" in by_chain:
        print(L(f"  2. {by_chain['main']['name']}: about 25 GB of disk (an SSD is best), the first sync takes 1 to 3 days",
                f"  2. {by_chain['main']['name']}: около 25 ГБ на диске (лучше SSD), первая синхронизация — 1–3 дня"))
    others = [n["name"] for n in plan["networks"] if n not in by_chain.values()]
    sample = (" (" + ", ".join(others[:3]) + ("…" if len(others) > 3 else "") + ")") if others else ""
    print(L(f"  3. Another network{sample}: only if your node of it already runs on this computer",
            f"  3. Другая сеть{sample}: только если твоя нода этой сети уже работает на этом компьютере"))
    if nodes:
        print(L("  4. Stop watching one of the networks above", "  4. Перестать наблюдать одну из сетей выше"))
    if by_chain:
        nums = " and ".join(n for n, c in (("1", "testnet4"), ("2", "main")) if c in by_chain)
        print(L(f"For {nums} I download Bitcoin Core and set up the node myself.",
                f"Для {nums.replace('and', 'и')} я сам скачаю Bitcoin Core и настрою ноду."))
    default = "0" if nodes else ("1" if "testnet4" in by_chain else "2" if "main" in by_chain else "3")
    choice = ask(L("Your choice", "Твой выбор"), default)
    if choice in ("1", "2") and ({"1": "testnet4", "2": "main"}[choice] in by_chain):
        chain = {"1": "testnet4", "2": "main"}[choice]
        ncfg = setup_bitcoin_core(chain)
        if not ncfg:
            return 1
        nodes[by_chain[chain]["id"]] = ncfg
    elif choice == "3":
        net, ncfg = setup_existing_node(plan)
        if not ncfg:
            print(L("Nothing changed.", "Ничего не изменил."))
            return 1
        nodes[net["id"]] = ncfg
    elif choice == "4" and nodes:
        if not remove_network(cfg, nodes, names):
            return 1
        if not nodes:
            save_config(cfg)
            if is_running():
                stop()
            print(L(f"The eye has no networks left, so it does not run. Add one:  {PY} {SCRIPT.name} setup",
                    f"Сетей у глаза не осталось, поэтому он не работает. Добавить сеть:  {PY} {SCRIPT.name} setup"))
            return 0
    elif choice != "0":
        print(L("No such choice. Run the setup again.", "Такого варианта нет. Запусти настройку ещё раз."))
        return 1
    if not nodes:
        print(L("Without a node of your own the eye has nothing to watch: it never takes data from other explorers.",
                "Без своей ноды глазу нечего наблюдать: у чужих обозревателей он данные не берёт."))
        return 1
    cfg["every"] = 15
    cfg["lang"] = LANG
    save_config(cfg)
    installed = install_copy()

    for ncfg in nodes.values():
        if not ncfg.get("start_node"):
            continue
        reader = NodeReader(ncfg)
        try:
            reader.call("getblockchaininfo")
            continue
        except ReadError:
            pass
        print(L("\nStarting the node…", "\nЗапускаю ноду…"))
        start_node(ncfg, quiet=True)
        for _ in range(45):
            time.sleep(2)
            try:
                reader.call("getblockchaininfo")
                break
            except ReadError:
                continue
    print(L("\nTrial report to the server:", "\nПробный отчёт на сервер:"))
    if run(once=True) != 0:
        print(L(f"\nThe settings are saved. Fix the problem above and check again:  {PY} \"{installed}\" once",
                f"\nНастройки сохранены. Исправь проблему выше и проверь ещё раз:  {PY} \"{installed}\" once"))
        return 1

    started = False
    if ask_yes(L("\nStart the eye now and every time this computer starts?",
                 "\nЗапустить глаз сейчас и при каждом включении компьютера?"), True):
        started = autostart(installed) == 0
    print(L("\nDone.", "\nГотово."))
    if any(n.get("start_node") for n in nodes.values()):
        print(L("The node is syncing now. Until it finishes, the eye waits quietly and then starts watching by itself.",
                "Нода сейчас синхронизируется. Пока она не закончит, глаз тихо ждёт, а потом сам начнёт наблюдать."))
    if not started:
        print(L(f"Run the eye:  {PY} \"{installed}\"", f"Запустить глаз:  {PY} \"{installed}\""))
    print(L(f"See what it does:  {PY} \"{installed}\" status", f"Посмотреть, что он делает:  {PY} \"{installed}\" status"))
    print(L(f"Your cabinet shows its state and points: {cfg['server']}/cabinet#observers",
            f"Состояние и баллы — в кабинете: {cfg['server']}/cabinet#observers"))
    return 0


# ---------- автозапуск ----------

def autostart(script=None, off=False):
    script = Path(script or (DIR / "flovix_eye.py" if (DIR / "flovix_eye.py").exists() else SCRIPT)).resolve()
    if WINDOWS:
        # Папка «Автозагрузка» пользователя: права администратора не нужны
        startup = Path(os.environ.get("APPDATA", "")) / "Microsoft/Windows/Start Menu/Programs/Startup"
        launcher = startup / "Flovix eye.cmd"
        if off:
            launcher.unlink(missing_ok=True)
            print(L("Autostart is off.", "Автозапуск выключен."))
            return 0
        if not startup.is_dir():
            print(L(f"Could not find the Startup folder {startup}", f"Не нашёл папку автозагрузки {startup}"))
            return 1
        pyw = Path(sys.executable).with_name("pythonw.exe")
        exe = str(pyw if pyw.exists() else sys.executable)
        launcher.write_text(f'@start "" "{exe}" "{script}" run\r\n', encoding="utf-8")
        print(L("The eye will start by itself when you sign in to Windows.", "Глаз будет запускаться сам при входе в Windows."))
        if not is_running():
            spawn_background(script)
        print(L("It is running in the background now; you can close this window.",
                "Он уже работает в фоне, это окно можно закрыть."))
        return 0
    if MACOS:
        plist = _home() / "Library/LaunchAgents/com.flovixclude.eye.plist"
        if off:
            subprocess.run(["launchctl", "unload", str(plist)], capture_output=True)
            plist.unlink(missing_ok=True)
            print(L("Autostart is off.", "Автозапуск выключен."))
            return 0
        plist.parent.mkdir(parents=True, exist_ok=True)
        plist.write_text(f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>com.flovixclude.eye</string>
<key>ProgramArguments</key><array><string>{sys.executable}</string><string>{script}</string><string>run</string></array>
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
</dict></plist>
""", encoding="utf-8")
        subprocess.run(["launchctl", "unload", str(plist)], capture_output=True)
        r = subprocess.run(["launchctl", "load", str(plist)])
        print(L("The eye runs in the background and starts with the computer.",
                "Глаз работает в фоне и запускается вместе с компьютером.") if r.returncode == 0 else
              L("launchctl did not accept the autostart.", "launchctl не принял автозапуск."))
        return r.returncode
    if os.geteuid() != 0:
        print(L("Autostart on Linux is a system service and needs administrator rights once.",
                "Автозапуск в Linux — это системная служба, для неё один раз нужны права администратора."))
        if shutil.which("sudo") and sys.stdin and sys.stdin.isatty():
            args = ["sudo", sys.executable, str(script), "autostart"] + (["off"] if off else []) + ["--lang", LANG]
            return subprocess.call(args)
        print(L(f"Run:  sudo {sys.executable} {script} autostart", f"Выполни:  sudo {sys.executable} {script} autostart"))
        return 1
    unit_path = Path("/etc/systemd/system/flovix-eye.service")
    if off:
        subprocess.run(["systemctl", "disable", "--now", "flovix-eye"])
        unit_path.unlink(missing_ok=True)
        subprocess.run(["systemctl", "daemon-reload"])
        print(L("Autostart is off.", "Автозапуск выключен."))
        return 0
    user = os.environ.get("SUDO_USER") or "root"
    unit = f"""[Unit]
Description=Flovix eye (observer for the Flovix watcher)
After=network-online.target
Wants=network-online.target

[Service]
User={user}
WorkingDirectory={script.parent}
Environment=FLOVIX_LANG={LANG}
ExecStart={sys.executable} -u {script} run
Restart=always
RestartSec=20
KillMode=process
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
"""
    unit_path.write_text(unit, encoding="utf-8")
    subprocess.run(["systemctl", "daemon-reload"])
    r = subprocess.run(["systemctl", "enable", "--now", "flovix-eye"])
    if r.returncode == 0:
        print(L("The flovix-eye service is running and starts after every reboot. Log: journalctl -u flovix-eye -f",
                "Служба flovix-eye работает и запустится после перезагрузки. Журнал: journalctl -u flovix-eye -f"))
    return r.returncode


def set_spread(on):
    cfg = load_config()
    cfg["spread"] = bool(on)
    save_config(cfg)
    print(L("Spreading across the network is " + ("on" if on else "off") + ". A running eye picks it up after a restart.",
            "Расхождение по сети " + ("включено" if on else "выключено") + ". Работающий глаз учтёт это после перезапуска."))
    return 0


def stop():
    if not is_running():
        print(L("The eye is not running.", "Глаз сейчас не работает."))
        return 0
    STOP.write_text("stop", encoding="utf-8")
    for _ in range(30):
        time.sleep(1)
        if not is_running():
            print(L("Stopped. It starts again with the computer if autostart is on "
                    f"(turn it off:  {PY} {SCRIPT.name} autostart off).",
                    "Остановлен. Если включён автозапуск, глаз снова запустится вместе с компьютером "
                    f"(выключить:  {PY} {SCRIPT.name} autostart off)."))
            return 0
    print(L("The eye did not stop within 30 seconds.", "Глаз не остановился за 30 секунд."))
    return 1


def status():
    running = is_running()
    print(L("Eye: running" if running else "Eye: not running", "Глаз: работает" if running else "Глаз: не запущен"))
    print(L(f"Settings: {CONFIG}", f"Настройки: {CONFIG}"))
    if not STATUS.exists():
        print(L("No reports yet.", "Отчётов ещё не было."))
        return 1 if not CONFIG.exists() else 0
    st = json.loads(STATUS.read_text(encoding="utf-8"))
    print(L(f"Last report: {st.get('time')}, server: {st.get('server')}",
            f"Последний отчёт: {st.get('time')}, сервер: {st.get('server')}"))
    for name, line in (st.get("networks") or {}).items():
        print(f"  {name}: {line}")
    if st.get("update"):
        print(st["update"])
    print(L(f"Log: {LOG}", f"Журнал: {LOG}"))
    return 0


def main():
    global LANG
    args = sys.argv[1:]
    opts = {}
    for flag in ("--server", "--lang", "--dir", "--key", "--rpc", "--cookie", "--network"):
        if flag in args:
            i = args.index(flag)
            opts[flag] = args[i + 1] if i + 1 < len(args) else ""
            del args[i:i + 2]
    if opts.get("--dir"):
        set_dir(opts["--dir"])
    if opts.get("--lang"):
        LANG = "ru" if opts["--lang"].lower().startswith("ru") else "en"
    elif not os.environ.get("FLOVIX_LANG") and CONFIG.exists():
        try:
            LANG = load_config(required=False).get("lang") or LANG
        except (OSError, ValueError):
            pass
    cmd = args[0].lower() if args else ""
    if cmd and normalize_key(cmd):  # python flovix_eye.py FEYE-… — это тоже настройка
        args, cmd = ["setup"] + args, "setup"
    double_click = WINDOWS and not sys.argv[1:]
    code, interrupted = 0, False
    try:
        if cmd == "setup" or (not cmd and not CONFIG.exists()):
            code = setup(args[1] if len(args) > 1 else None, opts.get("--server"))
        elif cmd == "once":
            code = run(once=True)
        elif cmd == "status":
            code = status()
        elif cmd == "autostart":
            code = autostart(off=len(args) > 1 and args[1].lower() == "off")
        elif cmd == "stop":
            code = stop()
        elif cmd == "spread":
            code = set_spread(len(args) < 2 or args[1].lower() != "off")
        elif cmd == "connect":
            code = connect(opts)
        elif cmd in ("", "run"):
            code = run() or 0
        else:
            print(__doc__)
    except KeyboardInterrupt:
        interrupted = True
        print(L("\nStopped.", "\nОстановлено."))
    except EOFError:
        print(L("\nNo answer, the setup stopped.", "\nОтвета нет, настройка остановлена."))
        code = 1
    if double_click and not interrupted and sys.stdin and sys.stdin.isatty():
        try:
            input(L("\nPress Enter to close this window.", "\nНажми Enter, чтобы закрыть окно."))
        except (EOFError, KeyboardInterrupt):
            pass
    sys.exit(code)


if __name__ == "__main__":
    main()
