"""NumberBook - your phone numbers with a name, who answers, comments, a link and addresses; paste them in from hitta.se;
the same book on the PC and on the phone, kept equal by live sync (codes: public / family / me, or your own server).

EVERYTHING INSIDE THIS PROGRAM IS ENGLISH (code, comments, UI, Help).  The only non-English things are the Swedish word
tables of the paste parser in DEL 11 (words that hitta.se prints): that is DATA the parser has to match.

Built from NumberBook_template.py + nb_core.py + nb_gui.py by build_NumberBook.py, which pastes Lars's rule blocks (home,
icon, ui helpers, open, popups, about) in verbatim.  Sync talks to the relay NumberBook\\relay\\numberbook_relay.py.
"""
# ToDo: the phone app (app.numberbook) does not sync yet: it needs the same pull / merge / push steps as sync_once() in DEL 14
# (Java port, like StoryDesk); common phrases and usage counters stay local on purpose.
# ToDo: a per-number "shared with" list instead of the three levels; search in hitta.se from inside the program (needs their terms).

import os
import sys
import re
import json
import time
import shutil
import ctypes
import queue
import random
import base64
import platform
import threading
import subprocess
import webbrowser
import urllib.error
import urllib.parse
import urllib.request
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk, messagebox, filedialog

APP_NAME = "NumberBook"
APP_VERSION = "1.3"

# *************** DEL XX - PROGRAM HOME (WHERE MY DATA LIVES) *****************
# Copy verbatim into every program.  Rules, tree and table: 02_folder_tree_and_home.md
#
# Helpfiles, Icons and Folder-exe are SIBLINGS of Py, never children.  The home
# is COMPUTED, never hardcoded, so Py\<Name>.py and Folder-exe\<Name>\<Name>.exe
# find exactly the same data.
#
# Needs:  import os, sys


def _find_home(start):
    """Walk up (at most 4 levels) to the first folder that contains Helpfiles."""
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    # BOOTSTRAP: before Helpfiles exists the walk finds nothing, and returning
    # `start` would create Helpfiles as a CHILD of Py - every later run would
    # then find that wrong one first and never correct itself.  Py and
    # Folder-exe\<Name> are always direct children of the home, so their names
    # are enough to place the home correctly.
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    up_one = os.path.dirname(start)
    if os.path.basename(up_one).lower() == "folder-exe":
        return os.path.dirname(up_one)
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower scans for this line

# Name of this program = name of the .py (or of the .exe when built).  It is
# also the name of the data folder and of the icon, and it is computed so that
# a renamed file can never go out of sync with them.
PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False)
    else os.path.abspath(__file__)))[0]

BASE_DIR       = _program_home()
HELPFILES_DIR  = os.path.join(BASE_DIR, "Helpfiles")
PROGRAM_HF_DIR = os.path.join(HELPFILES_DIR, PROGRAM_NAME)   # own data
LOG_DIR        = os.path.join(HELPFILES_DIR, "0---Empty")    # logs ONLY
ICON_DIR       = os.path.join(BASE_DIR, "Icons")             # <PROGRAM_NAME>.ico


# *************** DEL XX - WINDOW ICON (EXTERNAL .ICO) ************************
# Copy verbatim into every program.  Rules and pitfalls: 10_icons.md
#
# The icon is an EXTERNAL file:  <home>\Icons\<PROGRAM_NAME>.ico
# It is never embedded in the program and never generated by it.  If the file
# is missing the program just runs with the default icon.
#
# Needs:  import ctypes, os, platform
#         block_home.py  (PROGRAM_NAME, ICON_DIR)
#
# In main():
#     _set_app_id()                                   # BEFORE tk.Tk()
#     root = tk.Tk()
#     root.title("...")
#     ... build the UI ...
#     root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
#     root.mainloop()


def _set_app_id():
    """Own taskbar group and icon for this program.  Call BEFORE tk.Tk()."""
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "MyOrg." + PROGRAM_NAME + ".1")
    except Exception:
        pass


def _find_icon_path() -> str:
    """<home>\\Icons\\<name>.ico, else the old place next to the .py, else ""."""
    name = PROGRAM_NAME + ".ico"
    here = os.path.dirname(os.path.abspath(globals().get("__file__", "")))
    for d in (ICON_DIR, os.path.join(here, "Icons")):
        p = os.path.join(d, name)
        if os.path.isfile(p):
            return p
    return ""


def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    ico_path = _find_icon_path()
    if not ico_path:
        return

    # Channel 1: tkinter's own API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Channel 2: WM_SETICON via Win32 (taskbar and Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        # winfo_id() is tkinter's inner frame; its PARENT is the real Win32
        # window.  FindWindowW by title is the fallback (it can pick the wrong
        # window if two windows share a title).
        hwnd = user32.GetParent(root.winfo_id()) or \
               user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON, 0, 0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


# *************** DEL XX - UI HELPERS (NO BLINK, MODAL DIALOGS) ***************
# Copy verbatim into every program.  Rules: 01_CORE_always_read.md, section 5.
#
# NO BLINKING CURSORS ANYWHERE.  Use tk.Entry / tk.Text (never ttk.Entry) and set
# the values PER WIDGET when it is created - also in Toplevel dialogs and log
# windows.  Do not rely on option_add.
#
# Needs:  import tkinter as tk

NO_BLINK = dict(insertofftime=0, insertontime=9999999)


def new_entry(parent, **kw):
    """tk.Entry with a fixed (non-blinking) cursor."""
    return tk.Entry(parent, **{**NO_BLINK, **kw})


def new_text(parent, **kw):
    """tk.Text with a fixed (non-blinking) cursor."""
    return tk.Text(parent, **{**NO_BLINK, **kw})


def no_blink(w):
    """Fix the cursor of a widget that already exists.  Returns the widget."""
    try:
        w.configure(**NO_BLINK)
    except Exception:
        pass
    return w


def make_modal(top, on_escape=None):
    """Every Toplevel dialog: grab_set(), focus_force(), <Escape> - in that order.

    on_escape is called instead of top.destroy() when Escape is pressed.
    A dialog opened on top of another modal one takes the grab; when it is
    destroyed the grab goes back to the dialog underneath (otherwise that one
    stops answering the mouse)."""
    try:
        below = top.grab_current()    # the modal window we are about to cover
    except Exception:
        below = None
    try:
        top.grab_set()
    except Exception:
        pass                      # window not viewable yet - not fatal
    try:
        top.focus_force()
    except Exception:
        pass
    top.bind("<Escape>", lambda e: (on_escape or top.destroy)())

    def _give_back(e):
        if e.widget is top and below is not None:
            try:
                if below.winfo_exists():
                    below.grab_set()
            except Exception:
                pass
    top.bind("<Destroy>", _give_back, add="+")


def continue_button(parent, text, command, **kw):
    """The "Continue" / "OK" / "Next" button of a game: reacts to a mouse click,
    Enter (also the numpad one) AND Space - always, whichever widget has focus.

    Returns the tk.Button; the caller packs/grids it.  The keys are bound on the
    button's own window and only act while the button exists and is on screen,
    so an old Continue can never fire from a later screen.  Enter/Space are
    left alone while the player is typing (Entry, Text, Combobox ...).  The
    button takes focus and also handles the keys itself (stopping tk's own Space
    handling, so nothing fires twice); the window binding covers every other
    focus, and steps aside for a DIFFERENT focused button (Space presses that)."""

    def go(event=None):
        if not btn.winfo_exists() or not btn.winfo_ismapped():
            return
        if str(btn.cget("state")) == "disabled":
            return
        command()

    def key(event):
        w = btn.focus_get()
        cls = w.winfo_class() if w is not None else ""
        if cls in ("Entry", "Text", "TEntry", "TCombobox", "Spinbox", "Listbox"):
            return                                   # the player is typing
        if (event.keysym == "space" and w is not btn
                and cls in ("Button", "TButton", "Checkbutton", "Radiobutton")):
            return                                   # tk presses that other button
        go()
        return "break"

    btn = tk.Button(parent, text=text, command=go, **kw)
    top = btn.winfo_toplevel()
    seqs = ("<Return>", "<KP_Enter>", "<space>")
    ids = [(seq, top.bind(seq, key, add="+")) for seq in seqs]
    for seq in seqs:                     # focus on the button itself
        btn.bind(seq, lambda e: (go(), "break")[1])

    def cleanup(e):
        if e.widget is btn:
            for seq, fid in ids:
                try:
                    top.unbind(seq, fid)
                except Exception:
                    pass
    btn.bind("<Destroy>", cleanup, add="+")
    btn.focus_set()
    return btn


# *************** DEL XX - OPEN THINGS WITH MY OWN PROGRAMS *******************
# Copy verbatim.  A link, folder, PDF, log or image opened from here lands in MY
# programs, not in Edge / Explorer / Notepad / Adobe.  Rules and the reasons
# behind them: 20_open_with_my_programs.md
#
# Which program opens WHAT is decided in ONE file, never in code:
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
# _FALLBACK_KINDS is used only when that file cannot be read.
#
# Three rules this block must never break:
#   1. It may NEVER raise (Help must open even if WhyBrowse or the table is gone).
#   2. It may NEVER hand a thing to ITSELF (that is how you build a loop).
#   3. Popen, never run() (run() would freeze this program).
# And NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it starts another copy of this program (fork bomb, 2026-09-04).
#
# The table is read ONCE, the first time something is opened - not at start-up.
#
# Needs:  import os, sys, json, shutil, subprocess, webbrowser
#         block_home.py  (_program_home, PROGRAM_NAME)

MY_PROGRAM_NAME = PROGRAM_NAME

# Only used when DefaultHub's table cannot be read.  Same shape as the file.
_FALLBACK_KINDS = {
    "url":    {"match_type": "protocol", "match": ["http://", "https://"],
               "target_type": "suite", "target": "WhyBrowse"},
    "mail":   {"match_type": "protocol", "match": ["mailto:"],
               "target_type": "suite", "target": "F(re)email"},
    "folder": {"match_type": "folder", "match": [],
               "target_type": "suite", "target": "File_manager"},
    "pdf":    {"match_type": "extension", "match": [".pdf"],
               "target_type": "suite", "target": "PDFull"},
    "text":   {"match_type": "extension",
               "match": [".txt", ".log", ".md", ".csv", ".ini", ".cfg",
                         ".json", ".xml", ".py", ".nfo", ".srt", ".bat",
                         ".ps1"],
               "target_type": "suite", "target": "Meditor"},
    "image":  {"match_type": "extension",
               "match": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
                         ".tif", ".tiff", ".ico"],
               "target_type": "suite", "target": "SeeView"},
}
_HUB_KINDS = None


def _my_app_roots() -> list:
    """Trees to look in, nearest first.

    My own home is not always the tree that holds the other programs: a music
    program's home is 1---Musik, and Chess / Foul_bridge / Quiz_manager /
    Railroad_racing are their own worlds - none of those has a WhyBrowse or a
    DefaultHub.  So after its own home this walks UP, four levels, like
    _find_home."""
    roots, d = [], _program_home()
    for _ in range(4):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return roots


def _hub_kinds() -> dict:
    """DefaultHub's table, read once and remembered."""
    global _HUB_KINDS
    if _HUB_KINDS is not None:
        return _HUB_KINDS
    kinds = {}
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    kinds = (json.load(fh) or {}).get("kinds") or {}
                break
        except Exception:
            pass                       # unreadable or half-written: fall back
    _HUB_KINDS = kinds if isinstance(kinds, dict) and kinds else _FALLBACK_KINDS
    return _HUB_KINDS


def _target_for(thing, is_folder: bool = False) -> str:
    """Which of my programs opens this?  "" means: let Windows decide."""
    low = str(thing).lower()
    ext = "" if is_folder else os.path.splitext(low)[1]
    for k in (_hub_kinds() or {}).values():
        try:
            mt = k.get("match_type")
            match = [str(m).lower() for m in (k.get("match") or [])]
            if mt == "folder":
                hit = is_folder
            elif mt == "protocol":
                hit = (not is_folder) and any(low.startswith(m) for m in match)
            elif mt == "extension":
                hit = bool(ext) and ext in match
            else:
                hit = False
            if hit:
                if k.get("target_type") == "suite":
                    return str(k.get("target") or "")
                return ""              # "system" - deliberately Windows' job
        except Exception:
            continue
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of my .py programs with, or "".

    A 0-byte file is an App Execution Alias
    (%LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe and friends) - not an
    interpreter - and which() finds it first wherever the Store stub is on PATH."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
        cands.append(sys.executable)
    cands.append(shutil.which("pythonw"))
    cands.append(shutil.which("python"))
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs",
                        "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            cands.append(os.path.join(base, d, "pythonw.exe"))
    except OSError:
        pass
    for c in cands:
        try:
            if c and os.path.isfile(c) and os.path.getsize(c) > 0:
                return c
        except OSError:
            pass
    return ""


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, a build is only the fallback: the .py is the file that is
    actually edited, so it is always current, while a build can be days old
    (2026-09-05: File_manager's build had no command-line handling at all).
    A build is used only when there is no source or no interpreter."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    cmd = work = None
    for home in _my_app_roots():
        script = os.path.join(home, "Py", name + ".py")
        exe = os.path.join(home, "Folder-exe", name, name + ".exe")
        if os.path.isfile(script):
            pyw = _real_pythonw()
            if pyw:
                cmd, work = [pyw, script, str(argument)], os.path.dirname(script)
                break
        if os.path.isfile(exe):           # no source, or no interpreter
            cmd, work = [exe, str(argument)], os.path.dirname(exe)
            break
        if os.path.isfile(script):
            break                         # found the tree; do not look further
    if not cmd:
        return False
    try:
        subprocess.Popen(cmd, cwd=work or None)
        return True
    except Exception:
        return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass


# *************** DEL xx - TOOL POPUPS: MOVABLE, ZOOMABLE, NON-MODAL **********
# block_popups.py - copy verbatim into a program (needs: import os, tkinter as tk,
# tkinter.font as tkfont).  Two parts:
#
#   ToolPopup   a window beside the main window that you can DRAG, ZOOM (the
#               [-] 100% [+] bar, or Ctrl+mouse wheel), and close with Esc.
#               Position, zoom and "is it open" live in the PROGRAM'S OWN
#               settings dict (`store`), under three key names the program
#               picks - so they survive a restart.  Subclass it and write
#               build(self, s): s is the zoom as a float (1.0 = 100 %).  Draw
#               into self.body, or call self.canvas_area(w, h) and draw on the
#               canvas it returns (it gets a scrollbar by itself when the
#               screen is too small for the whole thing).
#
#   PlayerTextPopup  the PLAYER'S OWN TEXT, written and saved inside the program
#               (tactics, house rules, "good to remember").  Every file
#               <Helpfiles>\<program>\Playertext-<name>.txt is one text; what
#               follows the prefix is what the drop-down offers; the chosen text
#               is shown in a box with scrollbars + mouse wheel and can be edited
#               right there (saved by itself a second after the last key, and
#               when the popup closes or another text is picked).  [New...]
#               starts another text.  Nothing is ever deleted by the program.
#               An empty text never creates a file.  Call .save_now() from the
#               program's own on_close.
#
# The program supplies:
#   store      its settings dict (mutated in place)
#   keys       (show_key, pos_key, zoom_key) for a ToolPopup, e.g. ("show_aid","popup_pos","popup_zoom");
#              (show_key, pos_key, zoom_key, sel_key) for PlayerTextPopup, e.g.
#              ("show_playertext","playertext_pos","playertext_zoom","playertext_sel")
#              NB: pick names that do not collide with a text-key prefix the
#              program's self-test scans for (a "aid_*" setting broke one).
#   on_change  callable that saves the settings (e.g. lambda: save_settings(S))
#   theme      dict: bg panel fg dim accent btn btnfg field field_fg
#   on_closed  callable run after the popup closed itself (tick boxes off ...)
#   on_key     optional; Space/Enter forwarded to the game ("Play").  NEVER for
#              the notes popup - it is typed into.
#
# Open it once at start-up for a game's aid (show_key true), open the player
# text from a menu / button.  The main window keeps working: nothing here grabs input.

POPUP_ZOOMS = (50, 60, 70, 80, 90, 100, 115, 130, 150)


def popup_lines(font, texts, width):
    """How many lines the LONGEST of `texts` needs at `width` px (greedy word
    wrap).  Gives a label one fixed height whatever the language
    (01_CORE item 6)."""
    best = 1
    for t in texts:
        lines = 0
        for para in t.split("\n"):
            cur, n = "", 1
            for w in para.split():
                trial = (cur + " " + w).strip()
                if cur and font.measure(trial) > width:
                    n += 1
                    cur = w
                else:
                    cur = trial
            lines += n
        best = max(best, lines)
    return best


class ToolPopup(object):
    resizable = False

    def __init__(self, root, store, keys, on_change, theme, title,
                 on_closed=None, on_key=None):
        self.root, self.store, self.theme = root, store, theme
        self.k_show, self.k_pos, self.k_zoom = keys
        self.on_change, self.on_closed = on_change, on_closed
        self.move_job = None
        self._cv = self._bar = None
        self._full_h = 0
        top = self.top = tk.Toplevel(root)
        top.title(title)
        top.configure(bg=theme["bg"])
        top.resizable(self.resizable, self.resizable)
        top.transient(root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", lambda e: self.close())
        top.bind("<Control-MouseWheel>",
                 lambda e: self.step(1 if e.delta > 0 else -1))
        if on_key:
            for key in ("<Return>", "<KP_Enter>", "<space>"):
                top.bind(key, lambda e: on_key())
        bar = self.toolbar = tk.Frame(top, bg=theme["panel"])
        bar.pack(fill="x")
        self._btn(bar, u"−", lambda: self.step(-1)).pack(
            side="left", padx=(6, 0), pady=3)
        self.lbl_zoom = tk.Label(bar, width=5, bg=theme["panel"],
                                 fg=theme["fg"], font=("Segoe UI", 9, "bold"))
        self.lbl_zoom.pack(side="left")
        self._btn(bar, "+", lambda: self.step(1)).pack(side="left")
        self._btn(bar, "100%", lambda: self.set_zoom(100), w=5).pack(
            side="left", padx=(6, 0))
        self.extra_toolbar(bar)
        self.body = tk.Frame(top, bg=theme["bg"])
        self.body.pack(fill="both", expand=True)
        self._rebuild()
        self._place(store.get(self.k_pos))
        top.bind("<Configure>", self._configured)

    # ---- for subclasses ------------------------------------------------------
    def build(self, s):
        raise NotImplementedError

    def extra_toolbar(self, bar):
        pass

    def before_rebuild(self):
        pass

    def before_close(self):
        pass

    # ---- zoom ----------------------------------------------------------------
    def zoom(self):
        z = self.store.get(self.k_zoom, 100)
        return z if z in POPUP_ZOOMS else 100

    def step(self, d):
        i = POPUP_ZOOMS.index(self.zoom()) + d
        self.set_zoom(POPUP_ZOOMS[max(0, min(len(POPUP_ZOOMS) - 1, i))])

    def set_zoom(self, z):
        if z == self.zoom():
            return
        self.store[self.k_zoom] = z
        self.on_change()
        self._rebuild()
        self._place(self._where())          # the size changed: stay on screen

    def _btn(self, parent, text, cmd, w=3):
        th = self.theme
        return tk.Button(parent, text=text, command=cmd, width=w, bd=0,
                         relief="flat", bg=th["btn"], fg=th["btnfg"],
                         activebackground=th["accent"], takefocus=0,
                         cursor="hand2", font=("Segoe UI", 9, "bold"))

    def _rebuild(self):
        self.before_rebuild()
        for w in self.body.winfo_children():
            w.destroy()
        self._cv = None
        self.lbl_zoom.configure(text="%d%%" % self.zoom())
        self.build(self.zoom() / 100.0)
        self.top.update_idletasks()
        self._fit()

    # ---- a canvas that scrolls only when the screen is too small --------------
    def canvas_area(self, w, h):
        th = self.theme
        frame = tk.Frame(self.body, bg=th["bg"])
        frame.pack(padx=6)
        cv = tk.Canvas(frame, width=w, height=h, bg=th["bg"], bd=0,
                       highlightthickness=0, scrollregion=(0, 0, w, h))
        cv.pack(side="left")
        bar = tk.Scrollbar(frame, command=cv.yview, bg=th["panel"])
        cv.configure(yscrollcommand=bar.set)
        cv.bind("<MouseWheel>", lambda e: cv.yview_scroll(
            -1 if e.delta > 0 else 1, "units"))
        self._cv, self._bar, self._full_h = cv, bar, h
        return cv

    def resize_canvas(self, h):
        """The drawing is finished and turned out `h` px high."""
        h = int(h)
        w = int(self._cv.cget("width"))
        self._cv.configure(height=h, scrollregion=(0, 0, w, h))
        self._full_h = h

    def _fit(self):
        cv = self._cv
        if cv is None:
            return
        cv.configure(height=self._full_h)
        self._bar.pack_forget()
        self.top.update_idletasks()
        excess = self.top.winfo_reqheight() - (self.top.winfo_screenheight() - 90)
        if excess > 0:
            cv.configure(height=max(240, self._full_h - excess))
            self._bar.pack(side="left", fill="y")

    # ---- position ------------------------------------------------------------
    def _where(self):
        return [self.top.winfo_x(), self.top.winfo_y()]

    def _place(self, pos):
        top, root = self.top, self.root
        top.update_idletasks()
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        w, h = top.winfo_reqwidth(), top.winfo_reqheight()
        ok = (isinstance(pos, (list, tuple)) and len(pos) == 2
              and all(isinstance(v, int) for v in pos)
              and -w + 60 < pos[0] < sw - 60 and 0 <= pos[1] < sh - 60)
        if ok:
            x, y = pos
            x = min(x, max(0, sw - w)) if x + w > sw + 40 else x
        else:                               # default: right of the main window
            root.update_idletasks()
            x = root.winfo_x() + root.winfo_width() + 8
            y = root.winfo_y()
            if x + w > sw:                  # no room: hug the screen edge
                x = max(0, sw - w)
            y = max(0, min(y, sh - h - 40))
        top.geometry("+%d+%d" % (x, y))

    def _configured(self, event):
        if event.widget is not self.top:
            return
        if self.move_job:
            self.top.after_cancel(self.move_job)
        self.move_job = self.top.after(400, self._moved)

    def _moved(self):
        self.move_job = None
        try:
            self.store[self.k_pos] = [int(v) for v in self._where()]
            self.on_change()
        except Exception:
            pass

    def retitle(self, title):
        self.top.title(title)

    def close(self):
        try:
            self.before_close()
        except Exception:
            pass
        if self.move_job:
            try:
                self.top.after_cancel(self.move_job)
            except Exception:
                pass
        try:
            self.top.destroy()
        except Exception:
            pass
        self.store[self.k_show] = False
        self.on_change()
        if self.on_closed:
            self.on_closed()


PLAYERTEXT_PREFIX = "Playertext-"
PLAYERTEXT_DEFAULT_LABELS = {
    "hint": "Your own text - saved by itself as Playertext-<name>.txt in the "
            "program's Helpfiles folder.  Every such file there can be picked above.",
    "folder": "Folder", "new": "New...", "wrap": "Wrap",
    "newname": "Name of the new text (tactics, remember, house rules ...):",
    "ok": "OK", "cancel": "Cancel"}


def playertext_names(folder):
    """The <name> of every Playertext-<name>.txt in `folder`, sorted.  A
    Notes.txt from the first version of this block becomes Playertext-Notes.txt."""
    try:
        old, new = (os.path.join(folder, "Notes.txt"),
                    os.path.join(folder, PLAYERTEXT_PREFIX + "Notes.txt"))
        if os.path.isfile(old) and not os.path.exists(new):
            os.replace(old, new)
    except OSError:
        pass
    out = []
    try:
        for n in os.listdir(folder):
            if (n.lower().startswith(PLAYERTEXT_PREFIX.lower())
                    and n.lower().endswith(".txt")
                    and len(n) > len(PLAYERTEXT_PREFIX) + 4):
                out.append(n[len(PLAYERTEXT_PREFIX):-4])
    except OSError:
        pass
    return sorted(out, key=lambda s: s.lower())


def playertext_clean(name):
    """A name that is safe in a file name (no \\ / : * ? " < > |)."""
    bad = '<>:"/\\|?*'
    name = "".join(c for c in name if c not in bad and ord(c) >= 32)
    return name.strip().strip(".")[:40]


class PlayerTextPopup(ToolPopup):
    """The player's own text, written and saved INSIDE the program: tactics,
    house rules, things to remember.  Every file
    <Helpfiles>/<program>/Playertext-<name>.txt is one text; the part after
    the prefix is what the drop-down offers, and the chosen one is shown in a
    box with a scrollbar and mouse-wheel scrolling (and a horizontal bar when
    "Wrap" is off).  Typing saves by itself a second later and on close/switch.
    [New...] starts another text.  Nothing is ever deleted by the program.
    keys = (show_key, pos_key, zoom_key, selected_name_key)
    labels() -> dict with any of PLAYERTEXT_DEFAULT_LABELS' keys (a language
    switch calls relabel() which asks again).  Call .save_now() from the
    program's own on_close."""
    resizable = True

    def __init__(self, root, store, keys, on_change, theme, title, folder,
                 labels, on_closed=None, default_name="Notes"):
        self.folder, self.labels = folder, labels
        self.k_sel = keys[3]
        self.txt = self.hbar = self.btn_folder = self.lbl_status = None
        self.save_job = None
        self.dirty = False
        self.saved = None                   # None = no file yet
        names = playertext_names(folder)
        sel = store.get(self.k_sel)
        self.name = sel if sel in names else (names[0] if names else default_name)
        self.content = self._read(self.name)
        self.wrap = None
        ToolPopup.__init__(self, root, store, keys[:3], on_change, theme,
                           title, on_closed)
        self.wrap = self.wrap or tk.BooleanVar(value=True)
        self.top.after(80, self._focus)

    def _l(self, key):
        try:
            return self.labels().get(key) or PLAYERTEXT_DEFAULT_LABELS[key]
        except Exception:
            return PLAYERTEXT_DEFAULT_LABELS[key]

    def _path(self, name=None):
        return os.path.join(self.folder,
                            PLAYERTEXT_PREFIX + (name or self.name) + ".txt")

    def _focus(self):
        try:
            self.txt.focus_set()
        except Exception:
            pass

    def _read(self, name):
        self.saved = None
        self.dirty = False
        try:
            if os.path.isfile(self._path(name)):
                with open(self._path(name), encoding="utf-8-sig",
                          errors="replace") as fh:
                    text = fh.read()
                self.saved = text
                return text
        except Exception:
            pass
        return ""

    def extra_toolbar(self, bar):
        self.btn_folder = self._btn(bar, self._l("folder"), self._open_folder,
                                    w=8)
        self.btn_folder.pack(side="right", padx=6)

    def _open_folder(self):
        try:
            os.makedirs(self.folder, exist_ok=True)
            os.startfile(self.folder)
        except Exception:
            pass

    def before_rebuild(self):
        if self.txt is not None:
            try:
                self.content = self.txt.get("1.0", "end-1c")
            except Exception:
                pass

    def build(self, s):
        th = self.theme
        if self.wrap is None:
            self.wrap = tk.BooleanVar(value=True)
        row = tk.Frame(self.body, bg=th["bg"])
        row.pack(fill="x", padx=6, pady=(6, 0))
        tk.Label(row, text=PLAYERTEXT_PREFIX, bg=th["bg"], fg=th["dim"],
                 font=("Segoe UI", 9)).pack(side="left")
        names = playertext_names(self.folder)
        if self.name not in names:
            names = sorted(names + [self.name], key=lambda x: x.lower())
        self.var_name = tk.StringVar(value=self.name)
        om = tk.OptionMenu(row, self.var_name, *names, command=self._picked)
        om.configure(bg=th["btn"], fg=th["btnfg"], activebackground=th["accent"],
                     highlightthickness=0, bd=0, relief="flat", takefocus=0,
                     font=("Segoe UI", 9, "bold"), cursor="hand2")
        om["menu"].configure(bg=th["btn"], fg=th["btnfg"],
                             activebackground=th["accent"],
                             font=("Segoe UI", 9))
        om.pack(side="left")
        self._btn(row, self._l("new"), self._new, w=8).pack(side="left", padx=6)
        tk.Checkbutton(row, text=self._l("wrap"), variable=self.wrap,
                       command=self._wrap_changed, bg=th["bg"], fg=th["fg"],
                       selectcolor=th["panel"], activebackground=th["bg"],
                       activeforeground=th["accent"], highlightthickness=0,
                       takefocus=0, font=("Segoe UI", 9)).pack(side="right")
        box = tk.Frame(self.body, bg=th["panel"])
        box.pack(fill="both", expand=True, padx=6, pady=(4, 2))
        box.grid_rowconfigure(0, weight=1)
        box.grid_columnconfigure(0, weight=1)
        vbar = tk.Scrollbar(box, orient="vertical", bg=th["panel"])
        self.hbar = tk.Scrollbar(box, orient="horizontal", bg=th["panel"])
        self.txt = tk.Text(
            box, width=46, height=18, undo=True, bd=0, highlightthickness=0,
            padx=8, pady=6, bg=th["field"], fg=th["field_fg"],
            insertbackground=th["field_fg"], insertofftime=0,
            insertontime=1000,                           # no blinking cursor
            wrap="word" if self.wrap.get() else "none",
            font=("Segoe UI", max(7, int(round(10 * s)))),
            yscrollcommand=vbar.set, xscrollcommand=self.hbar.set)
        self.txt.grid(row=0, column=0, sticky="nsew")
        vbar.grid(row=0, column=1, sticky="ns")
        vbar.configure(command=self.txt.yview)
        self.hbar.configure(command=self.txt.xview)
        self._wrap_changed()
        self.txt.insert("1.0", self.content)
        self.txt.edit_modified(False)
        self.txt.edit_reset()

        def modified(e):
            if self.txt.edit_modified():
                self.txt.edit_modified(False)
                self._changed()
        self.txt.bind("<<Modified>>", modified)
        self.lbl_status = tk.Label(self.body, anchor="w", justify="left",
                                   bg=th["bg"], fg=th["dim"],
                                   font=("Segoe UI", 8), wraplength=420,
                                   text=self._l("hint"))
        self.lbl_status.pack(fill="x", padx=8, pady=(0, 4))

    def _wrap_changed(self):
        on = self.wrap.get()
        self.txt.configure(wrap="word" if on else "none")
        if on:
            self.hbar.grid_forget()
        else:
            self.hbar.grid(row=1, column=0, sticky="ew")

    def _picked(self, name):
        if name != self.name:
            self._switch(name)

    def _switch(self, name):
        self.save_now()
        self.txt = None                     # do not cache the old text
        self.name = name
        self.content = self._read(name)
        self.store[self.k_sel] = name
        self.on_change()
        self._rebuild()
        self._focus()

    def _new(self):
        th = self.theme
        self.save_now()
        dlg = tk.Toplevel(self.top)
        dlg.title(self._l("new"))
        dlg.transient(self.top)
        dlg.configure(bg=th["bg"])
        dlg.resizable(False, False)
        tk.Label(dlg, text=self._l("newname"), bg=th["bg"], fg=th["fg"],
                 font=("Segoe UI", 9)).pack(padx=14, pady=(12, 4))
        var = tk.StringVar()
        ent = tk.Entry(dlg, textvariable=var, width=30, bd=0,
                       bg=th["field"], fg=th["field_fg"],
                       insertbackground=th["field_fg"], insertofftime=0,
                       insertontime=1000, font=("Segoe UI", 10))
        ent.pack(padx=14, ipady=3)

        def ok(event=None):
            nm = playertext_clean(var.get())
            dlg.destroy()
            if nm:
                existing = {n.lower(): n for n in playertext_names(self.folder)}
                self._switch(existing.get(nm.lower(), nm))
        row = tk.Frame(dlg, bg=th["bg"])
        row.pack(pady=10)
        self._btn(row, self._l("ok"), ok, w=8).pack(side="left", padx=4)
        self._btn(row, self._l("cancel"), dlg.destroy, w=8).pack(side="left",
                                                                  padx=4)
        dlg.bind("<Return>", ok)
        dlg.bind("<Escape>", lambda e: dlg.destroy())
        dlg.update_idletasks()
        dlg.geometry("+%d+%d" % (self.top.winfo_x() + 40, self.top.winfo_y() + 80))
        dlg.grab_set()
        ent.focus_force()

    def _changed(self):
        self.dirty = True
        if self.save_job:
            self.top.after_cancel(self.save_job)
        self.save_job = self.top.after(1000, self.save_now)

    def save_now(self):
        if self.save_job:
            try:
                self.top.after_cancel(self.save_job)
            except Exception:
                pass
            self.save_job = None
        if self.txt is None or not self.dirty:
            return
        try:
            text = self.txt.get("1.0", "end-1c")
        except Exception:
            return
        self.content = text
        if self.saved is None and not text.strip():
            self.dirty = False              # an empty text never makes a file
            return
        try:
            os.makedirs(self.folder, exist_ok=True)
            tmp = self._path() + ".tmp"
            with open(tmp, "w", encoding="utf-8") as fh:
                fh.write(text)
            os.replace(tmp, self._path())
            self.saved, self.dirty = text, False
        except Exception:
            pass

    def before_close(self):
        self.save_now()

    def relabel(self, title):
        self.retitle(title)
        self.btn_folder.configure(text=self._l("folder"))
        self._rebuild()


# *************** DEL XX - ABOUT DIALOG (TEMPLATE) ****************************
# A TEMPLATE, not verbatim: adapt look / colours / emoji / name to the program,
# but KEEP THE MESSAGE (creator, documentation link, small gift).
# NOT for games - games never carry anything tied to me (see 40_games.md; they
# name the designers instead).
#
# Rules: About closes with ESC; Toplevel order grab_set(), focus_force(), <Escape>
# (make_modal does it).  Links open through open_url(), never webbrowser directly.
# The program NAME shown here has no "Issu" part (Issus, Issu's ...); only the
# creator line keeps Lars "Issu" Olsson.
#
# Needs:  import tkinter as tk
#         block_ui_helpers.py (make_modal)   block_open.py (open_url)
#
# Call:   show_about(root, "MyProgram", "What it is, in one line", "🏢")
# Change the colours by passing colors={...} that match the program's palette.

DOC_URL     = ("https://docs.google.com/document/d/"
               "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
REVOLUT_URL = "https://revolut.me/lars72oeh"
PAYPAL_URL  = "https://paypal.me/issusbarn"
WISE_URL    = "https://wise.com/pay/me/larsdenniso"

ABOUT_COLORS = dict(bg="#1e1e2e", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa",
                    sep="#3a3a4e", box="#252535", hover="#b4d4ff")


def show_about(root, app_name, tagline, emoji="🏢", colors=None):
    """Stylish About dialog with documentation link and donation info."""
    c = {**ABOUT_COLORS, **(colors or {})}

    top = tk.Toplevel(root)
    top.title("About " + app_name)
    top.configure(bg=c["bg"])
    top.resizable(False, False)
    top.transient(root)
    make_modal(top)                              # grab_set, focus_force, Escape

    # Header
    hdr = tk.Frame(top, bg=c["bg"])
    hdr.pack(fill="x")
    tk.Label(hdr, text=emoji, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 36)).pack(pady=(18, 0))
    tk.Label(hdr, text=app_name, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 20, "bold")).pack()
    tk.Label(hdr, text=tagline, bg=c["bg"], fg=c["dim"],
             font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20)

    # Creator
    tk.Label(top, text='Created by  Lars "Issu" Olsson', bg=c["bg"], fg=c["fg"],
             font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

    def link(parent, text, url, size=9, **pack):
        lbl = tk.Label(parent, text=text, bg=parent.cget("bg"), fg=c["accent"],
                       font=("Segoe UI", size, "underline"), cursor="hand2")
        lbl.pack(**pack)
        lbl.bind("<Button-1>", lambda e: open_url(url))
        lbl.bind("<Enter>",    lambda e: lbl.configure(fg=c["hover"]))
        lbl.bind("<Leave>",    lambda e: lbl.configure(fg=c["accent"]))
        return lbl

    link(top, "📄  View documentation", DOC_URL, pady=(6, 2))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20, pady=(14, 0))

    # Donation
    # Lars's wording since 2026-11-07 (rule 30): ENGLISH in every language
    tk.Label(top, text="Focusing on us instead of cha-ching\nbut if you like " + app_name +
                       ", you are welcome to send a token of appreciation",
             bg=c["bg"], fg=c["dim"], font=("Segoe UI", 8, "italic"),
             wraplength=300, justify="center").pack(pady=(10, 6))
    box = tk.Frame(top, bg=c["box"], padx=16, pady=10)
    box.pack(fill="x", padx=20, pady=(0, 6))
    for text, url in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL),
                      ("Wise", WISE_URL)):
        link(box, text, url, pady=1)

    tk.Button(top, text="Close", width=10, command=top.destroy).pack(pady=(8, 16))
    return top


# *************** DEL 10 - SMALL TEXT TOOLS (numbers, links, lines; the same rules as the phone app's Tools.java) *****************
FIELDS = ("number", "name", "people", "group", "note", "url", "note2", "details", "numbers", "addresses", "phrases")
LIST_FIELDS = ("numbers", "addresses", "phrases")          # numbers / addresses = [{"label","value"}], phrases = [str]
LEVELS = ("public", "family", "me")                        # who may see a number: everybody with a code / family + me / only me
LEVEL_RANK = {"public": 1, "family": 2, "me": 3}
LEVEL_TEXT = {"me": "Only me", "family": "Family", "public": "Public"}

_NUMBER_RE = re.compile(r"\+?\d(?:[ \-./()]?\d){6,}")
_SHORT_RE = re.compile(r"\+?\d(?:[ \-./]?\d){2,}")       # 3+ digits: only used when a block has no ordinary number at all
_WEB_RE = re.compile(r"(?i)\b(?:https?://|www\.)[^\s<>\"']+")
_MAIL_RE = re.compile(r"[\w.+\-]+@[\w\-]+(?:\.[\w\-]+)+")


def digits(number):
    """Only the digits (and a leading +): what a dialer needs."""
    out = []
    for ch in (number or "").strip():
        if ch.isdigit() and ord(ch) < 128:
            out.append(ch)
        elif ch == "+" and not out:
            out.append(ch)
    return "".join(out)


def can_save(d):
    """An entry needs a NAME or a phone number (a person without a number is fine)."""
    return valid_number(d.get("number", "")) or bool((d.get("name") or "").strip())


def valid_number(number):
    return len(digits(number).replace("+", "")) >= 3


def num_key(number):
    """The same number written two ways gets the same key (+46 31 ... = 031 ...)."""
    d = digits(number)
    if d.startswith("+46"):
        d = "0" + d[3:]
    elif d.startswith("0046"):
        d = "0" + d[4:]
    return d.replace("+", "")


def find_number(text):
    m = _NUMBER_RE.search(text or "")
    return m.group().strip() if m else ""


def clean_url(s):
    """A typed link made openable: no spaces, https:// added when there is no scheme.  '' when it cannot be a link."""
    t = (s or "").strip()
    if not t or re.search(r"\s", t):
        return ""
    if re.match(r"(?i)https?://.+", t):
        return t
    if re.match(r"(?i)[a-z][a-z0-9+.\-]*:.*", t) and not re.match(r"(?i)[^/]+:\d+.*", t):
        return ""
    return "https://" + t if "." in t else ""


def find_url(text):
    m = _WEB_RE.search(text or "")
    return clean_url(re.sub(r"[.,;:!?)]+$", "", m.group())) if m else ""


def text_lines(text):
    """One entry per line; blank lines and doubles dropped, order kept."""
    out = []
    for s in re.split(r"\r?\n", text or ""):
        t = s.strip()
        if t and t not in out:
            out.append(t)
    return out


def parse_items(text):
    """One item per line: 'Label: value' or only the value.  The text before the first colon is a label only when it is short and has no digit
    ('Reception: 031-123' splits; 'Open 08:00-17:00' does not)."""
    out = []
    for line in text_lines(text):
        c = line.find(":")
        item = None
        if 0 < c <= 24 and c < len(line) - 1:
            label = line[:c].strip()
            if label and not re.search(r"\d", label):
                item = {"label": label, "value": line[c + 1:].strip()}
        if item is None:
            item = {"label": "", "value": line}
        if item["value"] and item not in out:
            out.append(item)
    return out


def items_text(items):
    return "\n".join((i["label"] + ": " + i["value"]) if i.get("label") else i.get("value", "") for i in items or [])


def merge_text(text, more):
    """Appends the lines of 'more' that 'text' does not contain yet."""
    out = (text or "").strip()
    for line in text_lines(more):
        if line.lower() not in out.lower():
            out += ("\n" if out else "") + line
    return out


def clean_numbers(main, items):
    """The extra numbers without the main number and without doubles."""
    seen = {num_key(main)}
    out = []
    for i in items:
        k = num_key(i.get("value", ""))
        if valid_number(i.get("value", "")) and k not in seen:
            seen.add(k)
            out.append(i)
    return out


def merge_addresses(have, add):
    out = list(have)
    for a in add:
        if not any(h["value"].lower() == a["value"].lower() for h in out):
            out.append(a)
    return out


def new_id():
    return "%012x" % random.getrandbits(48)


def norm_data(d):
    """A complete, well-formed data dict (every field there, right types)."""
    d = d or {}
    out = {}
    for f in FIELDS:
        v = d.get(f)
        if f in ("numbers", "addresses"):
            lst = []
            for i in v if isinstance(v, list) else []:
                if isinstance(i, dict) and str(i.get("value", "")).strip():
                    it = {"label": str(i.get("label", "")).strip(), "value": str(i.get("value", "")).strip()}
                    if it not in lst:
                        lst.append(it)
            out[f] = lst
        elif f == "phrases":
            out[f] = [str(x).strip() for x in v if str(x).strip()] if isinstance(v, list) else []
        elif f == "url":
            out[f] = clean_url(str(v or ""))
        else:
            out[f] = str(v or "").strip()
    return out


def title_of(data):
    return data.get("name") or data.get("people") or data.get("number") or ""


# *************** DEL 11 - PASTE PARSER (hitta.se results and pages, a person line, "number  name", several at once) *****************
# What hitta.se really gives when you select and copy (looked at 2026-11-29):  a result list item copies as
#     Fineskin By Ika            <- the name twice (heading + link)
#     Fineskin By Ika
#     Högbergsgatan 66 B, Stockholm        <- street + town, no postcode
#     070-049 50 Visa            <- the number is CUT OFF until you press "Visa" on the page, then copy again
# and a whole company page copies with a lot of noise (Besöksadress, Adress, Org.nr., reviews, "Rekommenderade företag").
# The tables below are DATA the parser matches against (Swedish words on purpose); everything else in the program is English.
NOISE_LINES = {"visa", "visa nummer", "visa mer", "visa alla", "visa karta", "öppna karta", "ring", "skicka", "skicka sms", "karta", "kartor", "hitta hit",
               "vägbeskrivning", "spara", "dela", "annons", "sponsrad", "läs mer", "se fler", "mer info", "mer", "webbsida", "årsredovisningar",
               "verifierad", "·", "i", "besök hemsida", "lämna ett omdöme", "överblick", "bilder", "checkbox", "favorit", "fler uppgifter", "dölj"}
STOP_WORDS = ("kreditbetyg", "rekommenderade företag", "finansiell info", "visa bolagsdata", "källor", "fordon registrerade", "ladda upp bilder",
              "lägg till bilder")
PAGE_MARKERS = ("besöksadress", "org.nr", "bolagsdata", "överblick", "kreditbetyg")         # a whole page was copied: all of it is ONE entry
_POSTCODE_RE = re.compile(r"(?<![\d\-+/.])\b(\d{3}) ?(\d{2})\s+(?!Visa\b)([A-ZÅÄÖ][\wåäöÅÄÖéÉ\-]*(?: [A-ZÅÄÖ][\wåäöÅÄÖ\-]*)*)")
_STREET_RE = re.compile(r"^[A-ZÅÄÖa-zåäö][\wåäöÅÄÖéÉ.\-' ]*\s\d+\s?[A-Za-z]?(?:[ \-/]\d+)?(?:\s?(?:lgh|trappor|tr|vån)\.?\s?\d+)?\s*$")
_AGE_RE = re.compile(r",?\s*\d{1,3}\s*år\b")
_RATING_RE = re.compile(r"^\d(?:[.,]\d)?$|^\d+\s*omdömen?$", re.I)
_HOURS_RE = re.compile(r"(?i)\b(?:öppet|stängt|öppettider|mån|tis|ons|tors|fre|lör|sön|måndag|tisdag|onsdag|torsdag|fredag|lördag|söndag)\b")
_LABELS_NUMBER = ("telefon", "tel", "mobil", "växel", "kundtjänst", "kontakt", "fast telefon", "mobiltelefon", "direkt", "reception", "support", "boka", "bokning")
_UNIT_RE = re.compile(r"(?i)^(lägenhetsnummer|lägenhetsnr|lägenhet|lgh|våningsnummer|våning|vån|portkod|porttelefon|född|ålder|civilstånd|bor sedan)\b\.?\s*:?\s*(.*)$")
_ORG_RE = re.compile(r"(?i)^org\.?\s?(?:nr|nummer)\.?:?\s*(.*)$|^organisationsnummer:?\s*(.*)$")


def _is_noise(line):
    t = line.strip().strip("·").strip().lower()
    return (not t) or t in NOISE_LINES or bool(_RATING_RE.match(t))


def _split_blocks(text):
    text = (text or "").replace("\r\n", "\n").replace("\r", "\n").replace("\xa0", " ")
    text = re.sub(r"(?<=\S) \n(?=\S)", " ", text)            # a heading that wrapped ("Ikea \nBarkarby") is one line
    blocks, cur = [], []
    for line in text.split("\n"):
        if line.strip():
            cur.append(line.strip())
        elif cur:
            blocks.append(cur)
            cur = []
    if cur:
        blocks.append(cur)
    return blocks


def _dedupe_neighbours(lines):
    out = []
    for l in lines:
        if not out or out[-1].lower() != l.lower():
            out.append(l)
    return out


def _address_from(lines, i):
    """If lines[i] is (or ends) an address, -> (address text, how many lines were used, index of the first line used); else None."""
    line = lines[i]
    m = _POSTCODE_RE.search(line)
    if m:
        before = line[:m.start()].strip(" ,")
        if before:
            return (before + ", " + m.group(1) + " " + m.group(2) + " " + m.group(3), 1, i)
        if i > 0 and _STREET_RE.match(lines[i - 1]):
            return (lines[i - 1] + ", " + m.group(1) + " " + m.group(2) + " " + m.group(3), 2, i - 1)
        return (m.group(1) + " " + m.group(2) + " " + m.group(3), 1, i)
    # "Högbergsgatan 66 B, Stockholm"  (street, then a town)
    m2 = re.match(r"^(.+?\s\d+\s?[A-Za-z]?),\s*([A-ZÅÄÖ][\wåäöÅÄÖ\- ]+)$", line)
    if m2 and not _NUMBER_RE.search(line):
        return (line, 1, i)
    return None


def _parse_block(lines):
    """One block of lines -> a dict of fields (or None when it holds nothing usable), plus 'warn' (text) when something looks cut off."""
    lines = _dedupe_neighbours([l for l in lines])
    # the organisation number sits far down on a company page (under "Finansiell info"): take it before the cut
    org_early = ""
    for k, l in enumerate(lines):
        m = _ORG_RE.match(l)
        if m:
            org_early = (m.group(1) or m.group(2) or "").strip() or (lines[k + 1] if k + 1 < len(lines) else "")
            break
    # a whole page: stop at the first line that starts the junk (reviews, financial data ...)
    for k, l in enumerate(lines):
        low = l.lower()
        if k >= 3 and any(low.startswith(w) for w in STOP_WORDS):
            lines = lines[:k]
            break
    data = {"number": "", "name": "", "people": "", "group": "", "note": "", "url": "", "note2": "", "details": "", "numbers": [], "addresses": [], "phrases": []}
    used = set()
    warn = []
    extra = []                                    # details lines
    if org_early:
        extra.append("Org.nr: " + org_early)
    # --- labelled values ("Besöksadress" <street> <postcode town>, "Org.nr." <number>, "Telefon" <number>)
    for i, l in enumerate(lines):
        low = l.lower().strip(": ")
        if low in ("besöksadress", "adress", "postadress", "gatuadress", "leveransadress"):
            nxt = [j for j in range(i + 1, min(len(lines), i + 4)) if not _is_noise(lines[j])]
            vals = []
            for j in nxt:
                if _is_noise(lines[j]) or lines[j].lower() in ("besöksadress", "adress", "postadress", "vägbeskrivning"):
                    break
                vals.append(j)
                if _POSTCODE_RE.search(lines[j]):
                    break
            if vals:
                label = "Visit" if low == "besöksadress" else ("Post" if low in ("adress", "postadress") else "")
                data["addresses"].append({"label": label, "value": ", ".join(lines[j] for j in vals)})
                used.update(vals + [i])
        elif _ORG_RE.match(l):
            m = _ORG_RE.match(l)
            if not (m.group(1) or m.group(2) or "").strip() and i + 1 < len(lines):
                used.add(i + 1)
            used.add(i)
        elif i not in used and _UNIT_RE.match(l):
            # "Lägenhetsnummer 1201" / "Lgh: 1201" / "Lägenhetsnummer" + the value on the next line: a DETAIL of the entry - never the name, never a phone number
            m = _UNIT_RE.match(l)
            val = m.group(2).strip(" :")
            if not val and i + 1 < len(lines) and re.match(r"^(?=.*\d)[\w\-/ ]{1,12}$", lines[i + 1]) and not _is_noise(lines[i + 1]) and not _UNIT_RE.match(lines[i + 1]):
                val = lines[i + 1]
                used.add(i + 1)
            used.add(i)
            if val:
                extra.append("%s: %s" % (m.group(1)[:1].upper() + m.group(1)[1:].lower(), val))
    # --- addresses without a label
    idx = [j for j in range(len(lines)) if j not in used]           # lines already taken (Lägenhetsnummer ..., labelled addresses) do not sit between a street and its postcode
    view = [lines[j] for j in idx]
    for k in range(len(view)):
        a = _address_from(view, k)
        if a:
            addr, n, first = a
            if not any(x["value"].lower() == addr.lower() for x in data["addresses"]):
                data["addresses"].append({"label": "", "value": addr})
            used.update(idx[first:first + n])
    # --- numbers, links, e-mail, opening hours
    found = []
    for i, l in enumerate(lines):
        if i in used:
            continue
        low = l.lower()
        u = find_url(l)
        if u:
            if not data["url"]:
                data["url"] = u
            else:
                extra.append(l)
            used.add(i)
            continue
        mail = _MAIL_RE.search(l)
        if mail:
            extra.append("E-mail: " + mail.group())
            used.add(i)
            continue
        if _HOURS_RE.search(l) and re.search(r"\d", l):
            extra.append(l)
            used.add(i)
            continue
        m = _NUMBER_RE.search(l)
        if m:
            num = m.group().strip()
            rest = (l[:m.start()] + " " + l[m.end():]).strip()
            tail = re.sub(r"(?i)\bvisa\b", "", rest).strip(" :,;-–")
            masked = bool(re.search(r"(?i)\bvisa\b", rest))
            if masked:
                warn.append("The number %s looks cut off: press 'Visa' on hitta.se first, then copy again." % num)
            label = ""
            low_tail = tail.lower().strip(": ")
            if low_tail in _LABELS_NUMBER or (tail and len(tail) <= 24 and not re.search(r"\d", tail) and ":" in l):
                label = tail.strip(": ").capitalize()
                tail = ""
            found.append({"number": num, "label": label, "name": tail})
            used.add(i)
            continue
        if low.strip(": ") in _LABELS_NUMBER and i + 1 < len(lines) and _NUMBER_RE.search(lines[i + 1]):
            used.add(i)                                   # the label of a number on the next line
            data["_lab"] = low.strip(": ").capitalize()
    # --- no ordinary number: a SHORT one typed by hand ("Mamma 123", "Anders tel 123456"), or one hitta.se hides behind "Visa"
    if not found:
        hidden = any(l.strip().lower() in ("visa", "visa nummer") or re.search(r"(?i)\d[ \-]*\bvisa\s*$", l) or re.search(r"\d[\d \-]*[xX*•]{2,}", l) for l in lines)
        if hidden:                                    # never guess a number from half of one
            warn.append("The number is hidden: press 'Visa' on hitta.se first, then copy again.")
        for i, l in enumerate(lines):
            if hidden or i in used or _is_noise(l):
                continue
            ms = [m for m in _SHORT_RE.finditer(l) if 3 <= len(re.sub(r"\D", "", m.group())) <= 8]
            if ms:
                m = ms[-1]
                tail = (l[:m.start()] + " " + l[m.end():]).strip(" :,;-–")
                tail = re.sub(r"(?i)\b(?:tel|telefon|nr|nummer)\b\.?\s*$", "", tail).strip(" :,;-–")
                found.append({"number": m.group().strip(), "label": "", "name": tail})
                used.add(i)
                break
    for k, f in enumerate(found):
        if k == 0:
            data["number"] = f["number"]
            if f["name"] and not data["name"]:
                data["name"] = f["name"]
            elif f["label"] and not data["name"] and f["label"].lower() not in _LABELS_NUMBER:
                data["name"] = f["label"]                 # "Bengt: 070-123 45 67" - the text before the colon is the NAME, not a label
        else:
            data["numbers"].append({"label": f["label"], "value": f["number"]})
    data.pop("_lab", None)
    # --- name and group from what is left
    rest = [(i, l) for i, l in enumerate(lines) if i not in used and not _is_noise(l)]
    names = []
    for i, l in rest:
        l2 = _AGE_RE.sub("", l).strip(" ,")
        if l2:
            names.append(l2)
    if names:
        if not data["name"]:
            data["name"] = names.pop(0)
        if names:
            if not data["group"] and len(names[0]) <= 40 and not re.search(r"\d", names[0]):
                data["group"] = names.pop(0)
            extra.extend(names)
    data["name"] = re.sub(r"\s*[-|]\s*hitta\.se\s*$", "", data["name"], flags=re.I).strip()
    data["numbers"] = clean_numbers(data["number"], data["numbers"])
    data["details"] = "\n".join(dict.fromkeys(extra))
    if not data["number"] and not data["name"] and not data["addresses"]:
        return None
    data = norm_data(data)
    data["_warn"] = " ".join(warn)
    return data


def parse_paste(text):
    """Pasted text -> a list of entries (data dicts, each with '_warn' = '' or a text).  Blocks are separated by blank lines.  A block where EVERY line has
    a number ('Anders 070-123 45 67') gives one entry per line.  Nothing is added by this function; the caller shows the result."""
    out = []
    blocks = _split_blocks(text)
    if any(m in (text or "").lower() for m in PAGE_MARKERS):
        blocks = [[l for b in blocks for l in b]]
    for block in blocks:
        if len(block) > 1 and all(_NUMBER_RE.search(l) or _SHORT_RE.search(l) for l in block) and not any(_POSTCODE_RE.search(l) for l in block):
            parts = [[l] for l in block]
        else:
            parts = [block]
        for lines in parts:
            d = _parse_block(lines)
            if d:
                out.append(d)
    # one page copied as several blocks (name block, address block, number block with no name) -> one entry
    if len(out) > 1 and sum(1 for d in out if d["name"]) == 1 and sum(1 for d in out if d["number"]) <= 1:
        named = next(d for d in out if d["name"])
        for d in out:
            if d is named:
                continue
            if d["number"] and not named["number"]:
                named["number"] = d["number"]
            else:
                named["numbers"] = clean_numbers(named["number"], named["numbers"] + ([{"label": "", "value": d["number"]}] if d["number"] else []) + d["numbers"])
            named["addresses"] = merge_addresses(named["addresses"], d["addresses"])
            named["url"] = named["url"] or d["url"]
            named["details"] = merge_text(named["details"], d["details"] + ("\n" + d["name"] if d["name"] else ""))
            named["_warn"] = (named["_warn"] + " " + d["_warn"]).strip()
        out = [named]
    return out


# *************** DEL 12 - THE BOOK (records, local file, what has changed since the last sync) *****************
# A record = {"id", "level", "deleted", "data": {FIELDS}, "sync": None | {"rev", "level", "deleted", "data"}, "local": {"opens","last","added"}, "blocked": ""}
#   data   = what is shared (the FIELDS above)          local = what stays on this computer (usage counters, date added)
#   sync   = the record as the server had it at the last sync (the BASE of the 3-way merge); None = the server has never seen this record
#   a record is DIRTY (must be pushed) when it differs from its sync copy.
BOOK_FILE = os.path.join(PROGRAM_HF_DIR, "book.json")
BACKUP_DIR = os.path.join(PROGRAM_HF_DIR, "Backups")


def rec_stamp(rec):
    return json.dumps([rec["level"], rec["deleted"], rec["data"]], sort_keys=True, ensure_ascii=False)


class Book(object):
    def __init__(self, path=BOOK_FILE):
        self.path = path
        self.lock = threading.RLock()
        self.recs = {}
        self.seq = 0                  # the server's seq up to which this book has been pulled
        self.sync_url = ""            # the server this book's sync info belongs to
        self.on_change = None         # called (outside the lock is not guaranteed) after every local edit
        self.load()

    # ---- file
    def load(self):
        try:
            with open(self.path, encoding="utf-8") as fh:
                d = json.load(fh) or {}
        except (OSError, ValueError):
            return
        with self.lock:
            self.seq = int(d.get("seq") or 0)
            self.sync_url = str(d.get("sync_url") or "")
            self.recs = {}
            for r in d.get("records", []):
                if isinstance(r, dict) and r.get("id"):
                    r["data"] = norm_data(r.get("data"))
                    r.setdefault("level", "me")
                    r.setdefault("deleted", False)
                    r.setdefault("sync", None)
                    r.setdefault("blocked", "")
                    r.setdefault("local", {})
                    r["local"].setdefault("opens", 0)
                    r["local"].setdefault("last", 0)
                    r["local"].setdefault("added", int(time.time() * 1000))
                    self.recs[r["id"]] = r

    def save(self):
        with self.lock:
            d = {"v": 1, "seq": self.seq, "sync_url": self.sync_url, "records": list(self.recs.values())}
            try:
                os.makedirs(os.path.dirname(self.path), exist_ok=True)
                tmp = self.path + ".tmp"
                with open(tmp, "w", encoding="utf-8") as fh:
                    json.dump(d, fh, ensure_ascii=False, indent=1)
                os.replace(tmp, self.path)
            except OSError:
                pass

    def backup_today(self, keep=20):
        """One copy of the book file per day in Backups\\ (the newest `keep` stay)."""
        try:
            if not os.path.isfile(self.path):
                return
            os.makedirs(BACKUP_DIR, exist_ok=True)
            dst = os.path.join(BACKUP_DIR, "book_%s.json" % time.strftime("%Y-%m-%d"))
            if not os.path.exists(dst):
                shutil.copyfile(self.path, dst)
            old = sorted(n for n in os.listdir(BACKUP_DIR) if n.startswith("book_") and n.endswith(".json"))
            for n in old[:-keep]:
                os.remove(os.path.join(BACKUP_DIR, n))
        except OSError:
            pass

    # ---- reading
    def live(self):
        with self.lock:
            return [r for r in self.recs.values() if not r["deleted"]]

    def get(self, rid):
        return self.recs.get(rid)

    def find_by_number(self, number):
        k = num_key(number)
        if not k:
            return None
        with self.lock:
            for r in self.recs.values():
                if r["deleted"]:
                    continue
                if num_key(r["data"]["number"]) == k:
                    return r
        return None

    def find_same(self, d):
        """The live entry that data `d` is about: the same number; else - when `d` has a name - the entry with that name that has NO number yet
        (a person without a phone number, or one whose number is added later)."""
        if valid_number(d.get("number", "")):
            r = self.find_by_number(d["number"])
            if r is not None:
                return r
        nm = (d.get("name") or "").strip().lower()
        if not nm:
            return None
        with self.lock:
            for r in self.recs.values():
                if not r["deleted"] and not r["data"]["number"].strip() and r["data"]["name"].strip().lower() == nm:
                    return r
        return None

    @staticmethod
    def is_dirty(rec):
        s = rec.get("sync")
        if s is None:
            return True
        return rec["level"] != s["level"] or rec["deleted"] != s["deleted"] or rec["data"] != s["data"]

    # ---- local edits (these make a record dirty)
    def add(self, data, level="me"):
        with self.lock:
            rec = {"id": new_id(), "level": level if level in LEVELS else "me", "deleted": False, "data": norm_data(data), "sync": None,
                   "local": {"opens": 0, "last": 0, "added": int(time.time() * 1000)}, "blocked": ""}
            self.recs[rec["id"]] = rec
        self._changed()
        return rec

    def update(self, rid, data=None, level=None):
        with self.lock:
            r = self.recs.get(rid)
            if r is None or r["deleted"]:
                return None
            if data is not None:
                r["data"] = norm_data(data)
            if level in LEVELS:
                r["level"] = level
        self._changed()
        return r

    def delete(self, rid):
        with self.lock:
            r = self.recs.get(rid)
            if r is None:
                return
            if r["sync"] is None:
                del self.recs[rid]                 # the server never heard of it: gone for good
            else:
                r["deleted"] = True                # a tombstone until the server has it
        self._changed()

    def used(self, rid):
        with self.lock:
            r = self.recs.get(rid)
            if r:
                r["local"]["opens"] += 1
                r["local"]["last"] = int(time.time() * 1000)
        self.save()

    def _changed(self):
        self.save()
        cb = self.on_change
        if cb:
            try:
                cb()
            except Exception:
                pass

    def merge_entry(self, rid, data):
        """Adds what is new in `data` to an existing entry (numbers, addresses, text lines); nothing is overwritten."""
        with self.lock:
            r = self.recs.get(rid)
            if r is None:
                return None
            d = dict(r["data"])
            nd = norm_data(data)
            for f in ("name", "people", "group", "note", "note2", "url"):
                if not d[f] and nd[f]:
                    d[f] = nd[f]
            if not d["number"].strip() and valid_number(nd["number"]):      # a person who had no number gets one
                d["number"] = nd["number"]
                nd["number"] = ""
            d["numbers"] = clean_numbers(d["number"], d["numbers"] + ([{"label": "", "value": nd["number"]}] if nd["number"] and num_key(nd["number"]) != num_key(d["number"]) else []) + nd["numbers"])
            d["addresses"] = merge_addresses(d["addresses"], nd["addresses"])
            d["details"] = merge_text(d["details"], nd["details"])
            d["phrases"] = list(dict.fromkeys(d["phrases"] + nd["phrases"]))
        return self.update(rid, d)

    def duplicates(self):
        """Groups of live records with the same number -> [[rec, rec ...], ...]."""
        groups = {}
        with self.lock:
            for r in self.recs.values():
                if not r["deleted"]:
                    k = num_key(r["data"]["number"])
                    if k:
                        groups.setdefault(k, []).append(r)
        return [sorted(g, key=lambda r: r["local"].get("added", 0)) for g in groups.values() if len(g) > 1]

    def merge_duplicates(self, group):
        """Keeps the oldest record of the group, adds what the others have, deletes the others."""
        keep, others = group[0], group[1:]
        for o in others:
            self.merge_entry(keep["id"], o["data"])
            self.delete(o["id"])
        return keep


# *************** DEL 13 - 3-WAY MERGE (what the phone changed + what this PC changed, without losing either) *****************
def _item_key(f, i):
    return json.dumps(i, sort_keys=True, ensure_ascii=False)


def merge_list(f, base, local, remote):
    """Items present in base: kept only when BOTH sides still have them.  Items new on either side are added (remote order first, then my new ones)."""
    kb = [_item_key(f, i) for i in base]
    kl = [_item_key(f, i) for i in local]
    kr = [_item_key(f, i) for i in remote]
    out = []
    for i, k in zip(remote, kr):
        if k in kb and k not in kl:
            continue                                  # I removed it
        out.append(i)
    for i, k in zip(local, kl):
        if k not in kb and k not in kr:
            out.append(i)                             # I added it
    return out


def merge3(base, local, remote):
    """-> (merged data, [names of the fields that really clashed]).  A clash keeps the REMOTE value and writes my value into Details."""
    base, local, remote = norm_data(base), norm_data(local), norm_data(remote)
    out, clashes = {}, []
    for f in FIELDS:
        b, l, r = base[f], local[f], remote[f]
        if f in LIST_FIELDS:
            out[f] = merge_list(f, b, l, r)
        elif l == b or l == r:
            out[f] = r
        elif r == b:
            out[f] = l
        elif f == "details":
            out[f] = merge_text(r, l)
        else:
            out[f] = r
            clashes.append(f)
            out["_lost_" + f] = l
    for f in clashes:
        lost = out.pop("_lost_" + f)
        out["details"] = merge_text(out["details"], "Conflict - my %s here was: %s" % (f, lost))
    return norm_data({k: v for k, v in out.items() if k in FIELDS}), clashes


def merge_level(base_level, local_level, remote_level):
    if local_level == base_level:
        return remote_level
    if remote_level == base_level or remote_level == local_level:
        return local_level
    return max(local_level, remote_level, key=lambda x: LEVEL_RANK.get(x, 3))        # both changed it: the more private one


# *************** DEL 14 - SYNC CLIENT (talks to the relay; the same steps the phone app will use) *****************
CODE_PREFIX = "NBK1."


class NBError(Exception):
    pass


def parse_code(text):
    """'NBK1.<base64url JSON {u: address, t: token, n: name, r: role}>' (what AppSite / the Codes dialog hands out), or 'address|token' -> dict or None."""
    t = (text or "").strip()
    if t.startswith(CODE_PREFIX):
        try:
            raw = t[len(CODE_PREFIX):]
            d = json.loads(base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4)).decode("utf-8"))
            if isinstance(d, dict) and d.get("u") and d.get("t"):
                return {"url": str(d["u"]), "token": str(d["t"]), "name": str(d.get("n", "")), "role": str(d.get("r", ""))}
        except Exception:
            return None
        return None
    if "|" in t:
        u, _, k = t.partition("|")
        if u.strip().lower().startswith("http") and k.strip():
            return {"url": u.strip(), "token": k.strip(), "name": "", "role": ""}
    return None


def code_text(url, token, name, role):
    d = {"u": url, "t": token, "n": name, "r": role}
    return CODE_PREFIX + base64.urlsafe_b64encode(json.dumps(d, separators=(",", ":")).encode("utf-8")).decode("ascii").rstrip("=")


class Server(object):
    def __init__(self, url, token="", key=""):
        self.url = url.strip()
        if self.url and not self.url.endswith("/"):
            self.url += "/"
        self.token, self.key = token, key

    def call(self, method, path, body=None, timeout=25):
        """-> parsed JSON (a dict).  Raises NBError with a plain sentence."""
        h = {"Content-Type": "application/json", "User-Agent": "NumberBook"}
        if self.token:
            h["X-NB-Token"] = self.token
        if self.key:
            h["X-NB-Key"] = self.key
        data = json.dumps(body).encode("utf-8") if body is not None else None
        req = urllib.request.Request(self.url + path.lstrip("/"), data=data, method=method, headers=h)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read().decode("utf-8") or "{}")
        except urllib.error.HTTPError as e:
            try:
                why = json.loads(e.read().decode("utf-8")).get("error", "")
            except Exception:
                why = ""
            if e.code == 401:
                raise NBError("the server does not know this code (wrong or switched off)")
            if e.code == 403:
                raise NBError("not allowed: " + (why or "this code has no right to do that"))
            raise NBError("the server said %d %s" % (e.code, why))
        except (urllib.error.URLError, OSError, ValueError) as exc:
            raise NBError("no answer from the server (%s)" % getattr(exc, "reason", exc))


class SyncResult(object):
    def __init__(self):
        self.pulled = self.pushed = self.conflicts = self.removed = 0
        self.blocked = []
        self.role = ""
        self.write = False
        self.name = ""

    def text(self):
        bits = []
        if self.pulled:
            bits.append("%d fetched" % self.pulled)
        if self.pushed:
            bits.append("%d sent" % self.pushed)
        if self.conflicts:
            bits.append("%d merged" % self.conflicts)
        if self.removed:
            bits.append("%d removed" % self.removed)
        if self.blocked:
            bits.append("%d not allowed" % len(self.blocked))
        return ", ".join(bits) if bits else "nothing new"


def apply_remote(book, r, res=None):
    """One record from the server into the book (book.lock must be held).  Never loses a local edit."""
    rid = r["id"]
    loc = book.recs.get(rid)
    rdel = bool(r.get("deleted"))
    rdata = norm_data(r.get("data"))
    rsync = {"rev": r["seq"], "level": r["level"], "deleted": rdel, "data": rdata}
    if loc is None:
        if rdel:
            return
        book.recs[rid] = {"id": rid, "level": r["level"], "deleted": False, "data": rdata, "sync": rsync,
                          "local": {"opens": 0, "last": 0, "added": int(time.time() * 1000)}, "blocked": ""}
        if res:
            res.pulled += 1
        return
    if loc["sync"] and loc["sync"]["rev"] == r["seq"]:
        return                                           # this is my own push coming back
    if not Book.is_dirty(loc):
        if rdel:
            del book.recs[rid]
            if res:
                res.removed += 1
            return
        loc["level"], loc["data"], loc["deleted"], loc["sync"], loc["blocked"] = r["level"], rdata, False, rsync, ""
        if res:
            res.pulled += 1
        return
    # the local copy was changed here too
    if rdel:
        if loc["deleted"]:
            del book.recs[rid]                           # both deleted it
        else:
            loc["sync"] = rsync                          # I edited, they deleted: my edit wins (it is sent again)
            if res:
                res.conflicts += 1
        return
    if loc["deleted"]:
        loc["deleted"], loc["level"], loc["data"], loc["sync"] = False, r["level"], rdata, rsync      # I deleted, they edited: their edit wins
        if res:
            res.conflicts += 1
        return
    base = loc["sync"]["data"] if loc["sync"] else norm_data({})
    base_level = loc["sync"]["level"] if loc["sync"] else loc["level"]
    loc["data"], _ = merge3(base, loc["data"], rdata)
    loc["level"] = merge_level(base_level, loc["level"], r["level"])
    loc["sync"] = rsync
    loc["blocked"] = ""
    if res:
        res.conflicts += 1


def sync_once(book, server, log=None):
    """One full round: pull what is new, merge, push what changed here.  -> SyncResult.  Raises NBError (nothing is lost; the next round goes on)."""
    say = log or (lambda s: None)
    res = SyncResult()
    me = server.call("GET", "me")
    res.role, res.write, res.name = me.get("role", ""), bool(me.get("write")), me.get("name", "")
    with book.lock:
        if book.sync_url != server.url:                  # another server: nothing in the book is known there
            for rid in [i for i, r in book.recs.items() if r["deleted"]]:
                del book.recs[rid]
            for r in book.recs.values():
                r["sync"] = None
                r["blocked"] = ""
            book.seq, book.sync_url = 0, server.url
    # ---- pull
    since = book.seq
    while True:
        r = server.call("GET", "changes?since=%d&limit=500" % since)
        with book.lock:
            for rec in r.get("records", []):
                apply_remote(book, rec, res)
            for hid in r.get("hidden", []):
                if hid in book.recs:
                    del book.recs[hid]
                    res.removed += 1
            since = int(r.get("seq", since))
            if not r.get("more"):
                book.seq = since
        if not r.get("more"):
            break
    book.save()
    # ---- push (up to 3 rounds: a conflict is merged and sent again)
    for _round in range(3):
        if not res.write:
            break
        with book.lock:
            todo = []
            for rec in book.recs.values():
                if not Book.is_dirty(rec):
                    continue
                if rec["blocked"] and rec["blocked"].split("\x00", 1)[0] == rec_stamp(rec):
                    continue                              # the server refused exactly this version before
                todo.append({"id": rec["id"], "base": rec["sync"]["rev"] if rec["sync"] else 0, "level": rec["level"], "deleted": rec["deleted"],
                             "data": json.loads(json.dumps(rec["data"]))})
        if not todo:
            break
        again = False
        for i in range(0, len(todo), 100):
            batch = todo[i:i + 100]
            ans = server.call("POST", "push", {"records": batch})
            with book.lock:
                for item, result in zip(batch, ans.get("results", [])):
                    rec = book.recs.get(item["id"])
                    st = result.get("status")
                    if rec is None:
                        continue
                    if st == "ok":
                        rec["sync"] = {"rev": result["seq"], "level": item["level"], "deleted": item["deleted"], "data": item["data"]}
                        rec["blocked"] = ""
                        res.pushed += 1
                        if rec["deleted"] and item["deleted"]:
                            del book.recs[item["id"]]
                    elif st == "conflict":
                        cur = result.get("current")
                        if cur:
                            apply_remote(book, cur, res)
                            again = True
                        else:                             # the server has a record we did not know: take it over as the base
                            rec["sync"] = None
                    else:
                        why = result.get("why") or st
                        rec["blocked"] = rec_stamp(rec) + "\x00" + why
                        res.blocked.append((item["id"], why))
        book.save()
        if not again:
            break
    say("sync: " + res.text())
    return res


def make_code(server_url, master_key, name, role, write=None):
    """Makes a code with the owner (master) key or an owner token already set in the Server -> (token, code text)."""
    s = Server(server_url, key=master_key)
    body = {"name": name, "role": role}
    if write is not None:
        body["write"] = bool(write)
    r = s.call("POST", "invite", body)
    if not r.get("token"):
        raise NBError("the server gave an answer I cannot read")
    return r["token"], code_text(s.url, r["token"], name, role), r.get("id", "")


# *************** DEL 15 - SETTINGS *********************************************
SETTINGS_FILE = os.path.join(PROGRAM_HF_DIR, "settings.json")
DEFAULTS = {
    "sync_url": "", "sync_token": "", "sync_name": "", "sync_role": "", "sync_write": False, "auto_sync": True, "last_sync": 0,
    "made_codes": {},                     # code id -> code text, for the codes made in this program (the server never tells a token twice)
    "sort": "A-Z", "group": "All groups", "level": "All levels", "new_level": "me",
    "show_playtext": False, "playtext_pos": None, "playtext_zoom": 100, "playtext_sel": "",
}


def load_settings():
    s = dict(DEFAULTS)
    try:
        with open(SETTINGS_FILE, encoding="utf-8") as fh:
            s.update(json.load(fh) or {})
    except Exception:
        pass
    return s


def save_settings(s):
    try:
        os.makedirs(os.path.dirname(SETTINGS_FILE), exist_ok=True)
        tmp = SETTINGS_FILE + ".tmp"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(s, fh, indent=2, ensure_ascii=False)
        os.replace(tmp, SETTINGS_FILE)
    except Exception:
        pass


# *************** DEL 16 - HELP TEXT ********************************************
HELP_TEXT = """Number Book - your numbers with a name, who answers, a comment, a link and addresses.  The same book can live on your phone
(Android app "Number Book") and here, kept equal by sync.

ADD NUMBERS (the quick way: paste)
  Copy something from hitta.se (or any page, e-mail, message) and press  Paste  (or Ctrl+V anywhere in the window).
  The program finds name, number(s), address, web link, e-mail and opening hours and shows what it found.  Untick what you do
  not want, then press "Add / update".  A number that is already in the book is not added twice: what is new
  (a second number, an address, a text line) is added to the existing entry.
  On hitta.se the number is hidden behind "Visa": press it first, then copy - the program warns when a number looks cut off.
  You can also type: "0706-061616  Long-term parking Landvetter" (one per line) gives one entry per line.  Short numbers work too: "Taxi 112".
  An entry needs a NAME or a number - a person without a phone number is fine (add the number later, or paste it again: it joins the same entry).
  In the paste window you can double-click Name, Number or Address of a row and fix it before it is saved.
  Several results at once: copy the whole list; blocks separated by an empty line become separate entries.

AN ENTRY
  Number, Name, People (who answers: "Peter and Maria"), Group (a free word to filter by), Comment 1 (shown above the link),
  Link, Comment 2 (below the link), Extra numbers and Addresses (one per line, "Label: value"), Details (opening hours, door
  code ...), Phrases (messages for the phone app; {people} and {name} are filled in).  Everything saves by itself.
  Who can see it:  Only me / Family / Public  (see Sync).
  Route and Map open Google Maps for the selected address line.  Look up opens hitta.se for the number.

SYNC (live, both ways, no overwriting)
  Sync > a CODE: AppSite (or the person who runs the server) gives you a code text.  Paste it in Sync... > Code > Connect.
  There are three kinds of code:  ME (sees and changes everything and makes codes), FAMILY (sees Family + Public numbers, can change
  those), PUBLIC (sees only Public numbers, read only unless you allow writing).  A number's level decides who gets it.
  Changes travel by themselves a few seconds after you stop typing, and every 30 seconds.  If you and the phone changed the
  SAME number in the meantime the two versions are merged field by field; if both changed the same field, the other
  side's text stays and yours is put into Details as "Conflict - my name here was ...".  Nothing is lost silently.
  Delete on one side deletes on the other; if one side deleted and the other edited, the edit wins.
  OWN SERVER: any small Linux server with python3 and nginx works.  Run the installer made from numberbook_relay.py (see the
  relay README), then Sync... > Own server: address + the owner key > "Make my code and connect".  The owner key is used once
  and never saved.  With a ME code the button "Codes..." makes codes for family and the public.

TOOLS
  Merge duplicates: finds numbers that are in the book twice (for example after the first sync with a phone that had its own
  list) and joins them.  Export / Import: a plain .json file with the numbers (no sync information).
  Backups: a copy of the book is kept for every day you use the program (Helpfiles\\NumberBook\\Backups, the last 20).

Escape closes this Help.
"""


# *************** DEL 17 - MAIN WINDOW ******************************************
THEME = dict(bg="#1e1e2e", panel="#252535", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa",
             btn="#3a3a4e", btnfg="#e0e0e0", field="#14141f", field_fg="#e0e0e0",
             good="#a6e3a1", bad="#f38ba8", warn="#f9e2af")
SORTS = ("A-Z", "Newest first", "Most used", "Recently used")


class App(object):
    W, H = 1200, 760

    def __init__(self, root, book=None, settings=None):
        self.root = root
        self.S = settings if settings is not None else load_settings()
        self.book = book if book is not None else Book(BOOK_FILE)
        self.book.backup_today()
        self.book.on_change = self._on_book_changed
        self.cur = None                       # id of the entry in the editor
        self.loading = False
        self.save_job = None
        self.sync_q = queue.Queue()
        self.sync_busy = False
        self.sync_want = 0.0                  # time (time.time()) when a round should start; 0 = none planned
        self.sync_next = 0.0
        self.sync_error = ""
        self.playtext = None
        self.vars = {}
        self.texts = {}
        self._build()
        self.refresh_list()
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        root.bind("<Control-v>", self._ctrl_v)
        root.after(1000, self._tick)
        if self.connected():
            self.plan_sync(1.5)
        self._status()

    # ---- helpers ----------------------------------------------------------------------
    def connected(self):
        return bool(self.S.get("sync_url") and self.S.get("sync_token"))

    def _lbl(self, parent, text, **kw):
        return tk.Label(parent, text=text, bg=parent.cget("bg"), fg=kw.pop("fg", THEME["fg"]),
                        font=kw.pop("font", ("Segoe UI", 9)), anchor="w", **kw)

    def _btn(self, parent, text, cmd, w=12, **kw):
        return tk.Button(parent, text=text, command=cmd, width=w, bg=kw.pop("bg", THEME["btn"]), fg=kw.pop("fg", THEME["btnfg"]),
                         activebackground=THEME["accent"], relief="flat", font=("Segoe UI", 9), **kw)

    def _entry(self, parent, width, var=None, **kw):
        return new_entry(parent, width=width, textvariable=var, bg=THEME["field"], fg=THEME["field_fg"], insertbackground=THEME["field_fg"],
                         relief="flat", font=("Segoe UI", 10), **kw)

    def _text(self, parent, height, **kw):
        return new_text(parent, height=height, wrap="word", bg=THEME["field"], fg=THEME["field_fg"], insertbackground=THEME["field_fg"],
                        relief="flat", font=("Segoe UI", 10), padx=4, pady=3, undo=True, **kw)

    def _box(self, parent, title):
        return tk.LabelFrame(parent, text=" " + title + " ", bg=THEME["bg"], fg=THEME["accent"], font=("Segoe UI", 9, "bold"),
                             bd=1, relief="groove", padx=8, pady=6)

    # ---- layout ------------------------------------------------------------------------
    def _build(self):
        r = self.root
        r.title(APP_NAME + " " + APP_VERSION)
        r.configure(bg=THEME["bg"])
        r.geometry("%dx%d" % (self.W, self.H))
        r.resizable(False, False)
        style = ttk.Style()
        try:
            style.theme_use("clam")
        except Exception:
            pass
        style.configure("TCombobox", fieldbackground=THEME["field"], background=THEME["btn"], foreground=THEME["field_fg"], arrowcolor=THEME["fg"])
        style.map("TCombobox", fieldbackground=[("readonly", THEME["field"]), ("disabled", THEME["panel"])],
                  foreground=[("readonly", THEME["field_fg"]), ("disabled", THEME["dim"])],
                  selectbackground=[("readonly", THEME["field"])], selectforeground=[("readonly", THEME["field_fg"])],
                  background=[("readonly", THEME["btn"]), ("disabled", THEME["panel"])])
        r.option_add("*TCombobox*Listbox.background", THEME["field"])
        r.option_add("*TCombobox*Listbox.foreground", THEME["field_fg"])
        r.option_add("*TCombobox*Listbox.selectBackground", THEME["accent"])
        r.option_add("*TCombobox*Listbox.selectForeground", "#14141f")
        style.configure("Treeview", background=THEME["field"], fieldbackground=THEME["field"], foreground=THEME["field_fg"], rowheight=22, borderwidth=0)
        style.configure("Treeview.Heading", background=THEME["btn"], foreground=THEME["fg"], relief="flat")
        style.map("Treeview", background=[("selected", THEME["accent"])], foreground=[("selected", "#14141f")])

        top = tk.Frame(r, bg=THEME["bg"])
        top.place(x=10, y=8, width=self.W - 20, height=36)
        self.v_search = tk.StringVar()
        self.v_search.trace_add("write", lambda *a: self.refresh_list())
        self._lbl(top, "Search").pack(side="left")
        self.e_search = self._entry(top, 26, self.v_search)
        self.e_search.pack(side="left", padx=(6, 12), ipady=3)
        self._btn(top, "Paste...", self.open_paste, 9, bg=THEME["good"], fg="#14141f").pack(side="left", padx=2)
        self._btn(top, "Add...", lambda: self.open_paste(""), 8).pack(side="left", padx=2)
        self.lbl_sync = tk.Label(top, text="", bg=THEME["bg"], fg=THEME["dim"], font=("Segoe UI", 9), anchor="e", width=46)
        self.lbl_sync.pack(side="right", padx=(8, 0))
        for text, cmd, w in (("About", self.about, 7), ("Help", self.show_help, 7), ("Notes", self.open_notes, 7), ("Tools", self._tools_menu, 7),
                             ("Sync...", self.open_sync, 8)):
            b = self._btn(top, text, cmd, w)
            b.pack(side="right", padx=2)
            if text == "Tools":
                self.btn_tools = b

        left = tk.Frame(r, bg=THEME["bg"])
        left.place(x=10, y=52, width=470, height=self.H - 62)
        fr = tk.Frame(left, bg=THEME["bg"])
        fr.pack(fill="x")
        self.v_group = tk.StringVar(value=self.S["group"])
        self.v_level = tk.StringVar(value=self.S["level"])
        self.v_sort = tk.StringVar(value=self.S["sort"])
        self.cb_group = ttk.Combobox(fr, textvariable=self.v_group, state="readonly", width=16)
        self.cb_group.pack(side="left")
        self.cb_level = ttk.Combobox(fr, textvariable=self.v_level, state="readonly", width=12, values=["All levels"] + [LEVEL_TEXT[l] for l in ("me", "family", "public")])
        self.cb_level.pack(side="left", padx=6)
        self.cb_sort = ttk.Combobox(fr, textvariable=self.v_sort, state="readonly", width=14, values=SORTS)
        self.cb_sort.pack(side="left")
        for cb, key in ((self.cb_group, "group"), (self.cb_level, "level"), (self.cb_sort, "sort")):
            cb.bind("<<ComboboxSelected>>", lambda e, k=key: self._filter_changed(k))
        self.lbl_count = self._lbl(fr, "", fg=THEME["dim"])
        self.lbl_count.pack(side="right")
        cols = (("name", "Name", 240), ("number", "Number", 120), ("level", "Who", 62), ("state", "", 24))
        self.tree = ttk.Treeview(left, columns=[c[0] for c in cols], show="headings", selectmode="browse")
        for k, head, w in cols:
            self.tree.heading(k, text=head)
            self.tree.column(k, width=w, minwidth=w, stretch=(k == "name"))
        sb = tk.Scrollbar(left, command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y", pady=(6, 0))
        self.tree.pack(fill="both", expand=True, pady=(6, 0))
        self.tree.bind("<<TreeviewSelect>>", self._selected)
        self.tree.bind("<Delete>", lambda e: self.delete_current())

        right = tk.Frame(r, bg=THEME["bg"])
        right.place(x=490, y=52, width=self.W - 500, height=self.H - 62)
        self.right = right
        right.grid_columnconfigure(1, weight=1)
        row = 0

        def field(label, key, width=40, entry=True, height=2, hint=None):
            nonlocal row
            self._lbl(right, label).grid(row=row, column=0, sticky="nw", pady=3, padx=(0, 8))
            if entry:
                v = tk.StringVar()
                self.vars[key] = v
                w = self._entry(right, width, v)
                w.grid(row=row, column=1, sticky="we", pady=3, ipady=2)
                v.trace_add("write", lambda *a: self._edited())
            else:
                w = self._text(right, height)
                w.grid(row=row, column=1, sticky="we", pady=3)
                w.bind("<<Modified>>", self._text_modified)
                self.texts[key] = w
            row += 1
            return w

        self.e_number = field("Number", "number")
        self.e_name = field("Name", "name")
        self.e_people = field("People", "people")
        self.e_group = field("Group", "group")
        self._lbl(right, "Who can see it").grid(row=row, column=0, sticky="w", pady=3)
        lf = tk.Frame(right, bg=THEME["bg"])
        lf.grid(row=row, column=1, sticky="w", pady=3)
        self.v_elevel = tk.StringVar(value=LEVEL_TEXT["me"])
        self.cb_elevel = ttk.Combobox(lf, textvariable=self.v_elevel, state="readonly", width=14, values=[LEVEL_TEXT[l] for l in ("me", "family", "public")])
        self.cb_elevel.pack(side="left")
        self.cb_elevel.bind("<<ComboboxSelected>>", lambda e: self._edited())
        self.lbl_blocked = self._lbl(lf, "", fg=THEME["warn"])
        self.lbl_blocked.pack(side="left", padx=10)
        row += 1
        self.t_note = field("Comment 1", "note", entry=False, height=2)
        self._lbl(right, "Link").grid(row=row, column=0, sticky="w", pady=3)
        lk = tk.Frame(right, bg=THEME["bg"])
        lk.grid(row=row, column=1, sticky="we", pady=3)
        self.vars["url"] = tk.StringVar()
        self.vars["url"].trace_add("write", lambda *a: self._edited())
        self._entry(lk, 40, self.vars["url"]).pack(side="left", fill="x", expand=True, ipady=2)
        self._btn(lk, "Open", self.open_link, 7).pack(side="left", padx=(6, 0))
        row += 1
        self.t_note2 = field("Comment 2", "note2", entry=False, height=2)
        self.t_numbers = field("Extra numbers", "numbers", entry=False, height=3)
        self.t_addresses = field("Addresses", "addresses", entry=False, height=3)
        self.t_details = field("Details", "details", entry=False, height=4)
        self.t_phrases = field("Phrases", "phrases", entry=False, height=3)
        bar = tk.Frame(right, bg=THEME["bg"])
        bar.grid(row=row, column=0, columnspan=2, sticky="w", pady=(8, 0))
        for text, cmd, w in (("Copy number", self.copy_number, 12), ("Route", lambda: self.maps("dir"), 8), ("Map", lambda: self.maps("search"), 8),
                             ("Look up", self.look_up, 8), ("Add from paste...", self.paste_into_current, 15), ("Delete", self.delete_current, 8)):
            self._btn(bar, text, cmd, w).pack(side="left", padx=(0, 4))
        self.set_editor(None)

    # ---- the list ------------------------------------------------------------------------
    def _sort_key(self, rec):
        d = rec["data"]
        if self.v_sort.get() == "Newest first":
            return (-rec["local"].get("added", 0),)
        if self.v_sort.get() == "Most used":
            return (-rec["local"].get("opens", 0), title_of(d).lower())
        if self.v_sort.get() == "Recently used":
            return (-rec["local"].get("last", 0), title_of(d).lower())
        return (title_of(d).lower(),)

    def refresh_list(self, keep=None):
        keep = keep or self.cur
        recs = self.book.live()
        groups = sorted({r["data"]["group"] for r in recs if r["data"]["group"]}, key=str.lower)
        self.cb_group["values"] = ["All groups"] + groups
        if self.v_group.get() not in self.cb_group["values"]:
            self.v_group.set("All groups")
        q = self.v_search.get().strip().lower()
        lvl = self.v_level.get()
        grp = self.v_group.get()
        rows = []
        for r in recs:
            d = r["data"]
            if grp != "All groups" and d["group"] != grp:
                continue
            if lvl != "All levels" and LEVEL_TEXT[r["level"]] != lvl:
                continue
            if q:
                hay = " ".join([d["number"], d["name"], d["people"], d["group"], d["note"], d["note2"], d["details"], d["url"],
                                items_text(d["numbers"]), items_text(d["addresses"])]).lower()
                hit = q in hay
                if not hit and num_key(q):
                    hit = num_key(q) in num_key(d["number"]) or any(num_key(q) in num_key(i["value"]) for i in d["numbers"])
                if not hit:
                    continue
            rows.append(r)
        rows.sort(key=self._sort_key)
        self.tree.delete(*self.tree.get_children())
        for r in rows:
            d = r["data"]
            mark = "!" if r["blocked"] else ("•" if self.connected() and Book.is_dirty(r) else "")
            self.tree.insert("", "end", iid=r["id"], values=(title_of(d), d["number"], LEVEL_TEXT[r["level"]], mark))
        self.lbl_count.configure(text="%d of %d" % (len(rows), len(recs)))
        if keep and self.tree.exists(keep):
            self.tree.selection_set(keep)
            self.tree.see(keep)
        elif keep:
            self.cur = None
            self.set_editor(None)

    def _filter_changed(self, key):
        self.S[key] = {"group": self.v_group, "level": self.v_level, "sort": self.v_sort}[key].get()
        save_settings(self.S)
        self.refresh_list()

    def _selected(self, event=None):
        sel = self.tree.selection()
        self._commit_now()
        self.set_editor(sel[0] if sel else None)

    # ---- the editor ------------------------------------------------------------------------
    def set_editor(self, rid):
        self.loading = True
        try:
            self.cur = rid
            rec = self.book.get(rid) if rid else None
            enabled = rec is not None
            d = rec["data"] if rec else norm_data({})
            for k in ("number", "name", "people", "group", "url"):
                self.vars[k].set(d[k])
            for k, w in self.texts.items():
                w.configure(state="normal")
                w.delete("1.0", "end")
                v = d[k]
                w.insert("1.0", items_text(v) if k in ("numbers", "addresses") else ("\n".join(v) if k == "phrases" else v))
                w.edit_modified(False)
                w.edit_reset()
            self.v_elevel.set(LEVEL_TEXT[rec["level"]] if rec else LEVEL_TEXT["me"])
            self.lbl_blocked.configure(text=("Not shared: " + rec["blocked"].split("\x00", 1)[-1]) if rec and rec["blocked"] else "")
            self._offer_levels()
            for w in self.right.winfo_children():
                self._enable(w, enabled)
        finally:
            self.loading = False

    def _enable(self, w, on):
        if isinstance(w, (tk.Entry, tk.Text)):
            w.configure(state="normal" if on else "disabled")
        elif isinstance(w, (tk.Frame,)):
            for c in w.winfo_children():
                self._enable(c, on)
        elif isinstance(w, ttk.Combobox):
            w.configure(state="readonly" if on else "disabled")

    def _offer_levels(self):
        """Only the levels this code may give (a family code cannot make a number 'Only me')."""
        rank = LEVEL_RANK.get(self.S.get("sync_role") or "me", 3) if self.connected() else 3
        self.cb_elevel["values"] = [LEVEL_TEXT[l] for l in ("me", "family", "public") if LEVEL_RANK[l] <= rank]

    def _level_from_text(self, text):
        for k, v in LEVEL_TEXT.items():
            if v == text:
                return k
        return "me"

    def _text_modified(self, event):
        w = event.widget
        if w.edit_modified():
            w.edit_modified(False)
            self._edited()

    def _edited(self):
        if self.loading or not self.cur:
            return
        if self.save_job:
            self.root.after_cancel(self.save_job)
        self.save_job = self.root.after(600, self._commit_now)

    def _collect(self):
        d = {k: self.vars[k].get() for k in ("number", "name", "people", "group", "url")}
        for k, w in self.texts.items():
            t = w.get("1.0", "end-1c")
            d[k] = parse_items(t) if k in ("numbers", "addresses") else (text_lines(t) if k == "phrases" else t)
        return d

    def _commit_now(self):
        if self.save_job:
            try:
                self.root.after_cancel(self.save_job)
            except Exception:
                pass
            self.save_job = None
        rid = self.cur
        rec = self.book.get(rid) if rid else None
        if rec is None or self.loading:
            return
        d = self._collect()
        if d["number"].strip() and not valid_number(d["number"]):
            self.say("The number needs at least 3 digits (or leave it empty): not saved.", "warn")
            return
        if not can_save(d):
            self.say("Give it a name or a number: not saved.", "warn")
            return
        level = self._level_from_text(self.v_elevel.get())
        nd = norm_data(d)
        nd["numbers"] = clean_numbers(nd["number"], nd["numbers"])
        if nd == rec["data"] and level == rec["level"]:
            return
        self.book.update(rid, nd, level)
        if self.tree.exists(rid):
            self.tree.item(rid, values=(title_of(nd), nd["number"], LEVEL_TEXT[level], "•" if self.connected() else ""))

    def delete_current(self):
        rid = self.cur
        rec = self.book.get(rid) if rid else None
        if not rec:
            return
        if not messagebox.askyesno(APP_NAME, "Delete %s?%s" % (title_of(rec["data"]), "\nIt is deleted on the other devices too." if self.connected() else ""), parent=self.root):
            return
        self.cur = None
        self.book.delete(rid)
        self.refresh_list()
        self.set_editor(None)

    def copy_number(self):
        rec = self.book.get(self.cur) if self.cur else None
        if rec and not rec["data"]["number"].strip():
            self.say("This entry has no number.", "warn")
        elif rec:
            self.root.clipboard_clear()
            self.root.clipboard_append(digits(rec["data"]["number"]))
            self.book.used(rec["id"])
            self.say("Number copied.", "good")

    def open_link(self):
        u = clean_url(self.vars["url"].get())
        if u:
            open_url(u)

    def _selected_address(self):
        w = self.t_addresses
        try:
            line = w.get("insert linestart", "insert lineend").strip()
        except tk.TclError:
            line = ""
        if not line:
            items = parse_items(w.get("1.0", "end-1c"))
            line = items[0]["label"] and items[0]["value"] or (items[0]["value"] if items else "")
        else:
            it = parse_items(line)
            line = it[0]["value"] if it else line
        return line

    def maps(self, kind):
        a = self._selected_address()
        if not a:
            self.say("Put the cursor on an address line first.", "warn")
            return
        q = urllib.parse.quote(a)
        open_url("https://www.google.com/maps/dir/?api=1&destination=" + q if kind == "dir" else "https://www.google.com/maps/search/?api=1&query=" + q)

    def look_up(self):
        n = self.vars["number"].get().strip()
        if n:
            open_url("https://www.hitta.se/s%C3%B6k?vad=" + urllib.parse.quote(digits(n)))

    # ---- paste -------------------------------------------------------------------------------
    def _ctrl_v(self, event):
        w = self.root.focus_get()
        if isinstance(w, (tk.Entry, tk.Text, ttk.Combobox)):
            return
        self.open_paste()

    def say(self, text, tag="dim"):
        self.lbl_sync.configure(text=text, fg=THEME.get(tag, THEME["dim"]))
        self.root.after(6000, self._status)

    def open_paste(self, text=None, merge_into=None):
        """text None = take the clipboard; '' = empty box.  merge_into = id of an entry that gets what is new from the paste."""
        if text is None:
            try:
                text = self.root.clipboard_get()
            except tk.TclError:
                text = ""
        self._commit_now()
        T = THEME
        top = tk.Toplevel(self.root)
        top.title("Paste or type numbers" if not merge_into else "Add to this entry from a paste")
        top.configure(bg=T["bg"])
        top.geometry("940x640")
        top.resizable(False, False)
        top.transient(self.root)
        make_modal(top)
        self._lbl(top, "Paste text from hitta.se (or anywhere) or type  'number  name'  - one per line.  What is found is shown below.", fg=T["dim"]).pack(anchor="w", padx=12, pady=(10, 4))
        box = self._text(top, 8)
        box.pack(fill="x", padx=12)
        box.insert("1.0", text or "")
        cols = (("use", "", 28), ("what", "", 90), ("name", "Name", 230), ("number", "Number", 120), ("address", "Address", 280), ("warn", "Note", 150))
        tree = ttk.Treeview(top, columns=[c[0] for c in cols], show="headings", height=9, selectmode="none")
        for k, head, w in cols:
            tree.heading(k, text=head)
            tree.column(k, width=w, minwidth=w, stretch=False)
        tree.pack(fill="x", padx=12, pady=(8, 0))
        found = []
        ticked = {}
        info = self._lbl(top, "", fg=T["dim"])
        info.pack(anchor="w", padx=12, pady=(4, 0))

        def parse(*a):
            items = parse_paste(box.get("1.0", "end-1c"))
            found[:] = items
            tree.delete(*tree.get_children())
            ticked.clear()
            for i, d in enumerate(items):
                ticked[i] = bool(merge_into) or can_save(d)     # a person without a phone number is fine; a row with neither name nor number is shown but not ticked
                row(i)
            warns = [d["_warn"] for d in items if d["_warn"]]
            nothing = sum(1 for d in items if not merge_into and not can_save(d))
            if nothing:
                warns.append("%d with no name and no number: double-click Name or Number and type it." % nothing)
            info.configure(text=(" ".join(warns) if warns else ("%d found." % len(items) if items else "Nothing found yet.")), fg=T["warn"] if warns else T["dim"])

        def row(i):
            d = found[i]
            ex = self.book.find_same(d)
            ok = bool(merge_into) or can_save(d)
            what = "update" if (merge_into or ex) else ("new" if ok else "nothing")
            note = d["_warn"] or ("" if ok else "Needs a name or number")
            vals = ("x" if ticked.get(i) else "", what, d["name"] or "(no name)", d["number"] or "(no number)",
                    d["addresses"][0]["value"] if d["addresses"] else "", note[:24] + ("..." if len(note) > 24 else ""))
            if tree.exists(str(i)):
                tree.item(str(i), values=vals)
            else:
                tree.insert("", "end", iid=str(i), values=vals)

        def toggle(event):
            iid = tree.identify_row(event.y)
            if iid and tree.identify_column(event.x) != "#4":
                ticked[int(iid)] = not ticked[int(iid)]
                row(int(iid))

        def type_number(event):
            """Double-click Name, Number or Address of a row in the preview: fix it right there, before it is saved."""
            iid = tree.identify_row(event.y)
            col = tree.identify_column(event.x)
            if not iid or col not in ("#3", "#4", "#5"):
                return
            i = int(iid)
            d = found[i]
            from tkinter import simpledialog
            if col == "#3":
                n = simpledialog.askstring(APP_NAME, "Name:", initialvalue=d["name"], parent=top)
                if n is not None:
                    d["name"] = n.strip()
                    ticked[i] = can_save(d) or bool(merge_into)
            elif col == "#4":
                n = simpledialog.askstring(APP_NAME, "Number for %s:" % (d["name"] or "this entry"), initialvalue=d["number"], parent=top)
                if n is not None:
                    d["number"] = n.strip()
                    ticked[i] = can_save(d) or bool(merge_into)
            else:
                n = simpledialog.askstring(APP_NAME, "Address for %s:" % (d["name"] or "this entry"), initialvalue=d["addresses"][0]["value"] if d["addresses"] else "", parent=top)
                if n is not None:
                    rest = d["addresses"][1:]
                    d["addresses"] = ([{"label": d["addresses"][0]["label"] if d["addresses"] else "", "value": n.strip()}] if n.strip() else []) + rest
            row(i)
        tree.bind("<Button-1>", toggle)
        tree.bind("<Double-1>", type_number)
        box.bind("<KeyRelease>", parse)
        box.bind("<<Paste>>", lambda e: top.after(80, parse))
        lf = tk.Frame(top, bg=T["bg"])
        lf.pack(fill="x", padx=12, pady=(8, 0))
        self._lbl(lf, "New entries are visible to").pack(side="left")
        v_lv = tk.StringVar(value=LEVEL_TEXT[self.S.get("new_level", "me")])
        rank = LEVEL_RANK.get(self.S.get("sync_role") or "me", 3) if self.connected() else 3
        ttk.Combobox(lf, textvariable=v_lv, state="readonly", width=14, values=[LEVEL_TEXT[l] for l in ("me", "family", "public") if LEVEL_RANK[l] <= rank]).pack(side="left", padx=8)
        self._lbl(lf, "Group for all").pack(side="left", padx=(20, 4))
        v_grp = tk.StringVar()
        self._entry(lf, 20, v_grp).pack(side="left", ipady=2)

        def do_add():
            todo = [i for i in range(len(found)) if ticked.get(i)]
            if not todo:
                messagebox.showinfo(APP_NAME, "Nothing is ticked, so nothing was saved.\n\nTick a row (click it) or paste/type something first.", parent=top)
                return
            missing = []
            for i in todo:
                d = found[i]
                if not merge_into and not can_save(d):
                    missing.append((d["addresses"][0]["value"] if d["addresses"] else "") or "(empty row)")
            if missing:                              # never drop an entry silently: say so and keep the window open with everything still in it
                messagebox.showwarning(APP_NAME, "These have no name and no number, so they cannot be saved:\n\n  " + "\n  ".join(missing[:12]) +
                                       "\n\nDouble-click Name or Number of the row and type it, or remove the tick.", parent=top)
                return
            added = updated = 0
            lvl = self._level_from_text(v_lv.get())
            self.S["new_level"] = lvl
            save_settings(self.S)
            last = None
            for i, d in enumerate(found):
                if not ticked.get(i):
                    continue
                d = {k: v for k, v in d.items() if k != "_warn"}
                if v_grp.get().strip() and not d["group"]:
                    d["group"] = v_grp.get().strip()
                target = self.book.get(merge_into) if merge_into else self.book.find_same(d)
                if target is not None:
                    self.book.merge_entry(target["id"], d)
                    updated += 1
                    last = target["id"]
                elif can_save(d):
                    last = self.book.add(d, lvl)["id"]
                    added += 1
            top.destroy()
            self.refresh_list(keep=last)
            if last and self.tree.exists(last):
                self.tree.selection_set(last)
                self.set_editor(last)
            self.say("%d added, %d updated." % (added, updated), "good")
        bb = tk.Frame(top, bg=T["bg"])
        bb.pack(pady=12)
        self._btn(bb, "Add / update", do_add, 14, bg=T["good"], fg="#14141f").pack(side="left", padx=6)
        self._btn(bb, "Cancel", top.destroy, 10).pack(side="left", padx=6)
        parse()
        box.focus_set()

    def paste_into_current(self):
        if not self.cur:
            return
        self.open_paste(None, merge_into=self.cur)

    # ---- tools -------------------------------------------------------------------------------
    def _tools_menu(self):
        m = tk.Menu(self.root, tearoff=0)
        m.add_command(label="Merge duplicates...", command=self.merge_duplicates)
        m.add_separator()
        m.add_command(label="Export numbers...", command=self.export_book)
        m.add_command(label="Import numbers...", command=self.import_book)
        m.add_separator()
        m.add_command(label="Open the data folder", command=lambda: open_path(PROGRAM_HF_DIR))
        b = self.btn_tools
        m.tk_popup(b.winfo_rootx(), b.winfo_rooty() + b.winfo_height())

    def merge_duplicates(self):
        groups = self.book.duplicates()
        if not groups:
            messagebox.showinfo(APP_NAME, "No number is in the book twice.", parent=self.root)
            return
        names = "\n".join("  " + " / ".join(title_of(r["data"]) for r in g) + "  (" + g[0]["data"]["number"] + ")" for g in groups[:12])
        if not messagebox.askyesno(APP_NAME, "%d number(s) are in the book more than once:\n\n%s\n\nJoin each group into its oldest entry (nothing of the others is lost)?" % (len(groups), names), parent=self.root):
            return
        for g in groups:
            self.book.merge_duplicates(g)
        self.cur = None
        self.refresh_list()
        self.set_editor(None)
        self.say("%d group(s) joined." % len(groups), "good")

    def export_book(self):
        p = filedialog.asksaveasfilename(parent=self.root, defaultextension=".json", initialfile="NumberBook_export.json", filetypes=[("Number Book", "*.json")])
        if not p:
            return
        out = [dict(r["data"], level=r["level"]) for r in self.book.live()]
        with open(p, "w", encoding="utf-8") as fh:
            json.dump({"numberbook": 1, "entries": out}, fh, ensure_ascii=False, indent=1)
        self.say("%d numbers exported." % len(out), "good")

    def import_book(self):
        p = filedialog.askopenfilename(parent=self.root, filetypes=[("Number Book", "*.json"), ("All files", "*.*")])
        if not p:
            return
        try:
            with open(p, encoding="utf-8") as fh:
                d = json.load(fh)
            entries = d["entries"] if isinstance(d, dict) else d
        except Exception as exc:
            messagebox.showerror(APP_NAME, "Cannot read that file: %s" % exc, parent=self.root)
            return
        n_new = n_up = 0
        for e in entries:
            if not isinstance(e, dict):
                continue
            nd = norm_data(e)
            if nd["number"].strip() and not valid_number(nd["number"]):          # not a usable number: keep the text as a detail, never lose it
                nd["details"] = merge_text(nd["details"], "Number: " + nd["number"])
                nd["number"] = ""
            if not can_save(nd):
                continue
            ex = self.book.find_same(nd)
            if ex:
                self.book.merge_entry(ex["id"], nd)
                n_up += 1
            else:
                self.book.add(nd, e.get("level") if e.get("level") in LEVELS else "me")
                n_new += 1
        self.refresh_list()
        self.say("%d added, %d updated." % (n_new, n_up), "good")

    # ---- sync (the network part runs in a thread; the window is only touched here) ---------------------
    def _on_book_changed(self):
        if self.connected() and self.S.get("auto_sync"):
            self.plan_sync(4.0)

    def plan_sync(self, delay):
        t = time.time() + delay
        if not self.sync_want or t < self.sync_want:
            self.sync_want = t

    def _tick(self):
        try:
            self._drain()
            now = time.time()
            if self.connected() and not self.sync_busy and self.S.get("auto_sync"):
                if (self.sync_want and now >= self.sync_want and now >= self.sync_next) or now - self.S.get("last_sync", 0) >= 30 and now >= self.sync_next:
                    self.sync_now()
        finally:
            self.root.after(1000, self._tick)

    def sync_now(self):
        if self.sync_busy or not self.connected():
            return
        self._commit_now()
        self.sync_busy = True
        self.sync_want = 0.0
        self._status()
        server = Server(self.S["sync_url"], self.S["sync_token"])

        def job():
            try:
                res = sync_once(self.book, server)
                self.sync_q.put(("ok", res))
            except NBError as exc:
                self.sync_q.put(("err", str(exc)))
            except Exception as exc:
                self.sync_q.put(("err", "unexpected: %r" % (exc,)))
        threading.Thread(target=job, daemon=True).start()

    def _drain(self):
        while True:
            try:
                kind, val = self.sync_q.get_nowait()
            except queue.Empty:
                return
            self.sync_busy = False
            if kind == "ok":
                self.sync_error = ""
                self.S["last_sync"] = time.time()
                self.S["sync_role"], self.S["sync_write"], self.S["sync_name"] = val.role, val.write, val.name or self.S.get("sync_name", "")
                save_settings(self.S)
                self.sync_next = 0
                self.last_result = val
                if val.pulled or val.removed or val.conflicts or val.pushed or val.blocked:
                    self.refresh_list()
                    if self.cur and self.book.get(self.cur) is None:
                        self.cur = None
                        self.set_editor(None)
                    elif self.cur:
                        rec = self.book.get(self.cur)
                        if rec and (val.pulled or val.conflicts) and not self._editor_has_focus():
                            self.set_editor(self.cur)
                if self.sync_want == 0 and any(Book.is_dirty(r) and not r["blocked"] for r in self.book.recs.values()) and val.write:
                    self.plan_sync(4.0)
            else:
                self.sync_error = val
                self.sync_next = time.time() + 60
            self._status()

    def _editor_has_focus(self):
        w = self.root.focus_get()
        return isinstance(w, (tk.Entry, tk.Text)) and w.winfo_toplevel() is self.root

    def _status(self):
        if not self.connected():
            txt, col = "Not connected  (Sync... to connect a phone or share)", THEME["dim"]
        elif self.sync_busy:
            txt, col = "Syncing ...", THEME["accent"]
        elif self.sync_error:
            txt, col = "Offline: " + self.sync_error[:60], THEME["bad"]
        else:
            ls = self.S.get("last_sync", 0)
            role = {"me": "me", "family": "family", "public": "public"}.get(self.S.get("sync_role"), "")
            ro = "" if self.S.get("sync_write") else ", read only"
            txt = "Synced %s (%s%s)" % (time.strftime("%H:%M:%S", time.localtime(ls)) if ls else "never", role, ro)
            col = THEME["good"]
        self.lbl_sync.configure(text=txt, fg=col)

    def open_sync(self):
        SyncDialog(self)

    # ---- dialogs -------------------------------------------------------------------------------
    def show_help(self):
        top = tk.Toplevel(self.root)
        top.title(APP_NAME + " - Help")
        top.configure(bg=THEME["bg"])
        top.geometry("820x680")
        top.resizable(False, False)
        top.transient(self.root)
        t = new_text(top, wrap="word", bg=THEME["field"], fg=THEME["field_fg"], font=("Segoe UI", 10), relief="flat")
        sb = tk.Scrollbar(top, command=t.yview)
        t.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        t.pack(fill="both", expand=True, padx=8, pady=8)
        t.insert("1.0", HELP_TEXT)
        t.configure(state="disabled")
        make_modal(top)

    def about(self):
        show_about(self.root, APP_NAME, "Your numbers with a name, a comment and a link - the same on PC and phone", "\U0001F4D2")

    def open_notes(self):
        if self.playtext is not None:
            try:
                if self.playtext.top.winfo_exists():
                    self.playtext.top.lift()
                    return
            except Exception:
                pass
        self.S["show_playtext"] = True

        def closed():
            self.playtext = None
        self.playtext = PlayerTextPopup(
            self.root, self.S, ("show_playtext", "playtext_pos", "playtext_zoom", "playtext_sel"),
            lambda: save_settings(self.S),
            dict(bg=THEME["bg"], panel=THEME["panel"], fg=THEME["fg"], dim=THEME["dim"], accent=THEME["accent"],
                 btn=THEME["btn"], btnfg=THEME["btnfg"], field=THEME["field"], field_fg=THEME["field_fg"]),
            "Notes", PROGRAM_HF_DIR, lambda: {}, on_closed=closed)

    def on_close(self):
        try:
            self._commit_now()
            if self.playtext is not None:
                self.playtext.save_now()
            self.book.save()
            save_settings(self.S)
        except Exception:
            pass
        self.root.destroy()


# *************** DEL 18 - SYNC DIALOG (connect with a code / own server) AND CODES (for a ME code) *****************
class SyncDialog(object):
    def __init__(self, app):
        self.app = app
        T = THEME
        top = self.top = tk.Toplevel(app.root)
        top.title("Sync")
        top.configure(bg=T["bg"])
        top.geometry("760x600")
        top.resizable(False, False)
        top.transient(app.root)
        make_modal(top)
        self.v_code = tk.StringVar()
        self.v_url = tk.StringVar()
        self.v_key = tk.StringVar()
        self.v_name = tk.StringVar(value="My computer")
        self.v_auto = tk.BooleanVar(value=bool(app.S.get("auto_sync")))
        self.lbl_state = app._lbl(top, "", fg=T["accent"], font=("Segoe UI", 10, "bold"), wraplength=720, justify="left")
        self.lbl_state.pack(anchor="w", padx=14, pady=(12, 4))
        self.lbl_msg = app._lbl(top, "", fg=T["dim"], wraplength=720, justify="left")
        self.lbl_msg.pack(anchor="w", padx=14)

        a = app._box(top, "Connect with a code")
        a.pack(fill="x", padx=14, pady=(10, 4))
        app._lbl(a, "A code text from AppSite, or from the person who runs the server (starts with NBK1.), or  address|code").pack(anchor="w")
        row = tk.Frame(a, bg=T["bg"])
        row.pack(fill="x", pady=4)
        app._entry(row, 70, self.v_code).pack(side="left", ipady=3)
        app._btn(row, "Paste", self.paste_code, 7).pack(side="left", padx=4)
        app._btn(row, "Connect", self.connect_code, 10, bg=T["good"], fg="#14141f").pack(side="left", padx=4)

        b = app._box(top, "Own server (any small Linux server with python3 + nginx; see the relay README)")
        b.pack(fill="x", padx=14, pady=4)
        g = tk.Frame(b, bg=T["bg"])
        g.pack(fill="x")
        for i, (lab, var, show) in enumerate((("Address", self.v_url, ""), ("Owner key", self.v_key, "*"), ("Name for my code", self.v_name, ""))):
            app._lbl(g, lab, width=16).grid(row=i, column=0, sticky="w", pady=2)
            e = app._entry(g, 62, var)
            if show:
                e.configure(show=show)
            e.grid(row=i, column=1, sticky="w", pady=2, ipady=2)
        app._lbl(b, "The owner key is used once to make YOUR code (role 'me') and is never saved.  Address looks like  https://myserver.example/numberbook/", fg=T["dim"], wraplength=700, justify="left").pack(anchor="w", pady=(2, 4))
        app._btn(b, "Make my code and connect", self.connect_own, 24).pack(anchor="w")

        c = tk.Frame(top, bg=T["bg"])
        c.pack(fill="x", padx=14, pady=10)
        tk.Checkbutton(c, text="Sync by itself (a few seconds after a change, and every 30 seconds)", variable=self.v_auto, command=self.auto_changed, bg=T["bg"], fg=T["fg"],
                       selectcolor=T["field"], activebackground=T["bg"], activeforeground=T["fg"], font=("Segoe UI", 9)).pack(anchor="w")
        bb = tk.Frame(top, bg=T["bg"])
        bb.pack(fill="x", padx=14, pady=4)
        self.btn_now = app._btn(bb, "Sync now", self.sync_now, 12)
        self.btn_now.pack(side="left", padx=(0, 6))
        self.btn_codes = app._btn(bb, "Codes...", self.codes, 12)
        self.btn_codes.pack(side="left", padx=6)
        self.btn_off = app._btn(bb, "Disconnect", self.disconnect, 12)
        self.btn_off.pack(side="left", padx=6)
        app._btn(bb, "Close", top.destroy, 10).pack(side="right")
        self.refresh()

    def refresh(self):
        S = self.app.S
        if self.app.connected():
            ro = "" if S.get("sync_write") else " (read only)"
            self.lbl_state.configure(text="Connected to %s as \"%s\", role %s%s" % (S["sync_url"], S.get("sync_name", ""), S.get("sync_role") or "?", ro))
        else:
            self.lbl_state.configure(text="Not connected.  The book stays on this computer only.")
        on = self.app.connected()
        self.btn_now.configure(state="normal" if on else "disabled")
        self.btn_off.configure(state="normal" if on else "disabled")
        self.btn_codes.configure(state="normal" if on and S.get("sync_role") == "me" else "disabled")

    def say(self, text, bad=False):
        self.lbl_msg.configure(text=text, fg=THEME["bad"] if bad else THEME["dim"])
        self.top.update_idletasks()

    def paste_code(self):
        try:
            self.v_code.set(self.top.clipboard_get().strip())
        except tk.TclError:
            pass

    def _connect(self, url, token, name="", role=""):
        """Checks the code with /me, then keeps it."""
        try:
            me = Server(url, token).call("GET", "me")
        except NBError as exc:
            self.say("Could not connect: %s" % exc, True)
            return False
        S = self.app.S
        S["sync_url"], S["sync_token"] = Server(url).url, token
        S["sync_name"], S["sync_role"], S["sync_write"] = me.get("name", name), me.get("role", role), bool(me.get("write"))
        save_settings(S)
        self.app._offer_levels()
        self.app.plan_sync(0.5)
        self.refresh()
        self.say("Connected: this code sees %s numbers%s." % (me.get("count", "?"), "" if me.get("write") else " and may only read"))
        self.app._status()
        return True

    def connect_code(self):
        c = parse_code(self.v_code.get())
        if not c:
            self.say("That is not a code text.  It starts with NBK1. (or write  address|code).", True)
            return
        if self.app.connected() and Server(c["url"]).url != self.app.S["sync_url"]:
            if not messagebox.askyesno(APP_NAME, "This book is connected to another server.  Switch?\nEverything in this book is then sent to the new server (nothing is deleted here).", parent=self.top):
                return
        self._connect(c["url"], c["token"], c["name"], c["role"])

    def connect_own(self):
        url, key, name = self.v_url.get().strip(), self.v_key.get().strip(), self.v_name.get().strip() or "My computer"
        if not url.lower().startswith("http") or not key:
            self.say("Fill in the address (https://...) and the owner key.", True)
            return
        self.say("Making your code ...")
        try:
            token, text, _ = make_code(url, key, name, "me")
        except NBError as exc:
            self.say("Could not make the code: %s" % exc, True)
            return
        self.v_key.set("")
        self.app.S.setdefault("made_codes", {})
        if self._connect(url, token, name, "me"):
            self.top.clipboard_clear()
            self.top.clipboard_append(text)
            self.say("Connected.  Your code text was copied to the clipboard - paste it on your phone (Sync) to connect it as well.")

    def auto_changed(self):
        self.app.S["auto_sync"] = bool(self.v_auto.get())
        save_settings(self.app.S)

    def sync_now(self):
        self.app.sync_next = 0
        self.app.sync_now()
        self.say("Syncing ... (the answer shows in the main window)")

    def disconnect(self):
        if not messagebox.askyesno(APP_NAME, "Disconnect?  The numbers stay here; nothing is deleted on the server.", parent=self.top):
            return
        S = self.app.S
        S["sync_url"] = S["sync_token"] = ""
        S["sync_role"] = ""
        save_settings(S)
        self.app._offer_levels()
        self.app.refresh_list()
        self.app._status()
        self.refresh()
        self.say("Disconnected.")

    def codes(self):
        CodesDialog(self.app, self.top)


class CodesDialog(object):
    """For a ME code: who has a code (public / family / me), make a new one, switch one off."""

    def __init__(self, app, parent):
        self.app = app
        T = THEME
        top = self.top = tk.Toplevel(parent)
        top.title("Codes")
        top.configure(bg=T["bg"])
        top.geometry("780x520")
        top.resizable(False, False)
        top.transient(parent)
        make_modal(top)
        app._lbl(top, "A code lets one person or phone in.  PUBLIC sees only Public numbers; FAMILY sees Family + Public and may change them; "
                 "ME sees everything.  Give each person their own code text.  Switch off takes a code away at once.", fg=T["dim"], wraplength=740, justify="left").pack(anchor="w", padx=12, pady=(10, 6))
        cols = (("name", "For", 190), ("role", "Role", 70), ("write", "May change", 90), ("last", "Last used", 140), ("state", "State", 190))
        self.tree = ttk.Treeview(top, columns=[c[0] for c in cols], show="headings", height=10, selectmode="browse")
        for k, head, w in cols:
            self.tree.heading(k, text=head)
            self.tree.column(k, width=w, minwidth=w, stretch=False)
        self.tree.pack(fill="x", padx=12)
        self.out = app._text(top, 6)
        self.out.configure(state="disabled", font=("Consolas", 9))
        bar = tk.Frame(top, bg=T["bg"])
        bar.pack(fill="x", padx=12, pady=8)
        for text, cmd, w in (("New code...", self.new, 12), ("Copy code text", self.copy, 14), ("Allow / stop changes", self.toggle_write, 20), ("Switch off", self.revoke, 11), ("Refresh", self.refresh, 9)):
            app._btn(bar, text, cmd, w).pack(side="left", padx=(0, 4))
        self.out.pack(fill="both", expand=True, padx=12, pady=(0, 10))
        self.rows = {}
        self.refresh()

    def server(self):
        return Server(self.app.S["sync_url"], self.app.S["sync_token"])

    def say(self, text):
        self.out.configure(state="normal")
        self.out.insert("end", text + "\n")
        self.out.see("end")
        self.out.configure(state="disabled")

    def refresh(self):
        try:
            r = self.server().call("GET", "invites")
        except NBError as exc:
            self.say(str(exc))
            return
        self.rows = {}
        self.tree.delete(*self.tree.get_children())
        for i in r.get("invites", []):
            self.rows[i["id"]] = i
            last = i.get("last") or 0
            st = "switched off" if i.get("rev") else ("works" + ("" if i["id"] in self.app.S.get("made_codes", {}) else " (code text not saved here)"))
            self.tree.insert("", "end", iid=i["id"], values=(i["name"], i["role"], "yes" if i.get("write") else "read only",
                                                              time.strftime("%Y-%m-%d %H:%M", time.localtime(last)) if last else "never", st))

    def chosen(self):
        sel = self.tree.selection()
        return sel[0] if sel else ""

    def new(self):
        T = THEME
        d = tk.Toplevel(self.top)
        d.title("New code")
        d.configure(bg=T["bg"])
        d.geometry("460x210")
        d.resizable(False, False)
        d.transient(self.top)
        make_modal(d)
        v_name, v_role, v_write = tk.StringVar(), tk.StringVar(value="family"), tk.BooleanVar(value=True)
        self.app._lbl(d, "For (a name)", width=14).grid(row=0, column=0, padx=10, pady=(16, 6), sticky="e")
        e = self.app._entry(d, 28, v_name)
        e.grid(row=0, column=1, sticky="w", pady=(16, 6), ipady=2)
        self.app._lbl(d, "Role", width=14).grid(row=1, column=0, padx=10, pady=6, sticky="e")
        ttk.Combobox(d, textvariable=v_role, state="readonly", width=12, values=("public", "family", "me")).grid(row=1, column=1, sticky="w", pady=6)
        tk.Checkbutton(d, text="May add / change numbers (a public code is read only by default)", variable=v_write, bg=T["bg"], fg=T["fg"], selectcolor=T["field"],
                       activebackground=T["bg"], activeforeground=T["fg"], font=("Segoe UI", 9)).grid(row=2, column=0, columnspan=2, padx=10, pady=4, sticky="w")

        def ok():
            name = v_name.get().strip()
            if not name:
                messagebox.showerror(APP_NAME, "Give the code a name.", parent=d)
                return
            role = v_role.get()
            write = v_write.get() if role != "public" or v_write.get() else False
            try:
                token, text, cid = self._make(name, role, write)
            except NBError as exc:
                self.say(str(exc))
                return
            self.app.S.setdefault("made_codes", {})[cid] = text
            save_settings(self.app.S)
            d.destroy()
            self.top.clipboard_clear()
            self.top.clipboard_append(text)
            self.say("Code for %s made and copied - paste it into a message to them:\n%s" % (name, text))
            self.refresh()
        bb = tk.Frame(d, bg=T["bg"])
        bb.grid(row=3, column=0, columnspan=2, pady=12)
        self.app._btn(bb, "Make", ok, 10, bg=T["good"], fg="#14141f").pack(side="left", padx=6)
        self.app._btn(bb, "Cancel", d.destroy, 10).pack(side="left", padx=6)
        e.focus_set()

    def _make(self, name, role, write):
        s = self.server()
        r = s.call("POST", "invite", {"name": name, "role": role, "write": bool(write)})
        if not r.get("token"):
            raise NBError("the server gave an answer I cannot read")
        return r["token"], code_text(s.url, r["token"], name, role), r.get("id", "")

    def copy(self):
        cid = self.chosen()
        t = self.app.S.get("made_codes", {}).get(cid)
        if not t:
            self.say("This code was not made in this program, so its text is not saved here.  Switch it off and make a new one.")
            return
        self.top.clipboard_clear()
        self.top.clipboard_append(t)
        self.say("Code text copied.")

    def toggle_write(self):
        cid = self.chosen()
        row = self.rows.get(cid)
        if not row:
            return
        try:
            self.server().call("POST", "update", {"id": cid, "write": not row.get("write")})
        except NBError as exc:
            self.say(str(exc))
            return
        self.refresh()

    def revoke(self):
        cid = self.chosen()
        row = self.rows.get(cid)
        if not row or not messagebox.askyesno(APP_NAME, "Switch off the code for %s?  It stops working at once." % row["name"], parent=self.top):
            return
        try:
            self.server().call("POST", "revoke", {"id": cid})
        except NBError as exc:
            self.say(str(exc))
            return
        self.refresh()


# *************** DEL 19 - START ***************************************************
def main():
    _set_app_id()                                   # BEFORE tk.Tk()
    root = tk.Tk()
    App(root)
    root.after(0, lambda: _set_window_icon(root))
    root.mainloop()


if __name__ == "__main__":
    main()

