# -*- coding: utf-8 -*-
# =============================================================================================================
#  StockFolio_sync  -  the PC side of the phone app "Issu's StockFolio"  (lives next to StockFolio.py)
# =============================================================================================================
#  ALL TEXT IN THIS PROGRAM IS ALWAYS IN ENGLISH - NEVER SWEDISH!
#
#  # ToDo / WHAT THIS DOES
#  * Keeps the open portfolio (transactions, dividends, companies, accounts, price history) equal to the phone app
#    through a small relay server of your own.  Both sides keep a COMPLETE copy and work offline; a round = ask what is
#    new, apply it, send what changed here, apply the answer.  The newest change of a record wins (whole record).
#  * END-TO-END ENCRYPTED: every record is encrypted here with a data secret that exists only on this PC and inside the
#    phone code; the relay holds unreadable text and cannot see a share, a price or an account name.
#      blob  = "1." + base64( nonce(16) + ciphertext + tag(32) )
#      keys  = HMAC-SHA256(secret, "stockfolio/enc/v1") and HMAC-SHA256(secret, "stockfolio/mac/v1")
#      ciphertext = plaintext XOR HMAC-SHA256(enc key, nonce + counter as 4 bytes big-endian) blocks
#      tag   = HMAC-SHA256(mac key, "v1\0" + record id + "\0" + nonce + ciphertext)      (encrypt, then MAC; the id is bound in)
#    Only the Python standard library is used (the Java side uses javax.crypto.Mac), so there is nothing to install.
#  * Record ids: t_<id> a transaction, d_<id> a dividend, i_<sha1(ticker)> a company, a_<sha1(name)> an account,
#    h_<sha1(ticker|year)> the price history of one ticker in one year (merged day by day, never shrinks), s_main settings.
#  * The phone code is  ISSUSYNC1:  + base64url of {"a":"stockfolio","u":relay address,"k":relay key,"e":data secret}.
#    It holds both keys: only give it to your own phone.
#  * StockFolio.py imports this file inside try/except, so the program still works when it is missing.
#
#  # ToDo (not built): several portfolio files at once (only the one open when you paired is synced), alerts on the PC.
# =============================================================================================================
import base64
import hashlib
import hmac
import json
import os
import re
import secrets
import struct
import threading
import time
import urllib.error
import urllib.request

SYNC_VERSION = "1.0"
CODE_PREFIX = "ISSUSYNC1:"
APP_ID = "stockfolio"
BLOB_PREFIX = "1."
TOMB_MS = 400 * 24 * 3600 * 1000


# *************** DEL 01 - THE ENCRYPTION (standard library only) *****************
def _keys(secret):
    s = secret.encode("utf-8")
    return (hmac.new(s, b"stockfolio/enc/v1", hashlib.sha256).digest(),
            hmac.new(s, b"stockfolio/mac/v1", hashlib.sha256).digest())


def _stream(enc_key, nonce, n):
    out = bytearray()
    i = 0
    while len(out) < n:
        out += hmac.new(enc_key, nonce + struct.pack(">I", i), hashlib.sha256).digest()
        i += 1
    return bytes(out[:n])


def encrypt(secret, rec_id, obj, nonce=None):
    """obj (JSON-able) -> the text the relay stores.  nonce is only given by the tests."""
    enc, mac = _keys(secret)
    nonce = nonce or os.urandom(16)
    pt = json.dumps(obj, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
    ks = _stream(enc, nonce, len(pt))
    ct = bytes(a ^ b for a, b in zip(pt, ks))
    tag = hmac.new(mac, b"v1\0" + rec_id.encode("utf-8") + b"\0" + nonce + ct, hashlib.sha256).digest()
    return BLOB_PREFIX + base64.b64encode(nonce + ct + tag).decode("ascii")


def decrypt(secret, rec_id, blob):
    """The text from the relay -> the object.  ValueError when it was changed, belongs to another id or another secret."""
    if not isinstance(blob, str) or not blob.startswith(BLOB_PREFIX):
        raise ValueError("unknown format")
    try:
        raw = base64.b64decode(blob[len(BLOB_PREFIX):].encode("ascii"), validate=True)
    except Exception:
        raise ValueError("not base64")
    if len(raw) < 16 + 32:
        raise ValueError("too short")
    nonce, ct, tag = raw[:16], raw[16:-32], raw[-32:]
    enc, mac = _keys(secret)
    want = hmac.new(mac, b"v1\0" + rec_id.encode("utf-8") + b"\0" + nonce + ct, hashlib.sha256).digest()
    if not hmac.compare_digest(want, tag):
        raise ValueError("wrong secret or changed record")
    pt = bytes(a ^ b for a, b in zip(ct, _stream(enc, nonce, len(ct))))
    return json.loads(pt.decode("utf-8"))


# *************** DEL 02 - THE PHONE CODE (the same text every synced app uses) *****************
def code_make(url, key, secret):
    body = json.dumps({"a": APP_ID, "u": url, "k": key, "e": secret}, separators=(",", ":"))
    return CODE_PREFIX + base64.urlsafe_b64encode(body.encode("utf-8")).decode("ascii").rstrip("=")


def code_parse(text):
    """{'a','u','k','e'} read out of any text around the code, or None."""
    if not text:
        return None
    t = re.sub(r"\s+", "", text)
    i = t.find(CODE_PREFIX)
    if i < 0:
        return None
    m = re.match(r"[A-Za-z0-9_\-]+", t[i + len(CODE_PREFIX):])
    if not m:
        return None
    body = m.group(0)
    for n in range(len(body), max(len(body) - 400, 15), -1):       # text after the code sticks to it: shorten until it decodes
        part = body[:n]
        try:
            d = json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)).decode("utf-8"))
        except Exception:
            continue
        if not isinstance(d, dict):
            continue
        url, key = str(d.get("u", "")), str(d.get("k", ""))
        if not re.match(r"^https?://\S+$", url, re.I) or len(key) < 8:
            return None
        return {"a": str(d.get("a", "")), "u": url, "k": key, "e": str(d.get("e", ""))}
    return None


# *************** DEL 03 - THE PORTFOLIO AS RECORDS (and back) *****************
# host = the StockFolio App (or a test double): .pf (transactions, dividends, instruments), .S (settings), .price_history, .account_meta, .accounts
def _sha(s):
    return hashlib.sha1(s.encode("utf-8")).hexdigest()


def rid(kind, key):
    """The record id (4-40 characters of A-Za-z0-9_-, what the relay accepts)."""
    key = str(key)
    if kind in ("t", "d") and re.fullmatch(r"[A-Za-z0-9]{1,30}", key):
        return "%s_%s" % (kind, key)
    return "%s_%s" % (kind, _sha(key)[:16])


def _num(v, default=0.0):
    try:
        return float(v)
    except (TypeError, ValueError):
        return default


def records_of(host):
    """{record id: payload} of everything that is shared with the phone."""
    out = {}
    for t in host.pf.transactions:
        if t.get("id") not in (None, ""):
            out.setdefault(rid("t", t["id"]), dict(t))
    for d in host.pf.dividends:
        if d.get("id") not in (None, ""):
            out.setdefault(rid("d", d["id"]), dict(d))
    for tk, inst in (host.pf.instruments or {}).items():
        p = dict(inst) if isinstance(inst, dict) else {}
        p["ticker"] = tk
        out[rid("i", tk)] = p
    names = list(getattr(host, "accounts", []) or [])
    for n in (getattr(host, "account_meta", {}) or {}):
        if n not in names:
            names.append(n)
    for order, n in enumerate(names):
        meta = (host.account_meta or {}).get(n, {})
        p = {"name": n, "order": order}
        for k in ("owner", "broker", "code", "section"):
            if meta.get(k):
                p[k] = meta[k]
        out[rid("a", n)] = p
    for tk, days in (host.price_history or {}).items():
        by_year = {}
        for day, price in days.items():
            by_year.setdefault(str(day)[:4], {})[day] = price
        for yr, ds in by_year.items():
            out[rid("h", tk + "|" + yr)] = {"ticker": tk, "year": yr, "days": ds}
    if host.S.get("warn_days") is not None:
        out["s_main"] = {"warn_days": host.S.get("warn_days")}
    return out


def _hash(payload):
    if payload is None:
        return "DEL"
    return _sha(json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")))


def _clean_tx(p):
    p = dict(p)
    p["id"] = str(p.get("id", ""))
    for k in ("shares", "price", "courtage"):
        p[k] = _num(p.get(k))
    p["type"] = "SELL" if str(p.get("type", "BUY")).upper() == "SELL" else "BUY"
    for k in ("ticker", "company", "account", "date", "note"):
        p[k] = str(p.get(k, "") or "")
    return p


def _clean_div(p):
    p = dict(p)
    p["id"] = str(p.get("id", ""))
    p["per_share"] = _num(p.get("per_share"))
    for k in ("shares", "amount"):
        if k in p:
            p[k] = _num(p.get(k))
    for k in ("ticker", "date", "account", "note"):
        p[k] = str(p.get(k, "") or "")
    return p


def apply_record(host, rec_id, payload):
    """Puts one record from the phone into the portfolio (payload None = deleted there).  Returns True when something changed."""
    kind = rec_id[:1]
    if kind in ("t", "d"):
        lst = host.pf.transactions if kind == "t" else host.pf.dividends
        idx = next((i for i, x in enumerate(lst) if x.get("id") not in (None, "") and rid(kind, x["id"]) == rec_id), None)
        if payload is None:
            if idx is None:
                return False
            del lst[idx]
            return True
        p = _clean_tx(payload) if kind == "t" else _clean_div(payload)
        if not p["id"] or not p["ticker"]:
            return False
        if idx is None:
            lst.append(p)
        elif lst[idx] == p:
            return False                                   # the same row already: nothing to save
        else:
            lst[idx] = p
        return True
    if kind == "i":
        tk = (payload or {}).get("ticker") if payload else None
        if payload is None:
            for k in [k for k in host.pf.instruments if rid("i", k) == rec_id]:
                del host.pf.instruments[k]
                return True
            return False
        if not tk:
            return False
        new = {k: v for k, v in payload.items() if k != "ticker"}
        if host.pf.instruments.get(tk) == new:
            return False
        host.pf.instruments[tk] = new
        return True
    if kind == "a":
        if payload is None:
            for n in [n for n in list(host.account_meta) if rid("a", n) == rec_id]:
                used = any(t.get("account") == n for t in host.pf.transactions)
                host.account_meta.pop(n, None)
                if not used and n in host.accounts:
                    host.accounts.remove(n)
                return True
            return False
        n = str(payload.get("name", "")).strip()
        if not n:
            return False
        meta = {k: str(payload[k]) for k in ("owner", "broker", "code", "section") if payload.get(k)}
        same = host.account_meta.get(n) == meta and n in host.accounts
        host.account_meta[n] = meta
        if n not in host.accounts:
            host.accounts.append(n)
        return not same
    if kind == "h":
        if payload is None:
            return False                                   # a price history never shrinks
        tk, days = payload.get("ticker"), payload.get("days")
        if not tk or not isinstance(days, dict):
            return False
        mine = host.price_history.setdefault(tk, {})
        changed = False
        for day, price in days.items():
            if day not in mine and re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(day)) and _num(price, None) is not None:
                mine[day] = _num(price)
                changed = True
        return changed
    if kind == "s":
        if payload and payload.get("warn_days") is not None:
            try:
                n = int(payload["warn_days"])
            except (TypeError, ValueError):
                return False
            if host.S.get("warn_days") == n:
                return False
            host.S["warn_days"] = n
            return True
        return False
    return False


# *************** DEL 04 - THE SYNC MEMORY AND ONE ROUND *****************
class SyncError(Exception):
    def __init__(self, code, detail=""):
        Exception.__init__(self, code + (": " + detail if detail else ""))
        self.code = code


ERR_TEXT = {
    "key": "The server does not accept the relay key (make a new phone code).",
    "many": "Too many tries - wait a while.",
    "big": "Too much to send at once.",
    "http": "The server answered with an error.",
    "answer": "The server's answer was not understood.",
    "net": "The server could not be reached.",
    "file": "This is not the portfolio that was paired with the phone.",
}


class Link:
    """The sync memory (one JSON file, PRIVATE: it holds the keys) and the steps of a round."""

    def __init__(self, path):
        self.path = path
        self.url = self.key = self.secret = ""
        self.since = 0
        self.file = ""                     # the portfolio file that is synced (normalised path)
        self.auto_min = 5
        self.recs = {}                     # record id -> {"h": synced hash, "u": synced time, "lh": hash of what is here now, "lu": time of that change}
        self.last = 0
        self.msg = ""
        self._lock = threading.RLock()
        self.load()

    # ----- file
    def load(self):
        try:
            with open(self.path, "r", encoding="utf-8") as f:
                d = json.load(f)
        except Exception:
            return
        self.url, self.key, self.secret = d.get("url", ""), d.get("key", ""), d.get("secret", "")
        self.since = int(d.get("since", 0) or 0)
        self.file = d.get("file", "")
        self.auto_min = int(d.get("auto_min", 5) or 0)
        self.recs = d.get("recs", {}) if isinstance(d.get("recs"), dict) else {}
        self.last = int(d.get("last", 0) or 0)
        self.msg = d.get("msg", "")

    def save(self):
        try:
            os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
            tmp = self.path + ".tmp"
            with open(tmp, "w", encoding="utf-8") as f:
                json.dump({"url": self.url, "key": self.key, "secret": self.secret, "since": self.since, "file": self.file,
                           "auto_min": self.auto_min, "recs": self.recs, "last": self.last, "msg": self.msg}, f, indent=1)
            os.replace(tmp, self.path)
        except Exception:
            pass

    def configured(self):
        return bool(self.url and self.key and self.secret)

    def code(self):
        return code_make(self.url, self.key, self.secret) if self.configured() else ""

    def new_secret(self):
        self.secret = secrets.token_urlsafe(32)

    def forget(self):
        self.url = self.key = self.secret = ""
        self.since, self.last, self.msg, self.file = 0, 0, "", ""
        self.recs = {}

    def restart_memory(self, file=""):
        """A different portfolio (or a new server): everything that is here counts as changed and is sent again."""
        self.since, self.recs, self.file = 0, {}, file

    # ----- the steps
    def detect(self, host, now=None):
        """Notes what changed HERE since the last time (the time of the change = now).  Cheap: called after every save."""
        with self._lock:
            now = int(time.time() * 1000) if now is None else now
            cur = {k: _hash(p) for k, p in records_of(host).items()}
            for k, h in cur.items():
                e = self.recs.get(k)
                if e is None:
                    self.recs[k] = {"h": "", "u": 0, "lh": h, "lu": now}
                elif e["lh"] != h:
                    e["lh"], e["lu"] = h, max(now, e["u"] + 1, e["lu"] + 1)
            for k in list(self.recs):
                e = self.recs[k]
                if k not in cur and e["lh"] != "DEL":
                    if e["h"] == "":                                   # never reached the relay: nothing to take away there
                        del self.recs[k]
                    else:
                        e["lh"], e["lu"] = "DEL", max(now, e["u"] + 1, e["lu"] + 1)

    def pending(self):
        return [k for k, e in self.recs.items() if e["lh"] != e["h"]]

    def apply_answer(self, host, ans):
        """The relay's answer is applied.  Returns {'new','changed','removed','bad'} counts; the host is told with phone_data_changed()."""
        st = {"new": 0, "changed": 0, "removed": 0, "bad": 0}
        with self._lock:
            recs = ans.get("recs") or {}
            seq = int(ans.get("seq", 0) or 0)
            if seq < self.since:                                        # the server was emptied/reinstalled: send everything again
                self.since = 0
                for e in self.recs.values():
                    e["h"], e["u"] = "", 0
                return st
            changed_any = False
            applied = []                                                # (record id, time, payload or None, existed here)
            for k in sorted(recs):
                r = recs[k]
                if not isinstance(r, dict):
                    continue
                try:
                    u = int(r.get("u", 0))
                except (TypeError, ValueError):
                    continue
                e = self.recs.get(k)
                if e is not None and u <= e["u"]:
                    continue                                            # the same or older than what we already have (our own push comes back)
                if e is not None and e["lh"] != e["h"] and e["lu"] > u:
                    continue                                            # our change is newer: it goes out in the push
                if r.get("d"):
                    payload = None
                else:
                    try:
                        payload = decrypt(self.secret, k, r.get("c"))
                    except ValueError:
                        st["bad"] += 1
                        continue
                if apply_record(host, k, payload):
                    changed_any = True
                applied.append((k, u, payload, e is not None and e["h"] not in ("", "DEL")))
            if applied:
                cur = records_of(host)                                  # what is here now: the memory of each applied record is set from it
                for k, u, payload, existed in applied:
                    if payload is not None and k not in cur:
                        st["bad"] += 1                                  # the record could not be used here (invalid): nothing to remember
                        continue
                    cur_h = _hash(cur.get(k) if payload is not None else None)
                    if k[:1] == "h" and payload is not None:            # a price history only grows: what the phone sent plus our own days
                        sent_h = _hash(payload)
                        self.recs[k] = {"h": sent_h, "u": u, "lh": cur_h, "lu": u if cur_h == sent_h else max(u + 1, int(time.time() * 1000))}
                    else:
                        self.recs[k] = {"h": cur_h, "u": u, "lh": cur_h, "lu": u}
                    if payload is None:
                        st["removed"] += 1
                    elif existed:
                        st["changed"] += 1
                    else:
                        st["new"] += 1
            if "seq" in ans:
                self.since = max(self.since, seq)
            if changed_any:
                host.phone_data_changed()
            self._prune()
        return st

    def _prune(self):
        now = int(time.time() * 1000)
        for k in [k for k, e in self.recs.items() if e["h"] == "DEL" and e["lh"] == "DEL" and now - e["u"] > TOMB_MS]:
            del self.recs[k]

    def make_push(self, host):
        """({record id: envelope}, {record id: (time, hash)}) of everything changed here and not yet sent."""
        with self._lock:
            cur = records_of(host)
            push, meta = {}, {}
            for k in sorted(self.pending()):
                e = self.recs[k]
                if e["lh"] == "DEL":
                    push[k] = {"u": e["lu"], "d": 1, "c": ""}
                elif k in cur:
                    push[k] = {"u": e["lu"], "d": 0, "c": encrypt(self.secret, k, cur[k])}
                else:
                    continue
                meta[k] = (e["lu"], e["lh"])
            return push, meta

    def commit(self, meta):
        """What reached the relay is not pending any more - unless it was changed again meanwhile."""
        with self._lock:
            for k, (lu, lh) in meta.items():
                e = self.recs.get(k)
                if e is not None and e["lu"] == lu:
                    e["h"], e["u"] = lh, lu

    def finish(self, text):
        self.last = int(time.time() * 1000)
        self.msg = text
        self.save()

    def round_blocking(self, host, post):
        """A whole round with a blocking post(since, recs) -> answer (the app does the same in steps on a worker thread; the tests use this)."""
        self.detect(host)
        st = self.apply_answer(host, post(self.since, {}))
        push, meta = self.make_push(host)
        if push:
            ans = post(self.since, push)
            self.commit(meta)
            more = self.apply_answer(host, ans)
            for k in st:
                st[k] += more[k]
        st["sent"] = len(push)
        self.finish(summary(st))
        return st


def summary(st):
    return "Synced: %d sent, %d new, %d changed, %d removed%s" % (
        st.get("sent", 0), st["new"], st["changed"], st["removed"], (", %d unreadable" % st["bad"]) if st["bad"] else "")


# *************** DEL 05 - ONE CALL OF THE RELAY *****************
def post_sync(url, key, since, recs, timeout=25):
    base = url if url.endswith("/") else url + "/"
    body = json.dumps({"since": since, "recs": recs}, separators=(",", ":")).encode("utf-8")
    req = urllib.request.Request(base + "sync", data=body, method="POST")
    req.add_header("X-Sync-Key", key)
    req.add_header("Content-Type", "application/json")
    req.add_header("User-Agent", "StockFolio-sync/1")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            ans = json.loads(r.read(16 * 1024 * 1024).decode("utf-8"))
    except urllib.error.HTTPError as e:
        raise SyncError({401: "key", 429: "many", 413: "big"}.get(e.code, "http"), str(e.code))
    except (urllib.error.URLError, OSError, TimeoutError) as e:
        raise SyncError("net", type(e).__name__)
    except ValueError:
        raise SyncError("answer")
    if not isinstance(ans, dict) or "seq" not in ans:
        raise SyncError("answer")
    return ans


# *************** DEL 06 - THE WINDOW AND THE TIMER INSIDE StockFolio.py (tkinter is only used here, and only when called) *****************
_STATE = {"link": None, "app": None, "ui": None, "busy": False, "log": None}


def attach(app, help_dir, ui, log=None):
    """Called once by StockFolio.py after the window is built: opens the sync memory, starts the timer."""
    link = Link(os.path.join(help_dir, "phone_sync.json"))
    _STATE.update(link=link, app=app, ui=ui, log=log)
    try:
        app.root.after(20000, _tick)
    except Exception:
        pass
    return link


def link():
    return _STATE["link"]


def _log(msg):
    try:
        if _STATE["log"]:
            _STATE["log"]("phone sync: " + msg)
    except Exception:
        pass


def after_save(pf):
    """Called by Portfolio.save(): notes the changes with the time they were made (cheap, never raises)."""
    try:
        lk, app = _STATE["link"], _STATE["app"]
        if lk and app and lk.configured() and app.pf is pf and _same_file(lk, pf.path):
            lk.detect(app)
            lk.save()
    except Exception as e:
        _log("after_save failed: %s" % e)


def _norm(p):
    return os.path.normcase(os.path.abspath(p)) if p else ""


def _same_file(lk, path):
    return not lk.file or _norm(lk.file) == _norm(path)


def _tick():
    app, lk = _STATE["app"], _STATE["link"]
    try:
        if lk and lk.configured() and lk.auto_min > 0 and not _STATE["busy"] and _same_file(lk, app.pf.path) \
                and int(time.time() * 1000) - lk.last >= lk.auto_min * 60000:
            run_async(quiet=True)
    except Exception as e:
        _log("tick failed: %s" % e)
    try:
        app.root.after(30000, _tick)
    except Exception:
        pass


def run_async(quiet=False, done=None):
    """One round without freezing the window: network on a worker thread, data changes on the main thread."""
    app, lk = _STATE["app"], _STATE["link"]
    if _STATE["busy"] or lk is None or not lk.configured():
        return False
    if not _same_file(lk, app.pf.path):
        lk.msg = ERR_TEXT["file"]
        if done:
            done(False, lk.msg)
        return False
    _STATE["busy"] = True
    root = app.root
    url, key = lk.url, lk.key

    def fail(e):
        _STATE["busy"] = False
        lk.msg = ERR_TEXT.get(getattr(e, "code", "net"), ERR_TEXT["net"])
        lk.save()
        _log("failed: %s" % e)
        if done:
            done(False, lk.msg)

    def step1():
        try:
            ans = post_sync(url, key, lk.since, {})
        except Exception as e:
            root.after(0, lambda e=e: fail(e))
            return
        root.after(0, lambda: step2(ans))

    def step2(ans):
        try:
            lk.detect(app)
            st = lk.apply_answer(app, ans)
            push, meta = lk.make_push(app)
        except Exception as e:
            fail(e)
            return
        if not push:
            st["sent"] = 0
            end(st)
            return

        def work():
            try:
                ans2 = post_sync(url, key, lk.since, push)
            except Exception as e:
                root.after(0, lambda e=e: fail(e))
                return
            root.after(0, lambda: step3(st, meta, ans2))
        threading.Thread(target=work, daemon=True).start()

    def step3(st, meta, ans2):
        try:
            lk.commit(meta)
            more = lk.apply_answer(app, ans2)
            for k in more:
                st[k] += more[k]
            st["sent"] = len(meta)
        except Exception as e:
            fail(e)
            return
        end(st)

    def end(st):
        _STATE["busy"] = False
        lk.finish(summary(st))
        if done:
            done(True, lk.msg)

    threading.Thread(target=step1, daemon=True).start()
    return True


def open_dialog(app, help_dir):
    """File > Phone sync...: the code, the relay, the timer, a button to sync now."""
    import tkinter as tk
    from tkinter import messagebox
    ui, lk = _STATE["ui"], _STATE["link"]
    if lk is None:
        messagebox.showinfo("Phone sync", "Phone sync is not ready yet.")
        return
    top = tk.Toplevel(app.root, bg=ui["bg"])
    top.title("Phone sync - Issu's StockFolio app")
    ui["init_dialog"](top, app.root)
    top.geometry("640x560")
    tk.Label(top, text="Phone sync", bg=ui["bg"], fg=ui["accent"], font=("Segoe UI", 14, "bold")).pack(pady=(12, 0))
    tk.Label(top, bg=ui["bg"], fg=ui["dim"], font=("Segoe UI", 9), justify="left", wraplength=600,
             text="Keeps this portfolio equal to the phone app. Everything is encrypted here before it leaves the PC: the relay "
                  "server only holds unreadable text. The phone code contains the keys - give it only to your own phone.").pack(padx=18, pady=(2, 8))
    info = tk.Label(top, bg=ui["bg"], fg=ui["fg"], font=ui["font"], justify="left", anchor="w", wraplength=600)
    info.pack(fill="x", padx=18)
    last = tk.Label(top, bg=ui["bg"], fg=ui["dim"], font=("Segoe UI", 9), justify="left", anchor="w", wraplength=600)
    last.pack(fill="x", padx=18, pady=(4, 6))
    bar = tk.Frame(top, bg=ui["bg"])
    bar.pack(fill="x", padx=14, pady=4)
    box = tk.Frame(top, bg=ui["bg"])
    box.pack(fill="x", padx=14, pady=4)

    def show():
        if lk.configured():
            host = re.sub(r"^[a-zA-Z]+://", "", lk.url).split("/")[0]
            info.config(text="Connected to %s\nPortfolio that is synced: %s\nWaiting to be sent: %d changes" % (
                host, os.path.basename(lk.file or app.pf.path), len(lk.pending())), fg=ui["fg"])
        else:
            info.config(text="Not set up yet. 1) Press 'Use relay.json'. 2) Press 'Copy phone code'. 3) Paste the code in the phone app "
                             "(Settings > Paste the phone code).", fg=ui["warn"])
        t = time.strftime("%Y-%m-%d %H:%M", time.localtime(lk.last / 1000)) if lk.last else "never"
        last.config(text="Last sync: %s   %s" % (t, lk.msg))
        top.after(2000, lambda: show() if top.winfo_exists() else None)

    def use_relay():
        path = os.path.join(help_dir, "relay.json")
        try:
            with open(path, "r", encoding="utf-8") as f:
                d = json.load(f)
            url, key = str(d["url"]), str(d["key"])
        except Exception:
            messagebox.showinfo("Phone sync", "relay.json was not found in:\n%s\n\nIt is made when the relay is installed "
                                "(WebdockTool > Jobs > StockFolio relay). Copy it there and try again." % help_dir, parent=top)
            return
        if lk.url != url or lk.key != key:
            lk.url, lk.key = url, key
            lk.since = 0
            for e in lk.recs.values():
                e["h"], e["u"] = "", 0
        if not lk.secret:
            lk.new_secret()
        if not lk.file:
            lk.file = app.pf.path
        lk.save()
        show()

    def copy_code():
        if not lk.configured():
            use_relay()
        if not lk.configured():
            return
        app.root.clipboard_clear()
        app.root.clipboard_append(lk.code())
        ui["flash_ok"](app.root, "Phone code copied")

    def sync_now():
        if not lk.configured():
            messagebox.showinfo("Phone sync", "Set it up first (Use relay.json).", parent=top)
            return
        if not run_async(done=lambda ok, msg: show()):
            show()
        show()

    def this_file():
        if messagebox.askyesno("Phone sync", "Sync THIS portfolio file with the phone from now on?\n\n%s\n\nThe phone will get this file's data "
                               "(the phone's own list is not deleted; records of the old file stay there)." % app.pf.path, parent=top):
            lk.restart_memory(app.pf.path)
            lk.save()
            show()

    def new_code():
        if messagebox.askyesno("Phone sync", "Make a NEW secret?\n\nEvery phone must paste the new code, and the old encrypted records on "
                               "the relay can no longer be read (they are sent again, encrypted with the new secret).", parent=top):
            lk.new_secret()
            lk.restart_memory(lk.file or app.pf.path)
            lk.save()
            show()

    def forget():
        if messagebox.askyesno("Phone sync", "Disconnect from the relay?\n\nNothing is deleted on the PC or the phone.", parent=top):
            lk.forget()
            lk.save()
            show()

    mk = ui["btn"]
    mk(bar, "Use relay.json", use_relay, ui["ok"]).pack(side="left", padx=4)
    mk(bar, "Copy phone code", copy_code, ui["ok"]).pack(side="left", padx=4)
    mk(bar, "Sync now", sync_now, ui["ok"]).pack(side="left", padx=4)
    mk(bar, "Close", top.destroy, ui["cancel"]).pack(side="right", padx=4)

    tk.Label(box, text="Sync by itself every", bg=ui["bg"], fg=ui["fg"], font=ui["font"]).pack(side="left")
    var = tk.StringVar(value=str(lk.auto_min))

    def set_auto(*_):
        try:
            lk.auto_min = int(var.get())
        except ValueError:
            lk.auto_min = 5
        lk.save()
    om = tk.OptionMenu(box, var, "0", "2", "5", "15", "30", command=set_auto)
    om.config(bg=ui["cancel"], fg="#10243a", relief="flat", highlightthickness=0, font=ui["font"])
    om.pack(side="left", padx=6)
    tk.Label(box, text="minutes (0 = only when you press Sync now)", bg=ui["bg"], fg=ui["dim"], font=("Segoe UI", 9)).pack(side="left")

    bar2 = tk.Frame(top, bg=ui["bg"])
    bar2.pack(fill="x", padx=14, pady=(10, 4))
    mk(bar2, "Sync THIS file instead", this_file, ui["cancel"]).pack(side="left", padx=4)
    mk(bar2, "New secret...", new_code, ui["cancel"]).pack(side="left", padx=4)
    mk(bar2, "Disconnect", forget, ui["cancel"]).pack(side="left", padx=4)
    tk.Label(top, bg=ui["bg"], fg=ui["dim"], font=("Segoe UI", 9), justify="left", wraplength=600,
             text="What is shared: transactions, dividends, companies, accounts (owner/broker/code), the price history and the warning days. "
                  "Not shared: broker statements, Google Sheet settings, the 'check against broker' notes. A change made on either side "
                  "reaches the other within a few minutes; if both change the same row, the newest change wins.").pack(padx=18, pady=(10, 0))
    top.bind("<Escape>", lambda e: top.destroy())
    show()
