# -*- coding: utf-8 -*-
# =============================================================================
# RailImport.py  -  turns a MAP PICTURE (BMP / PNG / JPG) into a Map creator .json map.
#
# EVERYTHING INSIDE THIS PROGRAM IS ENGLISH (code, comments, UI text, Help) - rule 1.
#
# WP1 of Railroad_racing_plan\PLAN.md.  This is only the window; the reading is done by
#   rail_import_core.py   (grid, terrain, rivers / borders, city rings and numbers, .places info)
#   hexgrid.py            (the grid search, copied from Hex_Labels.py)
#   map_template.json     (an empty Map creator map: the settings every map file carries)
# All four files live in ONE folder:  <Railroad_racing>\Rail_import\
#
# Needs: Python 3 with tkinter, numpy and Pillow.   Data: <home>\Helpfiles\RailImport\settings.json
# Start:  RailImport.py ["C:\...\map.bmp"]
# =============================================================================

import os
import re
import sys
import json
import ctypes
import platform
import threading
import webbrowser
import tkinter as tk
from tkinter import filedialog, messagebox

from PIL import Image, ImageDraw, ImageFont, ImageTk

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import rail_import_core as core


# *************** DEL 01 - 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 02 - 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 03 - 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 05 - 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, the wordplay focUSing on US / focuSING cha-CHING
    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 - SETTINGS, LOOK, SMALL HELPERS *****************
# ToDo: place names -> texts, legend -> overlay_text, roads, hand-drawn edges (see rail_import_core.py).
# 1.1: special-run symbols (stars / flags) are read through the legend; list, layer and editor for them.

APP_TITLE = "Rail Import"
APP_VERSION = "1.1"
SETTINGS_FILE = os.path.join(PROGRAM_HF_DIR, "settings.json")
DEFAULT_PICTURE_DIRS = (r"B:\0---Burn\Rail\0---Kartor",)     # only used when nothing was opened before

THEME = dict(bg="#f4f4f8", panel="#e4e4ec", fg="#1a1a22", dim="#606070", accent="#3b7ddd",
             btn="#d8d8e4", field="#ffffff")
CANVAS_BG = "#777788"
TERRAIN_CHOICES = ("Plain", "Hill", "Forest", "Mountain", "Swamp", "Marsh", "Desert", "Volcano", "Water", "Ocean")


def open_url(url):
    try:
        webbrowser.open(str(url))
    except Exception:
        pass


def load_json(path, default):
    try:
        with open(path, encoding="utf-8") as fh:
            data = json.load(fh)
        return data if isinstance(data, type(default)) else default
    except Exception:
        return default


def save_json(path, data):
    """Atomic write: a cut-off save can never leave half a file."""
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        tmp = path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(data, fh, ensure_ascii=False, indent=1)
        os.replace(tmp, path)
        return True
    except Exception:
        return False


def find_maps_folder():
    """<Railroad_racing>\\Rail_files\\Maps when this program sits inside Railroad_racing, else ''."""
    d = os.path.dirname(os.path.abspath(__file__))
    for _ in range(5):
        p = os.path.join(d, "Rail_files", "Maps")
        if os.path.isdir(p):
            return p
        up = os.path.dirname(d)
        if up == d:
            break
        d = up
    return ""


# *************** DEL 20 - THE WINDOW *****************

class ImportWindow(object):
    def __init__(self, root, picture=None):
        self.root = root
        self.settings = load_json(SETTINGS_FILE, {})
        self.picture_path = ""
        self.result = None               # what rail_import_core.import_picture returned
        self.base_img = None             # PIL picture
        self.zoom = 0.5
        self.tk_img = None
        self.busy = False
        self.pick_mode = False
        self.edited = False
        self.show = dict(picture=tk.BooleanVar(value=True), terrain=tk.BooleanVar(value=True),
                         edges=tk.BooleanVar(value=True), rings=tk.BooleanVar(value=True),
                         sr=tk.BooleanVar(value=True))
        self.city_keys = []
        self.sr_keys = []
        self.status = tk.StringVar(value="Open a map picture (BMP / PNG / JPG) to start.")
        root.title(APP_TITLE + " " + APP_VERSION)
        root.geometry("1280x800")
        root.minsize(1000, 640)
        root.configure(bg=THEME["bg"])
        self._build()
        root.bind("<F1>", lambda e: self.help())
        root.protocol("WM_DELETE_WINDOW", self.close)
        if picture:
            root.after(200, lambda: self.open_picture(picture))

    # ---------- building the window ----------
    def _build(self):
        r = self.root
        bar = tk.Frame(r, bg=THEME["panel"])
        bar.pack(fill="x")
        for text, cmd in (("Open picture...", self.ask_picture), ("Grid start...", self.toggle_pick),
                          ("Re-run", self.rerun), ("Save map (.json)...", self.save_map)):
            tk.Button(bar, text=text, command=cmd, bg=THEME["btn"], relief="flat", padx=10, pady=3
                      ).pack(side="left", padx=(6, 0), pady=5)
        self.pick_btn = bar.winfo_children()[1]
        tk.Label(bar, text="   Show:", bg=THEME["panel"], fg=THEME["dim"]).pack(side="left")
        for key, label in (("picture", "Picture"), ("terrain", "Terrain"), ("edges", "Edges"), ("rings", "Cities"),
                           ("sr", "Special runs")):
            tk.Checkbutton(bar, text=label, variable=self.show[key], command=self.draw, bg=THEME["panel"],
                           activebackground=THEME["panel"]).pack(side="left")
        tk.Label(bar, text="   Zoom:", bg=THEME["panel"], fg=THEME["dim"]).pack(side="left")
        for text, f in (("-", 1 / 1.25), ("+", 1.25)):
            tk.Button(bar, text=text, width=2, command=lambda f=f: self.set_zoom(self.zoom * f),
                      bg=THEME["btn"], relief="flat").pack(side="left", padx=1)
        tk.Button(bar, text="Fit", command=self.fit, bg=THEME["btn"], relief="flat", width=4).pack(side="left", padx=1)
        self.zoom_label = tk.Label(bar, text="", bg=THEME["panel"], fg=THEME["dim"], width=6)
        self.zoom_label.pack(side="left")
        for text, cmd in (("About", self.about), ("Help (F1)", self.help)):
            tk.Button(bar, text=text, command=cmd, bg=THEME["btn"], relief="flat", padx=8
                      ).pack(side="right", padx=(0, 6), pady=5)

        body = tk.Frame(r, bg=THEME["bg"])
        body.pack(fill="both", expand=True)
        right = tk.Frame(body, bg=THEME["bg"], width=380)
        right.pack(side="right", fill="y")
        right.pack_propagate(False)
        left = tk.Frame(body, bg=THEME["bg"])
        left.pack(side="left", fill="both", expand=True)
        self.canvas = tk.Canvas(left, bg=CANVAS_BG, highlightthickness=0)
        sx = tk.Scrollbar(left, orient="horizontal", command=self.canvas.xview)
        sy = tk.Scrollbar(left, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(xscrollcommand=sx.set, yscrollcommand=sy.set)
        sx.pack(side="bottom", fill="x")
        sy.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)
        self.canvas.bind("<ButtonPress-1>", self.on_click)
        self.canvas.bind("<B1-Motion>", lambda e: self.canvas.scan_dragto(e.x, e.y, gain=1))
        self.canvas.bind("<ButtonPress-2>", lambda e: self.canvas.scan_mark(e.x, e.y))
        self.canvas.bind("<B2-Motion>", lambda e: self.canvas.scan_dragto(e.x, e.y, gain=1))
        self.canvas.bind("<Button-3>", self.on_right_click)
        self.canvas.bind("<MouseWheel>", self.on_wheel)
        self.canvas.bind("<Shift-MouseWheel>", lambda e: self.canvas.xview_scroll(-1 if e.delta > 0 else 1, "units"))
        self.canvas.bind("<Control-MouseWheel>", self.on_ctrl_wheel)

        tk.Label(right, text="What was found", bg=THEME["bg"], fg=THEME["dim"], anchor="w"
                 ).pack(fill="x", padx=8, pady=(8, 0))
        fr = tk.Frame(right)
        fr.pack(fill="x", padx=8)
        sb = tk.Scrollbar(fr)
        sb.pack(side="right", fill="y")
        self.report = new_text(fr, height=14, width=44, wrap="word", font=("Segoe UI", 9), yscrollcommand=sb.set,
                               bg=THEME["field"], state="disabled")
        self.report.pack(side="left", fill="x", expand=True)
        sb.configure(command=self.report.yview)
        tk.Label(right, text="Special runs  (double-click or right-click on the picture to edit)", bg=THEME["bg"],
                 fg=THEME["dim"], anchor="w").pack(fill="x", padx=8, pady=(8, 0))
        frs = tk.Frame(right)
        frs.pack(fill="x", padx=8)
        sbs = tk.Scrollbar(frs)
        sbs.pack(side="right", fill="y")
        self.srlist = tk.Listbox(frs, font=("Consolas", 9), height=8, yscrollcommand=sbs.set, activestyle="none",
                                 exportselection=False)
        self.srlist.pack(side="left", fill="x", expand=True)
        sbs.configure(command=self.srlist.yview)
        self.srlist.bind("<Double-Button-1>", lambda e: self.edit_selected_sr())
        self.srlist.bind("<<ListboxSelect>>", lambda e: self.center_on_selected_sr())
        tk.Label(right, text="City rings  (double-click or right-click on the picture to edit)", bg=THEME["bg"],
                 fg=THEME["dim"], anchor="w").pack(fill="x", padx=8, pady=(8, 0))
        fr2 = tk.Frame(right)
        fr2.pack(fill="both", expand=True, padx=8, pady=(0, 6))
        sb2 = tk.Scrollbar(fr2)
        sb2.pack(side="right", fill="y")
        self.cities = tk.Listbox(fr2, font=("Consolas", 9), yscrollcommand=sb2.set, activestyle="none",
                                 exportselection=False)
        self.cities.pack(side="left", fill="both", expand=True)
        sb2.configure(command=self.cities.yview)
        self.cities.bind("<Double-Button-1>", lambda e: self.edit_selected_city())
        self.cities.bind("<<ListboxSelect>>", lambda e: self.center_on_selected_city())
        tk.Label(r, textvariable=self.status, bg=THEME["panel"], fg=THEME["fg"], anchor="w", padx=8
                 ).pack(fill="x", side="bottom")

    # ---------- opening and importing ----------
    def ask_picture(self):
        start = self.settings.get("last_picture_dir", "")
        if not start or not os.path.isdir(start):
            start = next((d for d in DEFAULT_PICTURE_DIRS if os.path.isdir(d)), os.path.expanduser("~"))
        p = filedialog.askopenfilename(parent=self.root, title="Open a map picture", initialdir=start,
                                       filetypes=[("Pictures", "*.bmp *.png *.jpg *.jpeg *.gif"), ("All files", "*.*")])
        if p:
            self.open_picture(p)

    def open_picture(self, path):
        if self.busy:
            return
        if self.edited and not messagebox.askyesno(APP_TITLE, "You have edited the map and not saved it.\nOpen another picture anyway?", parent=self.root):
            return
        try:
            self.base_img = Image.open(path).convert("RGB")
        except Exception as e:
            messagebox.showerror(APP_TITLE, "Cannot open the picture:\n%s" % e, parent=self.root)
            return
        self.picture_path = path
        self.settings["last_picture_dir"] = os.path.dirname(path)
        save_json(SETTINGS_FILE, self.settings)
        self.result = None
        self.fit()
        self.start_import(None)

    def rerun(self):
        if self.picture_path:
            self.start_import(None)

    def start_import(self, seed):
        if self.busy or not self.picture_path:
            return
        self.busy = True
        self.edited = False
        self.status.set("Reading %s ... (a big picture can take a minute)" % os.path.basename(self.picture_path))
        self.root.config(cursor="watch")
        box = {}

        def work():
            try:
                box["res"] = core.import_picture(self.picture_path, seed=seed)
            except Exception as e:
                box["err"] = str(e) or e.__class__.__name__
        threading.Thread(target=work, daemon=True).start()
        self.root.after(150, lambda: self.poll(box))

    def poll(self, box):
        if "res" not in box and "err" not in box:
            self.root.after(150, lambda: self.poll(box))
            return
        self.busy = False
        self.root.config(cursor="")
        if "err" in box:
            self.result = None
            self.set_report("Could not read this picture:\n\n" + box["err"] +
                            "\n\nTry 'Grid start...' and click inside ONE empty hexagon (no city, no text).")
            self.fill_cities()
            self.status.set("No grid found.")
            self.draw()
            return
        self.result = box["res"]
        self.set_report("\n".join(self.result["report"]))
        self.fill_cities()
        self.status.set("%s: %d hexagons, %d edges, %d cities, %d special runs.  Save the map when it looks right."
                        % (os.path.basename(self.picture_path), self.result["stats"]["hexes"],
                           self.result["stats"]["rivers"], len(self.city_keys), len(self.sr_keys)))
        self.draw()

    def set_report(self, text):
        self.report.configure(state="normal")
        self.report.delete("1.0", "end")
        self.report.insert("1.0", text)
        self.report.configure(state="disabled")

    # ---------- cities list ----------
    def fill_cities(self):
        self.cities.delete(0, "end")
        self.city_keys = []
        self.fill_srs()
        if not self.result:
            return
        cities = self.result["map"]["cities"]
        keys = set(self.result["rings"]) | set(tuple(int(v) for v in k.split(",")) for k, v in cities.items()
                                               if not v.get("ring_disabled"))
        for key in sorted(keys):
            self.city_keys.append(key)
            self.cities.insert("end", self.city_line(key))

    # ---------- special runs (stars / flags) ----------
    def fill_srs(self):
        self.srlist.delete(0, "end")
        self.sr_keys = []
        if not self.result:
            return
        for i, s in enumerate(self.result["symbols"]["srs"]):
            self.sr_keys.append(i)
            self.srlist.insert("end", self.sr_line(s))

    @staticmethod
    def sr_line(s):
        codes = sorted(s["codes"], key=core._code_order)
        what = (" & ".join(codes) if len(codes) == 2 and core._codes_to_entry_fields(codes)[0]["mid_label"] == "&"
                else " TO ".join(codes) if len(codes) == 2 else " ".join(codes))
        where = "  (in ring)" if s.get("in_ring") else ""
        tag = "  <- CHECK" if s.get("unsure") else ""
        return "%3d,%-3d  %s%s%s" % (s["row"], s["col"], what, where, tag)

    def sr_at(self, key):
        """Index of the special run on hexagon key, or None."""
        if not self.result:
            return None
        for i, s in enumerate(self.result["symbols"]["srs"]):
            if (s["row"], s["col"]) == key:
                return i
        return None

    def selected_sr(self):
        sel = self.srlist.curselection()
        return self.sr_keys[sel[0]] if sel else None

    def center_on_selected_sr(self):
        i = self.selected_sr()
        if i is not None and self.result:
            s = self.result["symbols"]["srs"][i]
            self.center_on(s["x"], s["y"])
            self.draw()

    def edit_selected_sr(self):
        i = self.selected_sr()
        if i is not None:
            s = self.result["symbols"]["srs"][i]
            self.edit_sr((s["row"], s["col"]))

    def rebuild_srs(self):
        """The list of special runs is the truth; write it into the Map creator dict again."""
        core.apply_symbols_to_map(self.result["map"], self.result["symbols"])
        self.fill_cities()

    def remove_sr(self, key):
        i = self.sr_at(key)
        if i is None:
            return
        del self.result["symbols"]["srs"][i]
        self.edited = True
        self.rebuild_srs()
        self.draw()

    def edit_sr(self, key):
        i = self.sr_at(key)
        cur = self.result["symbols"]["srs"][i] if i is not None else None
        top = tk.Toplevel(self.root)
        top.title("Special run at %d,%d" % key)
        top.configure(bg=THEME["bg"])
        top.resizable(False, False)
        top.transient(self.root)
        make_modal(top)
        codes = tk.StringVar(value=" ".join(sorted(cur["codes"], key=core._code_order)) if cur else "")
        fr = tk.Frame(top, bg=THEME["bg"])
        fr.pack(padx=16, pady=12)
        tk.Label(fr, text="SR codes:", bg=THEME["bg"]).grid(row=0, column=0, sticky="w")
        e1 = new_entry(fr, textvariable=codes, width=22)
        e1.grid(row=0, column=1, padx=6)
        tk.Label(top, text="One or more of O1-O6 (odd), E1-E6 (even), A1-A6 (all), separated by spaces.\n"
                           "The same symbol for ODD 3 and EVEN 3 is written  O3 E3.", bg=THEME["bg"], fg=THEME["dim"],
                 justify="left").pack(padx=12)
        err = tk.Label(top, text="", bg=THEME["bg"], fg="#b3261e")
        err.pack()

        def ok():
            lst = [c.upper() for c in re.split(r"[\s,;&]+", codes.get().strip()) if c]
            if not lst or not all(re.fullmatch(r"[OEA][1-6]", c) for c in lst):
                err.configure(text="Each code is O, E or A followed by 1 to 6.")
                return
            lst = sorted(set(lst), key=core._code_order)
            if cur:
                cur["codes"] = lst
                cur["unsure"] = False
            else:
                h = self.result["grid"].hexes[key]
                in_ring = "%d,%d" % key in self.result["map"]["cities"]
                color = "#800080"
                for g in (self.result["symbols"].get("legend") or {}).get("groups", []):
                    if lst[0] in g["codes"]:
                        color = g["color"]
                self.result["symbols"]["srs"].append(dict(
                    row=key[0], col=key[1], codes=lst, color=color, dx=0.0, dy=-0.54 if in_ring else 0.0,
                    x=h["x"], y=h["y"], in_ring=in_ring, unsure=False))
                self.result["symbols"]["srs"].sort(key=lambda s_: (s_["row"], s_["col"]))
            self.edited = True
            top.destroy()
            self.rebuild_srs()
            self.draw()
        row = tk.Frame(top, bg=THEME["bg"])
        row.pack(pady=(4, 12))
        tk.Button(row, text="OK", width=9, command=ok).pack(side="left", padx=4)
        tk.Button(row, text="Cancel", width=9, command=top.destroy).pack(side="left", padx=4)
        e1.focus_set()
        top.bind("<Return>", lambda e: ok())

    def city_line(self, key):
        c = self.result["map"]["cities"].get("%d,%d" % key)
        if c:
            if c.get("double"):
                what = "%s %s %s" % (c["double"][0], c.get("mid_label", "TO"), c["double"][1])
            else:
                what = str(c.get("single") or "")
            tag = "  <- CHECK" if self.result["rings"].get(key, {}).get("unsure") else ""
        else:
            rd = self.result["rings"].get(key, {})
            what = "?  (read '%s')" % rd.get("text", "")
            tag = "  <- CHECK"
        return "%3d,%-3d  %s%s" % (key[0], key[1], what, tag)

    def refresh_city(self, key):
        if key in self.city_keys:
            i = self.city_keys.index(key)
            self.cities.delete(i)
            self.cities.insert(i, self.city_line(key))
        else:
            self.fill_cities()

    def selected_key(self):
        sel = self.cities.curselection()
        return self.city_keys[sel[0]] if sel else None

    def center_on_selected_city(self):
        key = self.selected_key()
        if key and self.result and key in self.result["grid"].hexes:
            h = self.result["grid"].hexes[key]
            self.center_on(h["x"], h["y"])
            self.draw()

    def edit_selected_city(self):
        key = self.selected_key()
        if key:
            self.edit_city(key)

    # ---------- drawing ----------
    def set_zoom(self, z):
        if not self.base_img:
            return
        w, h = self.base_img.size
        z = max(0.05, min(4.0, z))
        while w * z * h * z > 60e6:
            z *= 0.9
        self.zoom = z
        self.draw()

    def fit(self):
        if not self.base_img:
            return
        self.root.update_idletasks()
        cw, ch = max(200, self.canvas.winfo_width()), max(200, self.canvas.winfo_height())
        w, h = self.base_img.size
        self.set_zoom(min(cw / float(w), ch / float(h)))

    def center_on(self, x, y):
        z = self.zoom
        w, h = self.base_img.size
        cw, ch = self.canvas.winfo_width(), self.canvas.winfo_height()
        self.canvas.xview_moveto(max(0.0, (x * z - cw / 2.0) / max(1.0, w * z)))
        self.canvas.yview_moveto(max(0.0, (y * z - ch / 2.0) / max(1.0, h * z)))

    def draw(self):
        c = self.canvas
        c.delete("all")
        if not self.base_img:
            return
        z = self.zoom
        w, h = self.base_img.size
        W, H = max(1, int(w * z)), max(1, int(h * z))
        if self.show["picture"].get():
            img = self.base_img.resize((W, H), Image.BILINEAR if z < 1 else Image.NEAREST)
        else:
            img = Image.new("RGB", (W, H), "white")
        if self.result:
            d = ImageDraw.Draw(img)
            self.draw_overlay(d, z)
        self.last_img = img
        self.tk_img = ImageTk.PhotoImage(img)
        c.create_image(0, 0, image=self.tk_img, anchor="nw")
        c.configure(scrollregion=(0, 0, W, H))
        self.zoom_label.configure(text="%d %%" % round(z * 100))

    def draw_overlay(self, d, z):
        res = self.result
        g = res["grid"]
        m = res["map"]
        if self.show["terrain"].get():
            rr = max(2, int(g.W * 0.12 * z))
            for k, v in m["terrain"].items():
                r_, c_ = map(int, k.split(","))
                hx = g.hexes.get((r_, c_))
                if not hx:
                    continue
                x, y = hx["x"] * z, hx["y"] * z
                d.ellipse((x - rr, y - rr, x + rr, y + rr), fill=v["color"], outline="#333333")
        if self.show["edges"].get():
            wdt = max(2, int(3 * z + 1))
            for rv in m["rivers"]:
                pts, _ = g.edge_points(rv["row"], rv["col"], rv["side"], n=2, margin=0.0)
                col = "#ff00cc" if rv["mode"] == "Border" else "#00e0ff"
                d.line([(pts[0][0] * z, pts[0][1] * z), (pts[1][0] * z, pts[1][1] * z)], fill=col, width=wdt)
        if self.show["rings"].get():
            rad = g.W * 0.5 * z
            try:
                font = ImageFont.truetype("arialbd.ttf", max(9, int(11 * max(z, 0.6) * 1.2)))
            except Exception:
                font = ImageFont.load_default()
            keys = set(res["rings"]) | set(tuple(int(v) for v in k.split(",")) for k, v in m["cities"].items()
                                           if not v.get("ring_disabled"))
            for key in keys:
                hx = g.hexes.get(key)
                if not hx:
                    continue
                x, y = hx["x"] * z, hx["y"] * z
                ok = "%d,%d" % key in m["cities"]
                d.ellipse((x - rad, y - rad, x + rad, y + rad), outline="#ff8800" if ok else "#ff0000", width=3)
                label = "?"
                if ok:
                    cc = m["cities"]["%d,%d" % key]
                    label = ("%s %s %s" % (cc["double"][0], cc.get("mid_label", "TO"), cc["double"][1])
                             if cc.get("double") else str(cc.get("single") or ""))
                d.text((x - rad, y + rad), label, fill="#000000" if ok else "#ff0000", font=font)
        if self.show["sr"].get():
            self.draw_sr_layer(d, z)

    def draw_sr_layer(self, d, z):
        """Special runs: a magenta circle (orange = please check) with the codes; cyan square = a coloured
        symbol-sized blob that matched no legend symbol."""
        res = self.result
        sym = res.get("symbols") or {}
        rad = max(6, res["grid"].W * 0.22 * z)
        try:
            font = ImageFont.truetype("arialbd.ttf", max(9, int(11 * max(z, 0.6) * 1.2)))
        except Exception:
            font = ImageFont.load_default()
        for s in sym.get("srs", []):
            x, y = s["x"] * z, s["y"] * z
            col = "#ff8800" if s.get("unsure") else "#d000d0"
            d.ellipse((x - rad, y - rad, x + rad, y + rad), outline=col, width=3)
            d.text((x + rad + 2, y - rad), " ".join(sorted(s["codes"], key=core._code_order)), fill=col, font=font)
        for u in sym.get("unknown", []):
            x, y = u["x"] * z, u["y"] * z
            d.rectangle((x - rad, y - rad, x + rad, y + rad), outline="#00b0b0", width=2)
        lg = sym.get("legend")
        if lg:
            cs = [e["cluster"] for e in lg["entries"]]
            x0, y0 = min(c["x0"] for c in cs) * z, min(c["y0"] for c in cs) * z
            x1, y1 = max(c["x0"] + c["w"] for c in cs) * z, max(c["y0"] + c["h"] for c in cs) * z
            d.rectangle((x0 - 4, y0 - 4, x1 + 4, y1 + 4), outline="#d000d0", width=2)
            for e in lg["entries"]:
                c = e["cluster"]
                d.text(((c["x0"] + c["w"] + 4) * z, c["y0"] * z), e["code"], fill="#d000d0", font=font)

    # ---------- mouse ----------
    def pic_xy(self, event):
        return self.canvas.canvasx(event.x) / self.zoom, self.canvas.canvasy(event.y) / self.zoom

    def nearest_hex(self, x, y):
        g = self.result["grid"] if self.result else None
        if not g:
            return None
        best, bd = None, None
        for k, h in g.hexes.items():
            dd = (h["x"] - x) ** 2 + (h["y"] - y) ** 2
            if bd is None or dd < bd:
                best, bd = k, dd
        return best if bd is not None and bd <= (g.W * 0.7) ** 2 else None

    def on_click(self, event):
        self.canvas.scan_mark(event.x, event.y)
        if self.pick_mode:
            x, y = self.pic_xy(event)
            self.toggle_pick(False)
            self.start_import((x, y))
            return
        if self.result:
            key = self.nearest_hex(*self.pic_xy(event))
            if key in getattr(self, "city_keys", []):
                i = self.city_keys.index(key)
                self.cities.selection_clear(0, "end")
                self.cities.selection_set(i)
                self.cities.see(i)
            si = self.sr_at(key) if key is not None else None
            if si is not None and si in self.sr_keys:
                j = self.sr_keys.index(si)
                self.srlist.selection_clear(0, "end")
                self.srlist.selection_set(j)
                self.srlist.see(j)

    def on_right_click(self, event):
        if not self.result:
            return
        key = self.nearest_hex(*self.pic_xy(event))
        if key is None:
            return
        menu = tk.Menu(self.root, tearoff=0)
        menu.add_command(label="Hexagon %d,%d" % key, state="disabled")
        menu.add_command(label="City here...", command=lambda: self.edit_city(key))
        c_here = self.result["map"]["cities"].get("%d,%d" % key)
        if c_here and not c_here.get("ring_disabled"):
            menu.add_command(label="Remove the city", command=lambda: self.remove_city(key))
        menu.add_command(label="Special run here...", command=lambda: self.edit_sr(key))
        if self.sr_at(key) is not None:
            menu.add_command(label="Remove the special run", command=lambda: self.remove_sr(key))
        sub = tk.Menu(menu, tearoff=0)
        for t in TERRAIN_CHOICES:
            sub.add_command(label=t, command=lambda t=t: self.set_terrain(key, t))
        sub.add_command(label="Foreign (copy colour of this hexagon's neighbour)...", command=lambda: self.set_foreign(key))
        menu.add_cascade(label="Terrain", menu=sub)
        menu.tk_popup(event.x_root, event.y_root)

    def on_wheel(self, event):
        self.canvas.yview_scroll(-1 if event.delta > 0 else 1, "units")

    def on_ctrl_wheel(self, event):
        self.set_zoom(self.zoom * (1.15 if event.delta > 0 else 1 / 1.15))

    def toggle_pick(self, on=None):
        self.pick_mode = (not self.pick_mode) if on is None else on
        self.canvas.configure(cursor="crosshair" if self.pick_mode else "")
        self.pick_btn.configure(relief="sunken" if self.pick_mode else "flat")
        if self.pick_mode:
            self.status.set("Click inside ONE empty hexagon (no city, no text, no river) to start the grid search.")

    # ---------- editing ----------
    def set_terrain(self, key, t):
        col = core.TERRAIN_COLORS[t]
        self.result["map"]["terrain"]["%d,%d" % key] = dict(color=core.hexcolor(col), merge=False, type=t)
        self.edited = True
        self.draw()

    def set_foreign(self, key):
        # the colour of the nearest hexagon that is already Foreign
        mine = self.result["map"]["terrain"]
        g = self.result["grid"]
        best, bd = None, None
        for k, v in mine.items():
            if v.get("is_foreign"):
                r_, c_ = map(int, k.split(","))
                h = g.hexes.get((r_, c_))
                dd = (h["x"] - g.hexes[key]["x"]) ** 2 + (h["y"] - g.hexes[key]["y"]) ** 2
                if bd is None or dd < bd:
                    best, bd = v["color"], dd
        mine["%d,%d" % key] = dict(color=best or "#f4f799", merge=False, type="Plain", is_foreign=True)
        self.edited = True
        self.draw()

    def remove_city(self, key):
        self.result["map"]["cities"].pop("%d,%d" % key, None)
        self.edited = True
        self.rebuild_srs()                  # a special run on this hexagon becomes a city entry again
        self.draw()

    def edit_city(self, key):
        cities = self.result["map"]["cities"]
        cur = cities.get("%d,%d" % key)
        if cur and cur.get("ring_disabled"):
            cur = None                      # that entry is a special run, not a city ring
        top = tk.Toplevel(self.root)
        top.title("City at %d,%d" % key)
        top.configure(bg=THEME["bg"])
        top.resizable(False, False)
        top.transient(self.root)
        make_modal(top)
        kind = tk.StringVar(value="double" if cur and cur.get("double") else "single")
        a = tk.StringVar(value=(cur.get("double") or [cur.get("single") or "", ""])[0] if cur and cur.get("double")
                         else (cur.get("single") or "" if cur else ""))
        b = tk.StringVar(value=(cur["double"][1] if cur and cur.get("double") else ""))
        mid = tk.StringVar(value=(cur.get("mid_label", "TO") if cur else "TO"))
        fr = tk.Frame(top, bg=THEME["bg"])
        fr.pack(padx=16, pady=12)
        tk.Radiobutton(fr, text="One number", variable=kind, value="single", bg=THEME["bg"]).grid(row=0, column=0, sticky="w")
        tk.Radiobutton(fr, text="Two numbers (e.g. 41 TO 44)", variable=kind, value="double", bg=THEME["bg"]).grid(row=1, column=0, sticky="w")
        e1 = new_entry(fr, textvariable=a, width=5)
        e1.grid(row=0, column=1, padx=6)
        e2 = new_entry(fr, textvariable=b, width=5)
        e2.grid(row=1, column=1, padx=6)
        tk.Label(fr, text="between:", bg=THEME["bg"]).grid(row=1, column=2)
        tk.OptionMenu(fr, mid, "TO", "AND").grid(row=1, column=3)
        tk.Label(top, text="Numbers are two digits, each 1 to 6 (11 ... 66).", bg=THEME["bg"], fg=THEME["dim"]).pack()
        err = tk.Label(top, text="", bg=THEME["bg"], fg="#b3261e")
        err.pack()

        def ok():
            nums = [a.get().strip()] + ([b.get().strip()] if kind.get() == "double" else [])
            if not all(re.fullmatch(r"[1-6][1-6]", n) for n in nums):
                err.configure(text="Each number must be two digits from 1 to 6.")
                return
            e = dict(core.CITY_DEFAULTS)
            if cur:
                e.update(cur)
            if kind.get() == "single":
                e.update(single=nums[0], double=None)
            else:
                e.update(single=None, double=nums, mid_label=mid.get())
            cities["%d,%d" % key] = e
            if key in self.result["rings"]:
                self.result["rings"][key]["unsure"] = False
            self.edited = True
            top.destroy()
            self.rebuild_srs()              # a special run on this hexagon moves to multi_srs texts
            self.draw()
        row = tk.Frame(top, bg=THEME["bg"])
        row.pack(pady=(4, 12))
        tk.Button(row, text="OK", width=9, command=ok).pack(side="left", padx=4)
        tk.Button(row, text="Cancel", width=9, command=top.destroy).pack(side="left", padx=4)
        e1.focus_set()
        top.bind("<Return>", lambda e: ok())

    # ---------- saving ----------
    def save_map(self):
        if not self.result:
            messagebox.showinfo(APP_TITLE, "Nothing to save yet - open a picture first.", parent=self.root)
            return
        folder = find_maps_folder() or self.settings.get("last_save_dir") or os.path.dirname(self.picture_path)
        base = os.path.splitext(os.path.basename(self.picture_path))[0] + ".json"
        p = filedialog.asksaveasfilename(parent=self.root, title="Save the map", initialdir=folder, initialfile=base,
                                         defaultextension=".json", filetypes=[("Map creator map", "*.json")])
        if not p:
            return
        if os.path.exists(p) and not messagebox.askyesno(APP_TITLE, "%s exists.\nReplace it?" % os.path.basename(p), parent=self.root):
            return
        try:
            core.save_map(self.result, p)
        except Exception as e:
            messagebox.showerror(APP_TITLE, "Could not save:\n%s" % e, parent=self.root)
            return
        self.settings["last_save_dir"] = os.path.dirname(p)
        save_json(SETTINGS_FILE, self.settings)
        self.edited = False
        self.status.set("Saved %s - open it in Map creator (Archive > Open)." % p)

    # ---------- help, about, closing ----------
    def about(self):
        show_about(self.root, "Rail Import", "Turns a map picture into a Railroad Racing map", "🗺️")

    def help(self):
        show_text(self.root, "Help - Rail Import", HELP_TEXT)

    def close(self):
        if self.edited and not messagebox.askyesno(APP_TITLE, "You have edited the map and not saved it.\nClose anyway?", parent=self.root):
            return
        self.root.destroy()


# *************** DEL 50 - HELP *****************

HELP_TEXT = """RAIL IMPORT - a map picture becomes a Map creator map

WHAT TO DO
1. Open picture...  Choose a BMP / PNG / JPG of a hex map (your MS Paint maps work).  The program
   finds the hexagon grid by itself, reads the terrain colours, the blue / red lines on the edges and
   the red city rings with their numbers, and draws what it understood on top of the picture.
2. Look at the result.  Show: Picture / Terrain / Edges / Cities / Special runs switch the layers.  Zoom with - + Fit,
   or Ctrl + mouse wheel.  Drag with the left or middle mouse button.
3. Fix what is wrong.  Right-click a hexagon: City here... (type its numbers), Remove the city, Terrain.
   The list "City rings" marks the rings it could not read with <- CHECK; double-click one to type it.
4. Save map (.json)...  The map goes to Rail_files\\Maps when this program sits in Railroad_racing.
   Open it in Map creator (Archive > Open) and carry on there.

IF NO GRID IS FOUND
Press Grid start... and click inside ONE empty hexagon (no city, no text), then it searches from there.

WHAT IT READS
  Terrain       white = Plain, orange = Hill, green = Forest, blue = Water ... (Map creator's colours);
                any other pale colour that fills whole hexagons becomes a Foreign hexagon.
  Edges         blue line = River (thickness 1-3 from the line width); pure red line = Border;
                a blue line between a Foreign and a home hexagon = Border.
  City rings    red ring: one number (single), 'AA TO BB' (double) or 'AA AND BB'.  The numbers are
                matched against the font the maps use; if a file next to the picture has the same name
                with .places, the numbers are checked against that list and the map info (places,
                special runs) is copied into the map.
  Special runs  the small stars / flags.  The legend (a column of symbols beside a list of names: ODD and
                EVEN side by side, or one list 1-6) tells which symbol is which run; every other copy of
                that symbol on the map becomes that run.  Codes as Map creator writes them: O1-O6 (odd
                list), E1-E6 (even list), A1-A6 (one list for both).  The same symbol in ODD 3 and EVEN 3 =
                'O3 & E3'; the same symbol in two rows of one list = 'A1 TO A2'.  A hexagon without a
                city ring gets a special-run city entry (coloured code text, ring switched off); a
                hexagon WITH a ring gets small code texts (multi_srs) where the symbol stood.
                The list "Special runs" shows them (<- CHECK = please look); right-click a hexagon:
                Special run here... / Remove the special run.  Orange circle = check it, cyan square =
                a coloured blob of symbol size that matches no legend symbol.
NOT READ YET (add them in Map creator): place names as texts on the map, roads, legend text (the pictures
that list the runs by country without symbols - Russia, Macedonia style - give no special runs).
The list under "What was found" says so for every map.

THE NUMBERING
Map creator's row, col.  The first row / column that holds a hexagon is 0.  Pointy maps keep odd rows
shifted right, flat maps (saved as 'flat2') keep odd columns shifted down - the same as your own maps.

Starting from a command line:  RailImport.py "C:\\...\\map.bmp"
Needs Python 3 with numpy and Pillow (the same as Hex Labels).
"""

WHATS_NEW = """WHAT'S NEW

1.1  (2026-11-19)  Special runs: stars / flags are read through the legend (ODD / EVEN or one list), put
                   on the right hexagons as Map creator special-run entries, listed, drawn, editable.
1.0  (2026-11-19)  First version: grid search, terrain, rivers / borders, city rings and numbers,
                   .places info, hand fixes, save as Map creator .json.
"""


def show_text(root, title, text):
    top = tk.Toplevel(root)
    top.title(title)
    top.transient(root)
    make_modal(top)
    top.geometry("760x600")
    fr = tk.Frame(top)
    fr.pack(fill="both", expand=True, padx=6, pady=6)
    sb = tk.Scrollbar(fr)
    sb.pack(side="right", fill="y")
    txt = new_text(fr, wrap="word", yscrollcommand=sb.set, font=("Segoe UI", 10), padx=10, pady=8)
    txt.pack(side="left", fill="both", expand=True)
    sb.configure(command=txt.yview)
    txt.insert("1.0", text)
    txt.configure(state="disabled")
    tk.Button(top, text="Close", width=10, command=top.destroy).pack(pady=(0, 8))
    return top


# *************** DEL 90 - START *****************

def main():
    picture = None
    for a in sys.argv[1:]:
        if os.path.isfile(a):
            picture = a
    _set_app_id()                                   # BEFORE tk.Tk()
    root = tk.Tk()
    ImportWindow(root, picture)
    root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
    root.mainloop()


if __name__ == "__main__":
    main()
