# -*- coding: utf-8 -*-
# =============================================================================
# RailHub.py  -  the front door of Railroad Racing / Railway Rivals.
#
# EVERYTHING INSIDE THIS PROGRAM IS ENGLISH (code, comments, UI text, Help) - rule 1.
#
# What it does (Lars, 2026-11-19, WP0 of Railroad_racing_plan\PLAN.md):
#   * One window with a tile for every Railroad Racing program, each with a one-line role:
#       Map creator (for map makers), Game central (for game masters), Playpen (for players),
#       Hex labels, Rail Maps library and the extra tools (race generator, invalid races,
#       NW route trainer, Json map reader).
#   * Start button per tile.  A tile says "Ready - files from <date>" (so you can see WHICH copy
#     will run), "Running", or WHY it cannot start (file missing).  A program that closes at
#     once with an error is reported, with a hint where its crash log is.
#   * "Newest maps" list (Rail_files\Maps), folder buttons (maps, Rail_files, logs, manual).
#   * "Picture import" (Rail_import\RailImport.py) turns a map picture into a map; a greyed "soon" tile kind
#     still exists for what is built next (tracing an ordinary map,
#     tracing an ordinary map).
#   * Notes (Player text popup), Help, What's new, About.
#
# Where it lives:  <Railroad_racing>\Rail_hub\RailHub.py   (its data: <Railroad_racing>\Helpfiles\RailHub)
# The programs are found from the hub's own location (a folder that holds Map_creator and
# Game_central).  Options:   RailHub.py --root "X:\...\Railroad_racing"     (testing)
#                            Helpfiles\RailHub\settings.json:  "rail_root", "python" (a pythonw.exe)
#
# Needs: Python 3 (tkinter only).  The programs it starts need what THEY need (Pillow, numpy ...).
#
# ToDo (nice to have): "Open this map with ..." needs a tiny sys.argv open-file hook in Map creator,
# Game central and Playpen (not in them today); a Picture import / Trace tile as soon as WP1/WP2
# exist; icon Icons\RailHub.ico (delivered separately, rule 10_icons).
# =============================================================================

import os
import sys
import json
import time
import shutil
import subprocess
import webbrowser
import ctypes
import platform
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk, messagebox


# *************** 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 04 - 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 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 06 - 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 10 - SETTINGS AND LOOK *****************
# ToDo: more tiles when Lars adds programs: add one dict to build_catalog().

APP_TITLE = "Rail Hub"
HUB_VERSION = "1.1"
SETTINGS_FILE = os.path.join(PROGRAM_HF_DIR, "settings.json")

THEME = dict(bg="#f4f4f8", panel="#e4e4ec", fg="#1a1a22", dim="#606070",
             accent="#3b7ddd", btn="#d8d8e4", btnfg="#1a1a22",
             field="#ffffff", field_fg="#000000")
OK_COLOR, BAD_COLOR, RUN_COLOR, SOON_COLOR = "#1b7f3b", "#b3261e", "#1d5fc4", "#808090"

TILE_W, TILE_H = 306, 96          # fixed: text never changes the layout (rule 6)


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


# *************** DEL 20 - FINDING THE RAIL FOLDER AND THE PROGRAMS *****************
# The programs live side by side in ONE folder (Railroad_racing): Map_creator, Game_central,
# Playpen, Rail---Extra_tools, Rail_files ...  Hex_Labels and Rail_Maps are ordinary programs of
# Lars's tree (Py\Hex_Labels.py, or Folder-exe\Hex_Labels\Hex_Labels.exe) found by walking up.

def _has_rail_programs(d):
    return os.path.isdir(os.path.join(d, "Map_creator")) and os.path.isdir(os.path.join(d, "Game_central"))


def find_rail_root(cli_root=None, settings=None):
    """The folder that holds Map_creator and Game_central."""
    for cand in (cli_root, (settings or {}).get("rail_root")):
        if cand and os.path.isdir(cand):
            return os.path.abspath(cand)
    here = os.path.dirname(os.path.abspath(sys.executable if getattr(sys, "frozen", False) else __file__))
    d = here
    for _ in range(4):
        if _has_rail_programs(d):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return os.path.dirname(here)         # the normal place (Rail_hub is a child of Railroad_racing)


def build_catalog(R):
    """Every tile.  kind: script = a .py in the Rail folder, app = one of my programs found in
    Py\\ / Folder-exe\\ (walking up from the Rail folder), soon = a greyed placeholder."""
    X = os.path.join
    ex = X(R, "Rail---Extra_tools")
    return [
        dict(id="map_creator", group="Make maps", title="Map creator", kind="script",
             path=X(R, "Map_creator", "main.py"), stamp=("ui.py", "map.py", "map_model.py"),
             role="For MAP MAKERS.  Draw hex maps with terrain, rivers, roads, cities and "
                  "special runs; saves .json."),
        dict(id="hex_labels", group="Make maps", title="Hex labels", kind="app", name="Hex_Labels",
             role="Writes A1-style names on every hexagon of a map picture (BMP, PNG, JPG).  "
                  "Finds the grid by itself."),
        dict(id="picture_import", group="Make maps", title="Picture import", kind="script",
             path=X(R, "Rail_import", "RailImport.py"), stamp=("rail_import_core.py", "hexgrid.py"),
             role="Turns a map picture (your MS Paint maps) into a Map creator .json: terrain, "
                  "rivers, city numbers."),
        dict(id="game_central", group="Games", title="Game central", kind="script",
             path=X(R, "Game_central", "main.py"), stamp=("ui.py", "map.py", "map_model.py"),
             role="For GAME MASTERS.  Create games and races, send and collect rounds, "
                  "scoring and the race phase."),
        dict(id="playpen", group="Games", title="Playpen", kind="script",
             path=X(R, "Playpen", "main.py"), stamp=("ui.py", "map.py", "map_model.py"),
             role="For PLAYERS.  Draw your railroad on the map, round by round."),
        dict(id="rail_maps", group="Games", title="Rail Maps library", kind="app", name="Rail_Maps",
             role="The Railway Rivals map library and its web page (maps on Google Drive)."),
        dict(id="race_generator", group="Tools", title="Race generator", kind="script",
             path=X(ex, "Rail_2026---Race_generator_(standalone).py"), stamp=(),
             role="Standalone path analyzer: load a map .json, pick a player and places, "
                  "see the shortest routes."),
        dict(id="invalid_races", group="Tools", title="Invalid races", kind="script",
             path=X(ex, "Rail_2026---Invalid_races_7b-FIXED.py"), stamp=(),
             role="Matches city numbers with their names and finds the races that are not "
                  "valid (terrain-aware)."),
        dict(id="nw_trainer", group="Tools", title="NW route trainer", kind="script",
             path=X(ex, "nw_route_trainer_v12.py"), stamp=(),
             role="Route training on a map: look-ahead panel, budget tracker, split and "
                  "multi-hex cities."),
        dict(id="json_reader", group="Tools", title="Json map reader", kind="script",
             path=X(ex, "Rail_2026---Json_map_reader.py"), stamp=(),
             role="Opens a Map creator .json map and shows what it holds."),
    ]


def _real_python_for_hub(settings):
    """The pythonw.exe to start the programs with: settings.json 'python' first, else the real one
    (never sys.executable blindly, never a 0-byte Store stub - block_open._real_pythonw)."""
    p = (settings or {}).get("python")
    try:
        if p and os.path.isfile(p) and os.path.getsize(p) > 0:
            return p
    except OSError:
        pass
    return _real_pythonw()


def _app_roots(R):
    """Trees that may hold Py\\ and Folder-exe\\: the Rail folder's ancestors, then my own."""
    roots, d = [], os.path.abspath(R)
    for _ in range(5):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    for r in _my_app_roots():
        if r not in roots:
            roots.append(r)
    return roots


def newest_mtime(paths):
    best = 0.0
    for p in paths:
        try:
            best = max(best, os.path.getmtime(p))
        except OSError:
            pass
    return best


def day(ts):
    return time.strftime("%Y-%m-%d", time.localtime(ts)) if ts else "?"


def resolve(entry, R, settings):
    """What would Start do?  Returns dict(ok, cmd, cwd, stamp, why).  Never raises."""
    out = dict(ok=False, cmd=None, cwd=None, stamp=0.0, why="")
    try:
        kind = entry["kind"]
        if kind == "soon":
            out["why"] = "Coming soon"
            return out
        pyw = _real_python_for_hub(settings)
        if kind == "script":
            script = entry["path"]
            if not os.path.isfile(script):
                rel = script[len(R):].lstrip("\\/") if script.lower().startswith(R.lower()) else script
                out["why"] = "Missing: " + rel
                return out
            if not pyw:
                out["why"] = "No Python found (set 'python' in settings.json)"
                return out
            folder = os.path.dirname(script)
            names = [script] + [os.path.join(folder, n) for n in entry.get("stamp", ())]
            out.update(ok=True, cmd=[pyw, script], cwd=folder, stamp=newest_mtime(names))
            return out
        if kind == "app":
            name = entry["name"]
            for home in _app_roots(R):
                script = os.path.join(home, "Py", name + ".py")
                exe = os.path.join(home, "Folder-exe", name, name + ".exe")
                if os.path.isfile(script) and pyw:
                    out.update(ok=True, cmd=[pyw, script], cwd=os.path.dirname(script),
                               stamp=newest_mtime([script]))
                    return out
                if os.path.isfile(exe):          # no source, or no interpreter
                    out.update(ok=True, cmd=[exe], cwd=os.path.dirname(exe), stamp=newest_mtime([exe]))
                    return out
            out["why"] = "Not found: Py\\%s.py (copy it there)" % name
            return out
    except Exception as e:                        # a tile problem must never stop the hub
        out["why"] = "Error: %s" % e
    return out


def explorer_path():
    return os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "explorer.exe")   # rule 8: real path


def newest_maps(R, limit=4):
    """The newest .json maps of Rail_files\\Maps (and its 0---Finished folder): [(mtime, path)]."""
    found = []
    for folder in (os.path.join(R, "Rail_files", "Maps"), os.path.join(R, "Rail_files", "Maps", "0---Finished")):
        try:
            with os.scandir(folder) as it:
                for e in it:
                    if e.is_file() and e.name.lower().endswith(".json"):
                        found.append((e.stat().st_mtime, e.path))
        except OSError:
            pass
    found.sort(reverse=True)
    return found[:limit]


# *************** DEL 30 - THE HUB WINDOW *****************

class Hub(object):
    def __init__(self, root, rail_root, settings):
        self.root = root
        self.R = rail_root
        self.settings = settings
        self.notes = None
        self.procs = {}                  # tile id -> [Popen, ...]
        self.tiles = {}                  # tile id -> dict(status=Label, button=Button)
        self.catalog = build_catalog(rail_root)
        root.title("%s %s" % (APP_TITLE, HUB_VERSION))
        root.configure(bg=THEME["bg"])
        root.geometry(settings.get("geometry") or "970x690")
        root.minsize(960, 660)
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        root.bind("<F1>", lambda e: self.help())
        self.build()
        self.refresh()
        root.after(300, self.fill_maps)
        root.after(2000, self.tick)

    # ---- layout ----------------------------------------------------------------------------
    def build(self):
        T = THEME
        top = tk.Frame(self.root, bg=T["bg"])
        top.pack(fill="x", padx=14, pady=(10, 0))
        tk.Label(top, text="Railroad Racing", bg=T["bg"], fg=T["accent"],
                 font=("Segoe UI", 20, "bold")).pack(side="left")
        tk.Label(top, text="  Railway Rivals on a computer: make maps, run games, play",
                 bg=T["bg"], fg=T["dim"], font=("Segoe UI", 10)).pack(side="left", pady=(10, 0))
        self.lbl_root = tk.Label(self.root, text="", bg=T["bg"], fg=T["dim"], font=("Segoe UI", 8),
                                 anchor="w")
        self.lbl_root.pack(fill="x", padx=16)

        body = tk.Frame(self.root, bg=T["bg"])
        body.pack(fill="both", expand=True, padx=8, pady=(2, 0))
        row = 0
        groups = []
        for e in self.catalog:
            if e["group"] not in groups:
                groups.append(e["group"])
        for g in groups:
            tk.Label(body, text=g, bg=T["bg"], fg=T["fg"], font=("Segoe UI", 11, "bold"),
                     anchor="w").grid(row=row, column=0, columnspan=3, sticky="w", padx=8, pady=(8, 0))
            row += 1
            col = 0
            for e in [x for x in self.catalog if x["group"] == g]:
                self.make_tile(body, e, row, col)
                col += 1
                if col == 3:
                    col, row = 0, row + 1
            if col != 0:
                if g == "Tools":
                    self.make_maps_box(body, row, col)       # fills the free space of the last row
                row += 1
        # bottom bar
        bar = tk.Frame(self.root, bg=T["panel"])
        bar.pack(fill="x", side="bottom")
        for text, cmd in (("Maps folder", lambda: self.open_folder(("Rail_files", "Maps"))),
                          ("Rail_files", lambda: self.open_folder(("Rail_files",))),
                          ("Logs", lambda: self.open_folder(("Rail_files", "Logs"))),
                          ("Manual", self.open_manual)):
            self._button(bar, text, cmd, 11).pack(side="left", padx=(8, 0), pady=7)
        for text, cmd in (("About", self.about), ("Notes", self.open_notes),
                          ("What's new", self.whats_new), ("Help", self.help)):
            self._button(bar, text, cmd, 10).pack(side="right", padx=(0, 8), pady=7)
        self.lbl_status = tk.Label(self.root, text="", bg=T["bg"], fg=T["dim"], font=("Segoe UI", 9),
                                   anchor="w")
        self.lbl_status.pack(fill="x", side="bottom", padx=14)

    def _button(self, parent, text, cmd, width):
        T = THEME
        return tk.Button(parent, text=text, command=cmd, width=width, bg=T["btn"], fg=T["btnfg"],
                         activebackground=T["accent"], relief="groove", font=("Segoe UI", 9))

    def make_tile(self, parent, e, row, col):
        T = THEME
        f = tk.Frame(parent, bg=T["panel"], width=TILE_W, height=TILE_H, highlightthickness=1,
                     highlightbackground="#c4c4d4")
        f.grid(row=row, column=col, padx=6, pady=5)
        f.grid_propagate(False)
        f.pack_propagate(False)
        soon = e["kind"] == "soon"
        tk.Label(f, text=e["title"], bg=T["panel"], fg=SOON_COLOR if soon else T["fg"],
                 font=("Segoe UI", 11, "bold"), anchor="w").place(x=10, y=5, width=TILE_W - 20, height=22)
        tk.Label(f, text=e["role"], bg=T["panel"], fg=T["dim"], font=("Segoe UI", 8), anchor="nw",
                 justify="left", wraplength=TILE_W - 22).place(x=10, y=28, width=TILE_W - 20, height=36)
        st = tk.Label(f, text="", bg=T["panel"], fg=T["dim"], font=("Segoe UI", 8), anchor="w")
        st.place(x=10, y=TILE_H - 26, width=TILE_W - 102, height=18)
        btn = self._button(f, "Soon" if soon else "Start", (lambda ent=e: self.start(ent)), 8)
        btn.place(x=TILE_W - 88, y=TILE_H - 32, width=78, height=24)
        if soon:
            btn.configure(state="disabled")
        self.tiles[e["id"]] = dict(status=st, button=btn)

    def make_maps_box(self, parent, row, col):
        T = THEME
        f = tk.Frame(parent, bg=T["panel"], width=TILE_W * 2 + 12, height=TILE_H, highlightthickness=1,
                     highlightbackground="#c4c4d4")
        f.grid(row=row, column=col, columnspan=3 - col, padx=6, pady=5)
        f.grid_propagate(False)
        f.pack_propagate(False)
        tk.Label(f, text="Newest maps  (double-click shows the file in its folder)", bg=T["panel"],
                 fg=T["fg"], font=("Segoe UI", 9, "bold"), anchor="w").place(x=10, y=4, width=560, height=20)
        self.lst = tk.Listbox(f, font=("Consolas", 9), activestyle="none", bg=T["field"],
                              fg=T["field_fg"], relief="flat", highlightthickness=0, exportselection=False)
        self.lst.place(x=10, y=26, width=TILE_W * 2 - 8, height=TILE_H - 34)
        self.lst.bind("<Double-Button-1>", lambda e: self.reveal_map())
        self.lst.bind("<Return>", lambda e: self.reveal_map())
        self.map_paths = []

    # ---- tile state ------------------------------------------------------------------------
    def refresh(self):
        self.lbl_root.configure(text="Rail folder:  " + self.R)
        for e in self.catalog:
            t = self.tiles.get(e["id"])
            if not t:
                continue
            live = [p for p in self.procs.get(e["id"], []) if p.poll() is None]
            self.procs[e["id"]] = live
            info = resolve(e, self.R, self.settings)
            if e["kind"] == "soon":
                t["status"].configure(text="Coming soon", fg=SOON_COLOR)
            elif live:
                t["status"].configure(text="Running (%d)" % len(live), fg=RUN_COLOR)
                t["button"].configure(state="normal" if info["ok"] else "disabled")
            elif info["ok"]:
                t["status"].configure(text="Ready - files from " + day(info["stamp"]), fg=OK_COLOR)
                t["button"].configure(state="normal")
            else:
                t["status"].configure(text=info["why"], fg=BAD_COLOR)
                t["button"].configure(state="disabled")

    def tick(self):
        try:
            self.refresh()
        except Exception:
            pass
        self.root.after(2000, self.tick)

    def set_status(self, text):
        self.lbl_status.configure(text=text)

    # ---- starting a program ---------------------------------------------------------------
    def start(self, e):
        info = resolve(e, self.R, self.settings)
        if not info["ok"]:
            messagebox.showwarning(APP_TITLE, "%s cannot start:\n%s" % (e["title"], info["why"]),
                                   parent=self.root)
            return None
        try:
            p = subprocess.Popen(info["cmd"], cwd=info["cwd"])        # Popen, never run()
        except Exception as ex:
            messagebox.showerror(APP_TITLE, "%s did not start:\n%s" % (e["title"], ex), parent=self.root)
            return None
        self.procs.setdefault(e["id"], []).append(p)
        self.set_status("Started %s (files from %s)" % (e["title"], day(info["stamp"])))
        self.root.after(2500, lambda: self.check_early_exit(e, p))
        self.refresh()
        return p

    def check_early_exit(self, e, p):
        """A program that is gone 2.5 s after the start with an error code: tell the user."""
        try:
            code = p.poll()
        except Exception:
            return
        if code is None or code == 0:
            return
        self.set_status("%s closed at once (code %s)" % (e["title"], code))
        if messagebox.askyesno(APP_TITLE,
                               "%s closed straight away (exit code %s).\n\nIt writes crashes to "
                               "Rail_files\\Logs.  Open that folder now?" % (e["title"], code),
                               parent=self.root):
            self.open_folder(("Rail_files", "Logs"))
        self.refresh()

    # ---- maps, folders, manual ------------------------------------------------------------
    def fill_maps(self):
        try:
            rows = newest_maps(self.R)
            self.map_paths = [p for _, p in rows]
            self.lst.delete(0, "end")
            if not rows:
                self.lst.insert("end", "(no .json maps found in Rail_files\\Maps)")
            for ts, p in rows:
                self.lst.insert("end", "%s  %s" % (day(ts), os.path.basename(p)))
        except Exception:
            pass

    def reveal_map(self):
        sel = self.lst.curselection()
        if not sel or sel[0] >= len(self.map_paths):
            return
        p = self.map_paths[sel[0]]
        try:
            subprocess.Popen([explorer_path(), "/select," + p])
        except Exception:
            open_path(os.path.dirname(p))

    def open_folder(self, parts):
        p = os.path.join(self.R, *parts)
        if not os.path.isdir(p):
            self.set_status("No such folder yet: " + p)
            return
        open_path(p)

    def open_manual(self):
        d = os.path.join(self.R, "Map_creator", "Hj\u00e4lpfiler")
        for n in ("manual_en.pdf", "manual_en.md"):
            p = os.path.join(d, n)
            if os.path.isfile(p):
                open_path(p)
                return
        self.set_status("No manual found in Map_creator\\Hj\u00e4lpfiler")

    # ---- small dialogs --------------------------------------------------------------------
    def about(self):
        show_about(self.root, APP_TITLE, "The front door of Railroad Racing", "\U0001F682")

    def help(self):
        show_text(self.root, "Help - " + APP_TITLE, HELP_TEXT)

    def whats_new(self):
        show_text(self.root, "What's new - " + APP_TITLE, WHATS_NEW)

    def open_notes(self):
        try:
            if self.notes is not None and self.notes.top.winfo_exists():
                self.notes.top.lift()
                return
        except Exception:
            pass
        self.settings["show_playertext"] = True
        self.notes = PlayerTextPopup(self.root, self.settings,
                                     ("show_playertext", "playertext_pos", "playertext_zoom", "playertext_sel"),
                                     self.save_settings, THEME, "Notes", PROGRAM_HF_DIR, lambda: {})

    def save_settings(self):
        save_json(SETTINGS_FILE, self.settings)

    def on_close(self):
        try:
            if self.notes is not None:
                self.notes.save_now()
        except Exception:
            pass
        try:
            self.settings["geometry"] = self.root.winfo_geometry()
        except Exception:
            pass
        self.save_settings()
        self.root.destroy()


# *************** DEL 50 - HELP AND WHAT'S NEW *****************

HELP_TEXT = """RAIL HUB - the front door of Railroad Racing

WHAT IT DOES
Starts the Railroad Racing programs from one window.  Each tile says who the program is for and
whether it is ready:
  Ready - files from <date>   the program can start; the date is when its files last changed,
                              so you can see WHICH copy will run.
  Running (n)                 started from here and still open.
  Missing / Not found ...     the file is not where it should be (the text says where).
  Coming soon                 a placeholder for something being built.

THE PROGRAMS
* Map creator  - for map makers.  Draws the hex maps (terrain, rivers, borders, roads, cities, special
                 runs, texts) and saves them as .json files.
* Game central - for game masters.  Creates games and races, sends out and collects the rounds,
                 scoring and the race phase.
* Playpen      - for players.  Draw your railroad on the map.
* Hex labels   - writes A1-style names on every hexagon of a map PICTURE.
* Picture import - turns a map PICTURE (BMP/PNG/JPG, your MS Paint maps) into a Map creator .json
                 map: finds the grid, reads terrain, rivers/borders and city numbers.  Lives in
                 Railroad_racing\\Rail_import\\ (RailImport.py + rail_import_core.py + hexgrid.py).
* Rail Maps library - the Railway Rivals map library and its web page.
* Extra tools  - race generator (path analyzer), invalid races, NW route trainer, Json map reader.
Hex labels and Rail Maps library are ordinary programs of the main tree (Py\\Hex_Labels.py,
Py\\Rail_Maps.py or Folder-exe\\<name>\\<name>.exe); the hub finds them by walking up from the
Railroad_racing folder.

IF A PROGRAM CLOSES AT ONCE
The hub tells you and offers to open Rail_files\\Logs, where the programs write their crash logs.

NEWEST MAPS
The four newest .json maps in Rail_files\\Maps (and its 0---Finished folder).  Double-click one to
see the file in its folder.

BUTTONS
Maps folder, Rail_files, Logs open those folders.  Manual opens the Map creator manual.
Notes is a small notepad of your own (saved by itself).  F1 = this Help.

SETTINGS (only if needed)  Helpfiles\\RailHub\\settings.json
  "rail_root"  the Railroad_racing folder, if the hub is not placed inside it.
  "python"     full path of the pythonw.exe to start the programs with.
Starting from a command line:  RailHub.py --root "X:\\...\\Railroad_racing"
"""

WHATS_NEW = """WHAT'S NEW

1.1  (2026-11-19)
  The "Picture tools" placeholder is now "Picture import" (Rail_import\\RailImport.py): turns a map
  picture into a Map creator .json.

1.0  (2026-11-19)
  First version: tiles for Map creator, Game central, Playpen, Hex labels, Rail Maps library and
  the four extra tools; ready / running / missing status; early-crash warning; newest maps list;
  folder buttons; Notes, Help, About.

COMING (plan: Railroad_racing_plan\\PLAN.md)
  Trace          show an ordinary map under the hex grid in Map creator and trace it, with
                   suggestions for terrain, sea and rivers.
  Better city numbers, special runs and texts.
  A "Rail Map Maker" edition for other people.
"""


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():
    cli_root = None
    args = sys.argv[1:]
    for i, a in enumerate(args):
        if a == "--root" and i + 1 < len(args):
            cli_root = args[i + 1]
    settings = load_json(SETTINGS_FILE, {})
    _set_app_id()                                   # BEFORE tk.Tk()
    root = tk.Tk()
    Hub(root, find_rail_root(cli_root, settings), settings)
    root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
    root.mainloop()


if __name__ == "__main__":
    main()
